Add names for mach-o permissions bits and use the symbol names in place of magic...
[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   // maxprot
189   Write32(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE); 
190   // initprot
191   Write32(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE); 
192   Write32(NumSections);
193   Write32(0); // flags
194
195   assert(OS.tell() - Start == SegmentLoadCommandSize);
196 }
197
198 void MachObjectWriter::WriteSection(const MCAssembler &Asm,
199                                     const MCAsmLayout &Layout,
200                                     const MCSectionData &SD,
201                                     uint64_t FileOffset,
202                                     uint64_t RelocationsStart,
203                                     unsigned NumRelocations) {
204   uint64_t SectionSize = Layout.getSectionAddressSize(&SD);
205
206   // The offset is unused for virtual sections.
207   if (SD.getSection().isVirtualSection()) {
208     assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
209     FileOffset = 0;
210   }
211
212   // struct section (68 bytes) or
213   // struct section_64 (80 bytes)
214
215   uint64_t Start = OS.tell();
216   (void) Start;
217
218   const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
219   WriteBytes(Section.getSectionName(), 16);
220   WriteBytes(Section.getSegmentName(), 16);
221   if (is64Bit()) {
222     Write64(getSectionAddress(&SD)); // address
223     Write64(SectionSize); // size
224   } else {
225     Write32(getSectionAddress(&SD)); // address
226     Write32(SectionSize); // size
227   }
228   Write32(FileOffset);
229
230   unsigned Flags = Section.getTypeAndAttributes();
231   if (SD.hasInstructions())
232     Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
233
234   assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
235   Write32(Log2_32(SD.getAlignment()));
236   Write32(NumRelocations ? RelocationsStart : 0);
237   Write32(NumRelocations);
238   Write32(Flags);
239   Write32(IndirectSymBase.lookup(&SD)); // reserved1
240   Write32(Section.getStubSize()); // reserved2
241   if (is64Bit())
242     Write32(0); // reserved3
243
244   assert(OS.tell() - Start == (is64Bit() ? sizeof(MachO::section_64) :
245                                sizeof(MachO::section)));
246 }
247
248 void MachObjectWriter::WriteSymtabLoadCommand(uint32_t SymbolOffset,
249                                               uint32_t NumSymbols,
250                                               uint32_t StringTableOffset,
251                                               uint32_t StringTableSize) {
252   // struct symtab_command (24 bytes)
253
254   uint64_t Start = OS.tell();
255   (void) Start;
256
257   Write32(MachO::LC_SYMTAB);
258   Write32(sizeof(MachO::symtab_command));
259   Write32(SymbolOffset);
260   Write32(NumSymbols);
261   Write32(StringTableOffset);
262   Write32(StringTableSize);
263
264   assert(OS.tell() - Start == sizeof(MachO::symtab_command));
265 }
266
267 void MachObjectWriter::WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
268                                                 uint32_t NumLocalSymbols,
269                                                 uint32_t FirstExternalSymbol,
270                                                 uint32_t NumExternalSymbols,
271                                                 uint32_t FirstUndefinedSymbol,
272                                                 uint32_t NumUndefinedSymbols,
273                                                 uint32_t IndirectSymbolOffset,
274                                                 uint32_t NumIndirectSymbols) {
275   // struct dysymtab_command (80 bytes)
276
277   uint64_t Start = OS.tell();
278   (void) Start;
279
280   Write32(MachO::LC_DYSYMTAB);
281   Write32(sizeof(MachO::dysymtab_command));
282   Write32(FirstLocalSymbol);
283   Write32(NumLocalSymbols);
284   Write32(FirstExternalSymbol);
285   Write32(NumExternalSymbols);
286   Write32(FirstUndefinedSymbol);
287   Write32(NumUndefinedSymbols);
288   Write32(0); // tocoff
289   Write32(0); // ntoc
290   Write32(0); // modtaboff
291   Write32(0); // nmodtab
292   Write32(0); // extrefsymoff
293   Write32(0); // nextrefsyms
294   Write32(IndirectSymbolOffset);
295   Write32(NumIndirectSymbols);
296   Write32(0); // extreloff
297   Write32(0); // nextrel
298   Write32(0); // locreloff
299   Write32(0); // nlocrel
300
301   assert(OS.tell() - Start == sizeof(MachO::dysymtab_command));
302 }
303
304 void MachObjectWriter::WriteNlist(MachSymbolData &MSD,
305                                   const MCAsmLayout &Layout) {
306   MCSymbolData &Data = *MSD.SymbolData;
307   const MCSymbol &Symbol = Data.getSymbol();
308   uint8_t Type = 0;
309   uint16_t Flags = Data.getFlags();
310   uint64_t Address = 0;
311
312   // Set the N_TYPE bits. See <mach-o/nlist.h>.
313   //
314   // FIXME: Are the prebound or indirect fields possible here?
315   if (Symbol.isUndefined())
316     Type = MachO::N_UNDF;
317   else if (Symbol.isAbsolute())
318     Type = MachO::N_ABS;
319   else
320     Type = MachO::N_SECT;
321
322   // FIXME: Set STAB bits.
323
324   if (Data.isPrivateExtern())
325     Type |= MachO::N_PEXT;
326
327   // Set external bit.
328   if (Data.isExternal() || Symbol.isUndefined())
329     Type |= MachO::N_EXT;
330
331   // Compute the symbol address.
332   if (Symbol.isDefined()) {
333     Address = getSymbolAddress(&Data, Layout);
334   } else if (Data.isCommon()) {
335     // Common symbols are encoded with the size in the address
336     // field, and their alignment in the flags.
337     Address = Data.getCommonSize();
338
339     // Common alignment is packed into the 'desc' bits.
340     if (unsigned Align = Data.getCommonAlignment()) {
341       unsigned Log2Size = Log2_32(Align);
342       assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
343       if (Log2Size > 15)
344         report_fatal_error("invalid 'common' alignment '" +
345                            Twine(Align) + "'");
346       // FIXME: Keep this mask with the SymbolFlags enumeration.
347       Flags = (Flags & 0xF0FF) | (Log2Size << 8);
348     }
349   }
350
351   // struct nlist (12 bytes)
352
353   Write32(MSD.StringIndex);
354   Write8(Type);
355   Write8(MSD.SectionIndex);
356
357   // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
358   // value.
359   Write16(Flags);
360   if (is64Bit())
361     Write64(Address);
362   else
363     Write32(Address);
364 }
365
366 void MachObjectWriter::WriteLinkeditLoadCommand(uint32_t Type,
367                                                 uint32_t DataOffset,
368                                                 uint32_t DataSize) {
369   uint64_t Start = OS.tell();
370   (void) Start;
371
372   Write32(Type);
373   Write32(sizeof(MachO::linkedit_data_command));
374   Write32(DataOffset);
375   Write32(DataSize);
376
377   assert(OS.tell() - Start == sizeof(MachO::linkedit_data_command));
378 }
379
380 static unsigned ComputeLinkerOptionsLoadCommandSize(
381   const std::vector<std::string> &Options, bool is64Bit)
382 {
383   unsigned Size = sizeof(MachO::linker_options_command);
384   for (unsigned i = 0, e = Options.size(); i != e; ++i)
385     Size += Options[i].size() + 1;
386   return RoundUpToAlignment(Size, is64Bit ? 8 : 4);
387 }
388
389 void MachObjectWriter::WriteLinkerOptionsLoadCommand(
390   const std::vector<std::string> &Options)
391 {
392   unsigned Size = ComputeLinkerOptionsLoadCommandSize(Options, is64Bit());
393   uint64_t Start = OS.tell();
394   (void) Start;
395
396   Write32(MachO::LC_LINKER_OPTIONS);
397   Write32(Size);
398   Write32(Options.size());
399   uint64_t BytesWritten = sizeof(MachO::linker_options_command);
400   for (unsigned i = 0, e = Options.size(); i != e; ++i) {
401     // Write each string, including the null byte.
402     const std::string &Option = Options[i];
403     WriteBytes(Option.c_str(), Option.size() + 1);
404     BytesWritten += Option.size() + 1;
405   }
406
407   // Pad to a multiple of the pointer size.
408   WriteBytes("", OffsetToAlignment(BytesWritten, is64Bit() ? 8 : 4));
409
410   assert(OS.tell() - Start == Size);
411 }
412
413
414 void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
415                                         const MCAsmLayout &Layout,
416                                         const MCFragment *Fragment,
417                                         const MCFixup &Fixup,
418                                         MCValue Target,
419                                         uint64_t &FixedValue) {
420   TargetObjectWriter->RecordRelocation(this, Asm, Layout, Fragment, Fixup,
421                                        Target, FixedValue);
422 }
423
424 void MachObjectWriter::BindIndirectSymbols(MCAssembler &Asm) {
425   // This is the point where 'as' creates actual symbols for indirect symbols
426   // (in the following two passes). It would be easier for us to do this sooner
427   // when we see the attribute, but that makes getting the order in the symbol
428   // table much more complicated than it is worth.
429   //
430   // FIXME: Revisit this when the dust settles.
431
432   // Report errors for use of .indirect_symbol not in a symbol pointer section
433   // or stub section.
434   for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
435          ie = Asm.indirect_symbol_end(); it != ie; ++it) {
436     const MCSectionMachO &Section =
437       cast<MCSectionMachO>(it->SectionData->getSection());
438
439     if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS &&
440         Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
441         Section.getType() != MCSectionMachO::S_SYMBOL_STUBS) {
442         MCSymbol &Symbol = *it->Symbol;
443         report_fatal_error("indirect symbol '" + Symbol.getName() +
444                            "' not in a symbol pointer or stub section");
445     }
446   }
447
448   // Bind non lazy symbol pointers first.
449   unsigned IndirectIndex = 0;
450   for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
451          ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
452     const MCSectionMachO &Section =
453       cast<MCSectionMachO>(it->SectionData->getSection());
454
455     if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
456       continue;
457
458     // Initialize the section indirect symbol base, if necessary.
459     IndirectSymBase.insert(std::make_pair(it->SectionData, IndirectIndex));
460
461     Asm.getOrCreateSymbolData(*it->Symbol);
462   }
463
464   // Then lazy symbol pointers and symbol stubs.
465   IndirectIndex = 0;
466   for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
467          ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
468     const MCSectionMachO &Section =
469       cast<MCSectionMachO>(it->SectionData->getSection());
470
471     if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
472         Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
473       continue;
474
475     // Initialize the section indirect symbol base, if necessary.
476     IndirectSymBase.insert(std::make_pair(it->SectionData, IndirectIndex));
477
478     // Set the symbol type to undefined lazy, but only on construction.
479     //
480     // FIXME: Do not hardcode.
481     bool Created;
482     MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
483     if (Created)
484       Entry.setFlags(Entry.getFlags() | 0x0001);
485   }
486 }
487
488 /// ComputeSymbolTable - Compute the symbol table data
489 ///
490 /// \param StringTable [out] - The string table data.
491 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
492 /// string table.
493 void MachObjectWriter::
494 ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
495                    std::vector<MachSymbolData> &LocalSymbolData,
496                    std::vector<MachSymbolData> &ExternalSymbolData,
497                    std::vector<MachSymbolData> &UndefinedSymbolData) {
498   // Build section lookup table.
499   DenseMap<const MCSection*, uint8_t> SectionIndexMap;
500   unsigned Index = 1;
501   for (MCAssembler::iterator it = Asm.begin(),
502          ie = Asm.end(); it != ie; ++it, ++Index)
503     SectionIndexMap[&it->getSection()] = Index;
504   assert(Index <= 256 && "Too many sections!");
505
506   // Index 0 is always the empty string.
507   StringMap<uint64_t> StringIndexMap;
508   StringTable += '\x00';
509
510   // Build the symbol arrays and the string table, but only for non-local
511   // symbols.
512   //
513   // The particular order that we collect the symbols and create the string
514   // table, then sort the symbols is chosen to match 'as'. Even though it
515   // doesn't matter for correctness, this is important for letting us diff .o
516   // files.
517   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
518          ie = Asm.symbol_end(); it != ie; ++it) {
519     const MCSymbol &Symbol = it->getSymbol();
520
521     // Ignore non-linker visible symbols.
522     if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
523       continue;
524
525     if (!it->isExternal() && !Symbol.isUndefined())
526       continue;
527
528     uint64_t &Entry = StringIndexMap[Symbol.getName()];
529     if (!Entry) {
530       Entry = StringTable.size();
531       StringTable += Symbol.getName();
532       StringTable += '\x00';
533     }
534
535     MachSymbolData MSD;
536     MSD.SymbolData = it;
537     MSD.StringIndex = Entry;
538
539     if (Symbol.isUndefined()) {
540       MSD.SectionIndex = 0;
541       UndefinedSymbolData.push_back(MSD);
542     } else if (Symbol.isAbsolute()) {
543       MSD.SectionIndex = 0;
544       ExternalSymbolData.push_back(MSD);
545     } else {
546       MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
547       assert(MSD.SectionIndex && "Invalid section index!");
548       ExternalSymbolData.push_back(MSD);
549     }
550   }
551
552   // Now add the data for local symbols.
553   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
554          ie = Asm.symbol_end(); it != ie; ++it) {
555     const MCSymbol &Symbol = it->getSymbol();
556
557     // Ignore non-linker visible symbols.
558     if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
559       continue;
560
561     if (it->isExternal() || Symbol.isUndefined())
562       continue;
563
564     uint64_t &Entry = StringIndexMap[Symbol.getName()];
565     if (!Entry) {
566       Entry = StringTable.size();
567       StringTable += Symbol.getName();
568       StringTable += '\x00';
569     }
570
571     MachSymbolData MSD;
572     MSD.SymbolData = it;
573     MSD.StringIndex = Entry;
574
575     if (Symbol.isAbsolute()) {
576       MSD.SectionIndex = 0;
577       LocalSymbolData.push_back(MSD);
578     } else {
579       MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
580       assert(MSD.SectionIndex && "Invalid section index!");
581       LocalSymbolData.push_back(MSD);
582     }
583   }
584
585   // External and undefined symbols are required to be in lexicographic order.
586   std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
587   std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
588
589   // Set the symbol indices.
590   Index = 0;
591   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
592     LocalSymbolData[i].SymbolData->setIndex(Index++);
593   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
594     ExternalSymbolData[i].SymbolData->setIndex(Index++);
595   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
596     UndefinedSymbolData[i].SymbolData->setIndex(Index++);
597
598   // The string table is padded to a multiple of 4.
599   while (StringTable.size() % 4)
600     StringTable += '\x00';
601 }
602
603 void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm,
604                                                const MCAsmLayout &Layout) {
605   uint64_t StartAddress = 0;
606   const SmallVectorImpl<MCSectionData*> &Order = Layout.getSectionOrder();
607   for (int i = 0, n = Order.size(); i != n ; ++i) {
608     const MCSectionData *SD = Order[i];
609     StartAddress = RoundUpToAlignment(StartAddress, SD->getAlignment());
610     SectionAddress[SD] = StartAddress;
611     StartAddress += Layout.getSectionAddressSize(SD);
612
613     // Explicitly pad the section to match the alignment requirements of the
614     // following one. This is for 'gas' compatibility, it shouldn't
615     /// strictly be necessary.
616     StartAddress += getPaddingSize(SD, Layout);
617   }
618 }
619
620 void MachObjectWriter::markAbsoluteVariableSymbols(MCAssembler &Asm,
621                                                    const MCAsmLayout &Layout) {
622   for (MCAssembler::symbol_iterator i = Asm.symbol_begin(),
623                                     e = Asm.symbol_end();
624       i != e; ++i) {
625     MCSymbolData &SD = *i;
626     if (!SD.getSymbol().isVariable())
627       continue;
628
629     // Is the variable is a symbol difference (SA - SB + C) expression,
630     // and neither symbol is external, mark the variable as absolute.
631     const MCExpr *Expr = SD.getSymbol().getVariableValue();
632     MCValue Value;
633     if (Expr->EvaluateAsRelocatable(Value, Layout)) {
634       if (Value.getSymA() && Value.getSymB())
635         const_cast<MCSymbol*>(&SD.getSymbol())->setAbsolute();
636     }
637   }
638 }
639
640 void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
641                                                 const MCAsmLayout &Layout) {
642   computeSectionAddresses(Asm, Layout);
643
644   // Create symbol data for any indirect symbols.
645   BindIndirectSymbols(Asm);
646
647   // Mark symbol difference expressions in variables (from .set or = directives)
648   // as absolute.
649   markAbsoluteVariableSymbols(Asm, Layout);
650
651   // Compute symbol table information and bind symbol indices.
652   ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
653                      UndefinedSymbolData);
654 }
655
656 bool MachObjectWriter::
657 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
658                                        const MCSymbolData &DataA,
659                                        const MCFragment &FB,
660                                        bool InSet,
661                                        bool IsPCRel) const {
662   if (InSet)
663     return true;
664
665   // The effective address is
666   //     addr(atom(A)) + offset(A)
667   //   - addr(atom(B)) - offset(B)
668   // and the offsets are not relocatable, so the fixup is fully resolved when
669   //  addr(atom(A)) - addr(atom(B)) == 0.
670   const MCSymbolData *A_Base = 0, *B_Base = 0;
671
672   const MCSymbol &SA = DataA.getSymbol().AliasedSymbol();
673   const MCSection &SecA = SA.getSection();
674   const MCSection &SecB = FB.getParent()->getSection();
675
676   if (IsPCRel) {
677     // The simple (Darwin, except on x86_64) way of dealing with this was to
678     // assume that any reference to a temporary symbol *must* be a temporary
679     // symbol in the same atom, unless the sections differ. Therefore, any PCrel
680     // relocation to a temporary symbol (in the same section) is fully
681     // resolved. This also works in conjunction with absolutized .set, which
682     // requires the compiler to use .set to absolutize the differences between
683     // symbols which the compiler knows to be assembly time constants, so we
684     // don't need to worry about considering symbol differences fully resolved.
685     //
686     // If the file isn't using sub-sections-via-symbols, we can make the
687     // same assumptions about any symbol that we normally make about
688     // assembler locals.
689
690     if (!Asm.getBackend().hasReliableSymbolDifference()) {
691       if (!SA.isInSection() || &SecA != &SecB ||
692           (!SA.isTemporary() &&
693            FB.getAtom() != Asm.getSymbolData(SA).getFragment()->getAtom() &&
694            Asm.getSubsectionsViaSymbols()))
695         return false;
696       return true;
697     }
698     // For Darwin x86_64, there is one special case when the reference IsPCRel.
699     // If the fragment with the reference does not have a base symbol but meets
700     // the simple way of dealing with this, in that it is a temporary symbol in
701     // the same atom then it is assumed to be fully resolved.  This is needed so
702     // a relocation entry is not created and so the static linker does not
703     // mess up the reference later.
704     else if(!FB.getAtom() &&
705             SA.isTemporary() && SA.isInSection() && &SecA == &SecB){
706       return true;
707     }
708   } else {
709     if (!TargetObjectWriter->useAggressiveSymbolFolding())
710       return false;
711   }
712
713   const MCFragment *FA = Asm.getSymbolData(SA).getFragment();
714
715   // Bail if the symbol has no fragment.
716   if (!FA)
717     return false;
718
719   A_Base = FA->getAtom();
720   if (!A_Base)
721     return false;
722
723   B_Base = FB.getAtom();
724   if (!B_Base)
725     return false;
726
727   // If the atoms are the same, they are guaranteed to have the same address.
728   if (A_Base == B_Base)
729     return true;
730
731   // Otherwise, we can't prove this is fully resolved.
732   return false;
733 }
734
735 void MachObjectWriter::WriteObject(MCAssembler &Asm,
736                                    const MCAsmLayout &Layout) {
737   unsigned NumSections = Asm.size();
738
739   // The section data starts after the header, the segment load command (and
740   // section headers) and the symbol table.
741   unsigned NumLoadCommands = 1;
742   uint64_t LoadCommandsSize = is64Bit() ?
743     sizeof(MachO::segment_command_64) + NumSections * sizeof(MachO::section_64):
744     sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section);
745
746   // Add the data-in-code load command size, if used.
747   unsigned NumDataRegions = Asm.getDataRegions().size();
748   if (NumDataRegions) {
749     ++NumLoadCommands;
750     LoadCommandsSize += sizeof(MachO::linkedit_data_command);
751   }
752
753   // Add the symbol table load command sizes, if used.
754   unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
755     UndefinedSymbolData.size();
756   if (NumSymbols) {
757     NumLoadCommands += 2;
758     LoadCommandsSize += (sizeof(MachO::symtab_command) +
759                          sizeof(MachO::dysymtab_command));
760   }
761
762   // Add the linker option load commands sizes.
763   const std::vector<std::vector<std::string> > &LinkerOptions =
764     Asm.getLinkerOptions();
765   for (unsigned i = 0, e = LinkerOptions.size(); i != e; ++i) {
766     ++NumLoadCommands;
767     LoadCommandsSize += ComputeLinkerOptionsLoadCommandSize(LinkerOptions[i],
768                                                             is64Bit());
769   }
770   
771   // Compute the total size of the section data, as well as its file size and vm
772   // size.
773   uint64_t SectionDataStart = (is64Bit() ? sizeof(MachO::mach_header_64) :
774                                sizeof(MachO::mach_header)) + LoadCommandsSize;
775   uint64_t SectionDataSize = 0;
776   uint64_t SectionDataFileSize = 0;
777   uint64_t VMSize = 0;
778   for (MCAssembler::const_iterator it = Asm.begin(),
779          ie = Asm.end(); it != ie; ++it) {
780     const MCSectionData &SD = *it;
781     uint64_t Address = getSectionAddress(&SD);
782     uint64_t Size = Layout.getSectionAddressSize(&SD);
783     uint64_t FileSize = Layout.getSectionFileSize(&SD);
784     FileSize += getPaddingSize(&SD, Layout);
785
786     VMSize = std::max(VMSize, Address + Size);
787
788     if (SD.getSection().isVirtualSection())
789       continue;
790
791     SectionDataSize = std::max(SectionDataSize, Address + Size);
792     SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
793   }
794
795   // The section data is padded to 4 bytes.
796   //
797   // FIXME: Is this machine dependent?
798   unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
799   SectionDataFileSize += SectionDataPadding;
800
801   // Write the prolog, starting with the header and load command...
802   WriteHeader(NumLoadCommands, LoadCommandsSize,
803               Asm.getSubsectionsViaSymbols());
804   WriteSegmentLoadCommand(NumSections, VMSize,
805                           SectionDataStart, SectionDataSize);
806
807   // ... and then the section headers.
808   uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
809   for (MCAssembler::const_iterator it = Asm.begin(),
810          ie = Asm.end(); it != ie; ++it) {
811     std::vector<MachO::any_relocation_info> &Relocs = Relocations[it];
812     unsigned NumRelocs = Relocs.size();
813     uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
814     WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
815     RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info);
816   }
817
818   // Write the data-in-code load command, if used.
819   uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
820   if (NumDataRegions) {
821     uint64_t DataRegionsOffset = RelocTableEnd;
822     uint64_t DataRegionsSize = NumDataRegions * 8;
823     WriteLinkeditLoadCommand(MachO::LC_DATA_IN_CODE, DataRegionsOffset,
824                              DataRegionsSize);
825   }
826
827   // Write the symbol table load command, if used.
828   if (NumSymbols) {
829     unsigned FirstLocalSymbol = 0;
830     unsigned NumLocalSymbols = LocalSymbolData.size();
831     unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
832     unsigned NumExternalSymbols = ExternalSymbolData.size();
833     unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
834     unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
835     unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
836     unsigned NumSymTabSymbols =
837       NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
838     uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
839     uint64_t IndirectSymbolOffset = 0;
840
841     // If used, the indirect symbols are written after the section data.
842     if (NumIndirectSymbols)
843       IndirectSymbolOffset = DataInCodeTableEnd;
844
845     // The symbol table is written after the indirect symbol data.
846     uint64_t SymbolTableOffset = DataInCodeTableEnd + IndirectSymbolSize;
847
848     // The string table is written after symbol table.
849     uint64_t StringTableOffset =
850       SymbolTableOffset + NumSymTabSymbols * (is64Bit() ?
851                                               sizeof(MachO::nlist_64) :
852                                               sizeof(MachO::nlist));
853     WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
854                            StringTableOffset, StringTable.size());
855
856     WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
857                              FirstExternalSymbol, NumExternalSymbols,
858                              FirstUndefinedSymbol, NumUndefinedSymbols,
859                              IndirectSymbolOffset, NumIndirectSymbols);
860   }
861
862   // Write the linker options load commands.
863   for (unsigned i = 0, e = LinkerOptions.size(); i != e; ++i) {
864     WriteLinkerOptionsLoadCommand(LinkerOptions[i]);
865   }
866
867   // Write the actual section data.
868   for (MCAssembler::const_iterator it = Asm.begin(),
869          ie = Asm.end(); it != ie; ++it) {
870     Asm.writeSectionData(it, Layout);
871
872     uint64_t Pad = getPaddingSize(it, Layout);
873     for (unsigned int i = 0; i < Pad; ++i)
874       Write8(0);
875   }
876
877   // Write the extra padding.
878   WriteZeros(SectionDataPadding);
879
880   // Write the relocation entries.
881   for (MCAssembler::const_iterator it = Asm.begin(),
882          ie = Asm.end(); it != ie; ++it) {
883     // Write the section relocation entries, in reverse order to match 'as'
884     // (approximately, the exact algorithm is more complicated than this).
885     std::vector<MachO::any_relocation_info> &Relocs = Relocations[it];
886     for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
887       Write32(Relocs[e - i - 1].r_word0);
888       Write32(Relocs[e - i - 1].r_word1);
889     }
890   }
891
892   // Write out the data-in-code region payload, if there is one.
893   for (MCAssembler::const_data_region_iterator
894          it = Asm.data_region_begin(), ie = Asm.data_region_end();
895          it != ie; ++it) {
896     const DataRegionData *Data = &(*it);
897     uint64_t Start =
898       getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->Start),
899                        Layout);
900     uint64_t End =
901       getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->End),
902                        Layout);
903     DEBUG(dbgs() << "data in code region-- kind: " << Data->Kind
904                  << "  start: " << Start << "(" << Data->Start->getName() << ")"
905                  << "  end: " << End << "(" << Data->End->getName() << ")"
906                  << "  size: " << End - Start
907                  << "\n");
908     Write32(Start);
909     Write16(End - Start);
910     Write16(Data->Kind);
911   }
912
913   // Write the symbol table data, if used.
914   if (NumSymbols) {
915     // Write the indirect symbol entries.
916     for (MCAssembler::const_indirect_symbol_iterator
917            it = Asm.indirect_symbol_begin(),
918            ie = Asm.indirect_symbol_end(); it != ie; ++it) {
919       // Indirect symbols in the non lazy symbol pointer section have some
920       // special handling.
921       const MCSectionMachO &Section =
922         static_cast<const MCSectionMachO&>(it->SectionData->getSection());
923       if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
924         // If this symbol is defined and internal, mark it as such.
925         if (it->Symbol->isDefined() &&
926             !Asm.getSymbolData(*it->Symbol).isExternal()) {
927           uint32_t Flags = MachO::INDIRECT_SYMBOL_LOCAL;
928           if (it->Symbol->isAbsolute())
929             Flags |= MachO::INDIRECT_SYMBOL_ABS;
930           Write32(Flags);
931           continue;
932         }
933       }
934
935       Write32(Asm.getSymbolData(*it->Symbol).getIndex());
936     }
937
938     // FIXME: Check that offsets match computed ones.
939
940     // Write the symbol table entries.
941     for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
942       WriteNlist(LocalSymbolData[i], Layout);
943     for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
944       WriteNlist(ExternalSymbolData[i], Layout);
945     for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
946       WriteNlist(UndefinedSymbolData[i], Layout);
947
948     // Write the string table.
949     OS << StringTable.str();
950   }
951 }
952
953 MCObjectWriter *llvm::createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
954                                              raw_ostream &OS,
955                                              bool IsLittleEndian) {
956   return new MachObjectWriter(MOTW, OS, IsLittleEndian);
957 }