Move everything depending on Object/MachOFormat.h over to Support/MachO.h.
[oota-llvm.git] / lib / MC / MachObjectWriter.cpp
1 //===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
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"
26 #include <vector>
27 using namespace llvm;
28
29 void MachObjectWriter::reset() {
30   Relocations.clear();
31   IndirectSymBase.clear();
32   StringTable.clear();
33   LocalSymbolData.clear();
34   ExternalSymbolData.clear();
35   UndefinedSymbolData.clear();
36   MCObjectWriter::reset();
37 }
38
39 bool MachObjectWriter::
40 doesSymbolRequireExternRelocation(const MCSymbolData *SD) {
41   // Undefined symbols are always extern.
42   if (SD->Symbol->isUndefined())
43     return true;
44
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)
48     return true;
49
50   // Otherwise, we can use an internal relocation.
51   return false;
52 }
53
54 bool MachObjectWriter::
55 MachSymbolData::operator<(const MachSymbolData &RHS) const {
56   return SymbolData->getSymbol().getName() <
57     RHS.SymbolData->getSymbol().getName();
58 }
59
60 bool MachObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
61   const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
62     (MCFixupKind) Kind);
63
64   return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
65 }
66
67 uint64_t MachObjectWriter::getFragmentAddress(const MCFragment *Fragment,
68                                               const MCAsmLayout &Layout) const {
69   return getSectionAddress(Fragment->getParent()) +
70     Layout.getFragmentOffset(Fragment);
71 }
72
73 uint64_t MachObjectWriter::getSymbolAddress(const MCSymbolData* SD,
74                                             const MCAsmLayout &Layout) const {
75   const MCSymbol &S = SD->getSymbol();
76
77   // If this is a variable, then recursively evaluate now.
78   if (S.isVariable()) {
79     if (const MCConstantExpr *C =
80           dyn_cast<const MCConstantExpr>(S.getVariableValue()))
81       return C->getValue();
82
83
84     MCValue Target;
85     if (!S.getVariableValue()->EvaluateAsRelocatable(Target, Layout))
86       report_fatal_error("unable to evaluate offset for variable '" +
87                          S.getName() + "'");
88
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() + "'");
96
97     uint64_t Address = Target.getConstant();
98     if (Target.getSymA())
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);
104     return Address;
105   }
106
107   return getSectionAddress(SD->getFragment()->getParent()) +
108     Layout.getSymbolOffset(SD);
109 }
110
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())
116     return 0;
117
118   const MCSectionData &NextSD = *Layout.getSectionOrder()[Next];
119   if (NextSD.getSection().isVirtualSection())
120     return 0;
121   return OffsetToAlignment(EndAddr, NextSD.getAlignment());
122 }
123
124 void MachObjectWriter::WriteHeader(unsigned NumLoadCommands,
125                                    unsigned LoadCommandsSize,
126                                    bool SubsectionsViaSymbols) {
127   uint32_t Flags = 0;
128
129   if (SubsectionsViaSymbols)
130     Flags |= MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
131
132   // struct mach_header (28 bytes) or
133   // struct mach_header_64 (32 bytes)
134
135   uint64_t Start = OS.tell();
136   (void) Start;
137
138   Write32(is64Bit() ? MachO::MH_MAGIC_64 : MachO::MH_MAGIC);
139
140   Write32(TargetObjectWriter->getCPUType());
141   Write32(TargetObjectWriter->getCPUSubtype());
142
143   Write32(MachO::MH_OBJECT);
144   Write32(NumLoadCommands);
145   Write32(LoadCommandsSize);
146   Write32(Flags);
147   if (is64Bit())
148     Write32(0); // reserved
149
150   assert(OS.tell() - Start ==
151          (is64Bit()?sizeof(MachO::mach_header_64): sizeof(MachO::mach_header)));
152 }
153
154 /// WriteSegmentLoadCommand - Write a segment load command.
155 ///
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,
159                                                uint64_t VMSize,
160                                                uint64_t SectionDataStartOffset,
161                                                uint64_t SectionDataSize) {
162   // struct segment_command (56 bytes) or
163   // struct segment_command_64 (72 bytes)
164
165   uint64_t Start = OS.tell();
166   (void) Start;
167
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)));
175
176   WriteBytes("", 16);
177   if (is64Bit()) {
178     Write64(0); // vmaddr
179     Write64(VMSize); // vmsize
180     Write64(SectionDataStartOffset); // file offset
181     Write64(SectionDataSize); // file size
182   } else {
183     Write32(0); // vmaddr
184     Write32(VMSize); // vmsize
185     Write32(SectionDataStartOffset); // file offset
186     Write32(SectionDataSize); // file size
187   }
188   Write32(0x7); // maxprot
189   Write32(0x7); // initprot
190   Write32(NumSections);
191   Write32(0); // flags
192
193   assert(OS.tell() - Start == SegmentLoadCommandSize);
194 }
195
196 void MachObjectWriter::WriteSection(const MCAssembler &Asm,
197                                     const MCAsmLayout &Layout,
198                                     const MCSectionData &SD,
199                                     uint64_t FileOffset,
200                                     uint64_t RelocationsStart,
201                                     unsigned NumRelocations) {
202   uint64_t SectionSize = Layout.getSectionAddressSize(&SD);
203
204   // The offset is unused for virtual sections.
205   if (SD.getSection().isVirtualSection()) {
206     assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
207     FileOffset = 0;
208   }
209
210   // struct section (68 bytes) or
211   // struct section_64 (80 bytes)
212
213   uint64_t Start = OS.tell();
214   (void) Start;
215
216   const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
217   WriteBytes(Section.getSectionName(), 16);
218   WriteBytes(Section.getSegmentName(), 16);
219   if (is64Bit()) {
220     Write64(getSectionAddress(&SD)); // address
221     Write64(SectionSize); // size
222   } else {
223     Write32(getSectionAddress(&SD)); // address
224     Write32(SectionSize); // size
225   }
226   Write32(FileOffset);
227
228   unsigned Flags = Section.getTypeAndAttributes();
229   if (SD.hasInstructions())
230     Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
231
232   assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
233   Write32(Log2_32(SD.getAlignment()));
234   Write32(NumRelocations ? RelocationsStart : 0);
235   Write32(NumRelocations);
236   Write32(Flags);
237   Write32(IndirectSymBase.lookup(&SD)); // reserved1
238   Write32(Section.getStubSize()); // reserved2
239   if (is64Bit())
240     Write32(0); // reserved3
241
242   assert(OS.tell() - Start == (is64Bit() ? sizeof(MachO::section_64) :
243                                sizeof(MachO::section)));
244 }
245
246 void MachObjectWriter::WriteSymtabLoadCommand(uint32_t SymbolOffset,
247                                               uint32_t NumSymbols,
248                                               uint32_t StringTableOffset,
249                                               uint32_t StringTableSize) {
250   // struct symtab_command (24 bytes)
251
252   uint64_t Start = OS.tell();
253   (void) Start;
254
255   Write32(MachO::LC_SYMTAB);
256   Write32(sizeof(MachO::symtab_command));
257   Write32(SymbolOffset);
258   Write32(NumSymbols);
259   Write32(StringTableOffset);
260   Write32(StringTableSize);
261
262   assert(OS.tell() - Start == sizeof(MachO::symtab_command));
263 }
264
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)
274
275   uint64_t Start = OS.tell();
276   (void) Start;
277
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
287   Write32(0); // ntoc
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
298
299   assert(OS.tell() - Start == sizeof(MachO::dysymtab_command));
300 }
301
302 void MachObjectWriter::WriteNlist(MachSymbolData &MSD,
303                                   const MCAsmLayout &Layout) {
304   MCSymbolData &Data = *MSD.SymbolData;
305   const MCSymbol &Symbol = Data.getSymbol();
306   uint8_t Type = 0;
307   uint16_t Flags = Data.getFlags();
308   uint64_t Address = 0;
309
310   // Set the N_TYPE bits. See <mach-o/nlist.h>.
311   //
312   // FIXME: Are the prebound or indirect fields possible here?
313   if (Symbol.isUndefined())
314     Type = MachO::N_UNDF;
315   else if (Symbol.isAbsolute())
316     Type = MachO::N_ABS;
317   else
318     Type = MachO::N_SECT;
319
320   // FIXME: Set STAB bits.
321
322   if (Data.isPrivateExtern())
323     Type |= MachO::N_PEXT;
324
325   // Set external bit.
326   if (Data.isExternal() || Symbol.isUndefined())
327     Type |= MachO::N_EXT;
328
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();
336
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!");
341       if (Log2Size > 15)
342         report_fatal_error("invalid 'common' alignment '" +
343                            Twine(Align) + "'");
344       // FIXME: Keep this mask with the SymbolFlags enumeration.
345       Flags = (Flags & 0xF0FF) | (Log2Size << 8);
346     }
347   }
348
349   // struct nlist (12 bytes)
350
351   Write32(MSD.StringIndex);
352   Write8(Type);
353   Write8(MSD.SectionIndex);
354
355   // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
356   // value.
357   Write16(Flags);
358   if (is64Bit())
359     Write64(Address);
360   else
361     Write32(Address);
362 }
363
364 void MachObjectWriter::WriteLinkeditLoadCommand(uint32_t Type,
365                                                 uint32_t DataOffset,
366                                                 uint32_t DataSize) {
367   uint64_t Start = OS.tell();
368   (void) Start;
369
370   Write32(Type);
371   Write32(sizeof(MachO::linkedit_data_command));
372   Write32(DataOffset);
373   Write32(DataSize);
374
375   assert(OS.tell() - Start == sizeof(MachO::linkedit_data_command));
376 }
377
378 static unsigned ComputeLinkerOptionsLoadCommandSize(
379   const std::vector<std::string> &Options, bool is64Bit)
380 {
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);
385 }
386
387 void MachObjectWriter::WriteLinkerOptionsLoadCommand(
388   const std::vector<std::string> &Options)
389 {
390   unsigned Size = ComputeLinkerOptionsLoadCommandSize(Options, is64Bit());
391   uint64_t Start = OS.tell();
392   (void) Start;
393
394   Write32(MachO::LC_LINKER_OPTIONS);
395   Write32(Size);
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;
403   }
404
405   // Pad to a multiple of the pointer size.
406   WriteBytes("", OffsetToAlignment(BytesWritten, is64Bit() ? 8 : 4));
407
408   assert(OS.tell() - Start == Size);
409 }
410
411
412 void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
413                                         const MCAsmLayout &Layout,
414                                         const MCFragment *Fragment,
415                                         const MCFixup &Fixup,
416                                         MCValue Target,
417                                         uint64_t &FixedValue) {
418   TargetObjectWriter->RecordRelocation(this, Asm, Layout, Fragment, Fixup,
419                                        Target, FixedValue);
420 }
421
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.
427   //
428   // FIXME: Revisit this when the dust settles.
429
430   // Report errors for use of .indirect_symbol not in a symbol pointer section
431   // or stub 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());
436
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");
443     }
444   }
445
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());
452
453     if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
454       continue;
455
456     // Initialize the section indirect symbol base, if necessary.
457     IndirectSymBase.insert(std::make_pair(it->SectionData, IndirectIndex));
458
459     Asm.getOrCreateSymbolData(*it->Symbol);
460   }
461
462   // Then lazy symbol pointers and symbol stubs.
463   IndirectIndex = 0;
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());
468
469     if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
470         Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
471       continue;
472
473     // Initialize the section indirect symbol base, if necessary.
474     IndirectSymBase.insert(std::make_pair(it->SectionData, IndirectIndex));
475
476     // Set the symbol type to undefined lazy, but only on construction.
477     //
478     // FIXME: Do not hardcode.
479     bool Created;
480     MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
481     if (Created)
482       Entry.setFlags(Entry.getFlags() | 0x0001);
483   }
484 }
485
486 /// ComputeSymbolTable - Compute the symbol table data
487 ///
488 /// \param StringTable [out] - The string table data.
489 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
490 /// string table.
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;
498   unsigned Index = 1;
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!");
503
504   // Index 0 is always the empty string.
505   StringMap<uint64_t> StringIndexMap;
506   StringTable += '\x00';
507
508   // Build the symbol arrays and the string table, but only for non-local
509   // symbols.
510   //
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
514   // files.
515   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
516          ie = Asm.symbol_end(); it != ie; ++it) {
517     const MCSymbol &Symbol = it->getSymbol();
518
519     // Ignore non-linker visible symbols.
520     if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
521       continue;
522
523     if (!it->isExternal() && !Symbol.isUndefined())
524       continue;
525
526     uint64_t &Entry = StringIndexMap[Symbol.getName()];
527     if (!Entry) {
528       Entry = StringTable.size();
529       StringTable += Symbol.getName();
530       StringTable += '\x00';
531     }
532
533     MachSymbolData MSD;
534     MSD.SymbolData = it;
535     MSD.StringIndex = Entry;
536
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);
543     } else {
544       MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
545       assert(MSD.SectionIndex && "Invalid section index!");
546       ExternalSymbolData.push_back(MSD);
547     }
548   }
549
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();
554
555     // Ignore non-linker visible symbols.
556     if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
557       continue;
558
559     if (it->isExternal() || Symbol.isUndefined())
560       continue;
561
562     uint64_t &Entry = StringIndexMap[Symbol.getName()];
563     if (!Entry) {
564       Entry = StringTable.size();
565       StringTable += Symbol.getName();
566       StringTable += '\x00';
567     }
568
569     MachSymbolData MSD;
570     MSD.SymbolData = it;
571     MSD.StringIndex = Entry;
572
573     if (Symbol.isAbsolute()) {
574       MSD.SectionIndex = 0;
575       LocalSymbolData.push_back(MSD);
576     } else {
577       MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
578       assert(MSD.SectionIndex && "Invalid section index!");
579       LocalSymbolData.push_back(MSD);
580     }
581   }
582
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());
586
587   // Set the symbol indices.
588   Index = 0;
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++);
595
596   // The string table is padded to a multiple of 4.
597   while (StringTable.size() % 4)
598     StringTable += '\x00';
599 }
600
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);
610
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);
615   }
616 }
617
618 void MachObjectWriter::markAbsoluteVariableSymbols(MCAssembler &Asm,
619                                                    const MCAsmLayout &Layout) {
620   for (MCAssembler::symbol_iterator i = Asm.symbol_begin(),
621                                     e = Asm.symbol_end();
622       i != e; ++i) {
623     MCSymbolData &SD = *i;
624     if (!SD.getSymbol().isVariable())
625       continue;
626
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();
630     MCValue Value;
631     if (Expr->EvaluateAsRelocatable(Value, Layout)) {
632       if (Value.getSymA() && Value.getSymB())
633         const_cast<MCSymbol*>(&SD.getSymbol())->setAbsolute();
634     }
635   }
636 }
637
638 void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
639                                                 const MCAsmLayout &Layout) {
640   computeSectionAddresses(Asm, Layout);
641
642   // Create symbol data for any indirect symbols.
643   BindIndirectSymbols(Asm);
644
645   // Mark symbol difference expressions in variables (from .set or = directives)
646   // as absolute.
647   markAbsoluteVariableSymbols(Asm, Layout);
648
649   // Compute symbol table information and bind symbol indices.
650   ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
651                      UndefinedSymbolData);
652 }
653
654 bool MachObjectWriter::
655 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
656                                        const MCSymbolData &DataA,
657                                        const MCFragment &FB,
658                                        bool InSet,
659                                        bool IsPCRel) const {
660   if (InSet)
661     return true;
662
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;
669
670   const MCSymbol &SA = DataA.getSymbol().AliasedSymbol();
671   const MCSection &SecA = SA.getSection();
672   const MCSection &SecB = FB.getParent()->getSection();
673
674   if (IsPCRel) {
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.
683     //
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
686     // assembler locals.
687
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()))
693         return false;
694       return true;
695     }
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){
704       return true;
705     }
706   } else {
707     if (!TargetObjectWriter->useAggressiveSymbolFolding())
708       return false;
709   }
710
711   const MCFragment *FA = Asm.getSymbolData(SA).getFragment();
712
713   // Bail if the symbol has no fragment.
714   if (!FA)
715     return false;
716
717   A_Base = FA->getAtom();
718   if (!A_Base)
719     return false;
720
721   B_Base = FB.getAtom();
722   if (!B_Base)
723     return false;
724
725   // If the atoms are the same, they are guaranteed to have the same address.
726   if (A_Base == B_Base)
727     return true;
728
729   // Otherwise, we can't prove this is fully resolved.
730   return false;
731 }
732
733 void MachObjectWriter::WriteObject(MCAssembler &Asm,
734                                    const MCAsmLayout &Layout) {
735   unsigned NumSections = Asm.size();
736
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);
743
744   // Add the data-in-code load command size, if used.
745   unsigned NumDataRegions = Asm.getDataRegions().size();
746   if (NumDataRegions) {
747     ++NumLoadCommands;
748     LoadCommandsSize += sizeof(MachO::linkedit_data_command);
749   }
750
751   // Add the symbol table load command sizes, if used.
752   unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
753     UndefinedSymbolData.size();
754   if (NumSymbols) {
755     NumLoadCommands += 2;
756     LoadCommandsSize += (sizeof(MachO::symtab_command) +
757                          sizeof(MachO::dysymtab_command));
758   }
759
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) {
764     ++NumLoadCommands;
765     LoadCommandsSize += ComputeLinkerOptionsLoadCommandSize(LinkerOptions[i],
766                                                             is64Bit());
767   }
768   
769   // Compute the total size of the section data, as well as its file size and vm
770   // size.
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;
775   uint64_t VMSize = 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);
783
784     VMSize = std::max(VMSize, Address + Size);
785
786     if (SD.getSection().isVirtualSection())
787       continue;
788
789     SectionDataSize = std::max(SectionDataSize, Address + Size);
790     SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
791   }
792
793   // The section data is padded to 4 bytes.
794   //
795   // FIXME: Is this machine dependent?
796   unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
797   SectionDataFileSize += SectionDataPadding;
798
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);
804
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);
814   }
815
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,
822                              DataRegionsSize);
823   }
824
825   // Write the symbol table load command, if used.
826   if (NumSymbols) {
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;
838
839     // If used, the indirect symbols are written after the section data.
840     if (NumIndirectSymbols)
841       IndirectSymbolOffset = DataInCodeTableEnd;
842
843     // The symbol table is written after the indirect symbol data.
844     uint64_t SymbolTableOffset = DataInCodeTableEnd + IndirectSymbolSize;
845
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());
853
854     WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
855                              FirstExternalSymbol, NumExternalSymbols,
856                              FirstUndefinedSymbol, NumUndefinedSymbols,
857                              IndirectSymbolOffset, NumIndirectSymbols);
858   }
859
860   // Write the linker options load commands.
861   for (unsigned i = 0, e = LinkerOptions.size(); i != e; ++i) {
862     WriteLinkerOptionsLoadCommand(LinkerOptions[i]);
863   }
864
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);
869
870     uint64_t Pad = getPaddingSize(it, Layout);
871     for (unsigned int i = 0; i < Pad; ++i)
872       Write8(0);
873   }
874
875   // Write the extra padding.
876   WriteZeros(SectionDataPadding);
877
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);
887     }
888   }
889
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();
893          it != ie; ++it) {
894     const DataRegionData *Data = &(*it);
895     uint64_t Start =
896       getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->Start),
897                        Layout);
898     uint64_t End =
899       getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->End),
900                        Layout);
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
905                  << "\n");
906     Write32(Start);
907     Write16(End - Start);
908     Write16(Data->Kind);
909   }
910
911   // Write the symbol table data, if used.
912   if (NumSymbols) {
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
918       // special handling.
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;
928           Write32(Flags);
929           continue;
930         }
931       }
932
933       Write32(Asm.getSymbolData(*it->Symbol).getIndex());
934     }
935
936     // FIXME: Check that offsets match computed ones.
937
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);
945
946     // Write the string table.
947     OS << StringTable.str();
948   }
949 }
950
951 MCObjectWriter *llvm::createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
952                                              raw_ostream &OS,
953                                              bool IsLittleEndian) {
954   return new MachObjectWriter(MOTW, OS, IsLittleEndian);
955 }