1 //===- MCMachOStreamer.cpp - MachO Streamer -------------------------------===//
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/ADT/DenseMap.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/MC/MCAsmBackend.h"
16 #include "llvm/MC/MCAssembler.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCDirectives.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCFixup.h"
22 #include "llvm/MC/MCFragment.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCLinkerOptimizationHint.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCObjectStreamer.h"
27 #include "llvm/MC/MCSection.h"
28 #include "llvm/MC/MCSectionMachO.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCSymbolMachO.h"
32 #include "llvm/MC/MCValue.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <cassert>
38 #include <vector>
39 
40 using namespace llvm;
41 
42 namespace {
43 
44 class MCMachOStreamer : public MCObjectStreamer {
45 private:
46   /// LabelSections - true if each section change should emit a linker local
47   /// label for use in relocations for assembler local references. Obviates the
48   /// need for local relocations. False by default.
49   bool LabelSections;
50 
51   bool DWARFMustBeAtTheEnd;
52   bool CreatedADWARFSection;
53 
54   /// HasSectionLabel - map of which sections have already had a non-local
55   /// label emitted to them. Used so we don't emit extraneous linker local
56   /// labels in the middle of the section.
57   DenseMap<const MCSection*, bool> HasSectionLabel;
58 
59   void EmitInstToData(const MCInst &Inst, const MCSubtargetInfo &STI) override;
60 
61   void EmitDataRegion(DataRegionData::KindTy Kind);
62   void EmitDataRegionEnd();
63 
64 public:
65   MCMachOStreamer(MCContext &Context, std::unique_ptr<MCAsmBackend> MAB,
66                   raw_pwrite_stream &OS, std::unique_ptr<MCCodeEmitter> Emitter,
67                   bool DWARFMustBeAtTheEnd, bool label)
68       : MCObjectStreamer(Context, std::move(MAB), OS, std::move(Emitter)),
69         LabelSections(label), DWARFMustBeAtTheEnd(DWARFMustBeAtTheEnd),
70         CreatedADWARFSection(false) {}
71 
72   /// state management
73   void reset() override {
74     CreatedADWARFSection = false;
75     HasSectionLabel.clear();
76     MCObjectStreamer::reset();
77   }
78 
79   /// @name MCStreamer Interface
80   /// @{
81 
82   void ChangeSection(MCSection *Sect, const MCExpr *Subsect) override;
83   void EmitLabel(MCSymbol *Symbol, SMLoc Loc = SMLoc()) override;
84   void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) override;
85   void EmitEHSymAttributes(const MCSymbol *Symbol, MCSymbol *EHSymbol) override;
86   void EmitAssemblerFlag(MCAssemblerFlag Flag) override;
87   void EmitLinkerOptions(ArrayRef<std::string> Options) override;
88   void EmitDataRegion(MCDataRegionType Kind) override;
89   void EmitVersionMin(MCVersionMinType Kind, unsigned Major,
90                       unsigned Minor, unsigned Update) override;
91   void EmitThumbFunc(MCSymbol *Func) override;
92   bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
93   void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
94   void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
95                         unsigned ByteAlignment) override;
96 
97   void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
98                              unsigned ByteAlignment) override;
99   void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
100                     uint64_t Size = 0, unsigned ByteAlignment = 0) override;
101   void EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
102                       unsigned ByteAlignment = 0) override;
103 
104   void EmitIdent(StringRef IdentString) override {
105     llvm_unreachable("macho doesn't support this directive");
106   }
107 
108   void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override {
109     getAssembler().getLOHContainer().addDirective(Kind, Args);
110   }
111 
112   void FinishImpl() override;
113 };
114 
115 } // end anonymous namespace.
116 
117 static bool canGoAfterDWARF(const MCSectionMachO &MSec) {
118   // These sections are created by the assembler itself after the end of
119   // the .s file.
120   StringRef SegName = MSec.getSegmentName();
121   StringRef SecName = MSec.getSectionName();
122 
123   if (SegName == "__LD" && SecName == "__compact_unwind")
124     return true;
125 
126   if (SegName == "__IMPORT") {
127     if (SecName == "__jump_table")
128       return true;
129 
130     if (SecName == "__pointers")
131       return true;
132   }
133 
134   if (SegName == "__TEXT" && SecName == "__eh_frame")
135     return true;
136 
137   if (SegName == "__DATA" && (SecName == "__nl_symbol_ptr" ||
138                               SecName == "__thread_ptr"))
139     return true;
140 
141   return false;
142 }
143 
144 void MCMachOStreamer::ChangeSection(MCSection *Section,
145                                     const MCExpr *Subsection) {
146   // Change the section normally.
147   bool Created = changeSectionImpl(Section, Subsection);
148   const MCSectionMachO &MSec = *cast<MCSectionMachO>(Section);
149   StringRef SegName = MSec.getSegmentName();
150   if (SegName == "__DWARF")
151     CreatedADWARFSection = true;
152   else if (Created && DWARFMustBeAtTheEnd && !canGoAfterDWARF(MSec))
153     assert(!CreatedADWARFSection && "Creating regular section after DWARF");
154 
155   // Output a linker-local symbol so we don't need section-relative local
156   // relocations. The linker hates us when we do that.
157   if (LabelSections && !HasSectionLabel[Section] &&
158       !Section->getBeginSymbol()) {
159     MCSymbol *Label = getContext().createLinkerPrivateTempSymbol();
160     Section->setBeginSymbol(Label);
161     HasSectionLabel[Section] = true;
162   }
163 }
164 
165 void MCMachOStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
166                                           MCSymbol *EHSymbol) {
167   getAssembler().registerSymbol(*Symbol);
168   if (Symbol->isExternal())
169     EmitSymbolAttribute(EHSymbol, MCSA_Global);
170   if (cast<MCSymbolMachO>(Symbol)->isWeakDefinition())
171     EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
172   if (Symbol->isPrivateExtern())
173     EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
174 }
175 
176 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol, SMLoc Loc) {
177   // We have to create a new fragment if this is an atom defining symbol,
178   // fragments cannot span atoms.
179   if (getAssembler().isSymbolLinkerVisible(*Symbol))
180     insert(new MCDataFragment());
181 
182   MCObjectStreamer::EmitLabel(Symbol, Loc);
183 
184   // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
185   // to clear the weak reference and weak definition bits too, but the
186   // implementation was buggy. For now we just try to match 'as', for
187   // diffability.
188   //
189   // FIXME: Cleanup this code, these bits should be emitted based on semantic
190   // properties, not on the order of definition, etc.
191   cast<MCSymbolMachO>(Symbol)->clearReferenceType();
192 }
193 
194 void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
195   MCValue Res;
196 
197   if (Value->evaluateAsRelocatable(Res, nullptr, nullptr)) {
198     if (const MCSymbolRefExpr *SymAExpr = Res.getSymA()) {
199       const MCSymbol &SymA = SymAExpr->getSymbol();
200       if (!Res.getSymB() && (SymA.getName() == "" || Res.getConstant() != 0))
201         cast<MCSymbolMachO>(Symbol)->setAltEntry();
202     }
203   }
204   MCObjectStreamer::EmitAssignment(Symbol, Value);
205 }
206 
207 void MCMachOStreamer::EmitDataRegion(DataRegionData::KindTy Kind) {
208   // Create a temporary label to mark the start of the data region.
209   MCSymbol *Start = getContext().createTempSymbol();
210   EmitLabel(Start);
211   // Record the region for the object writer to use.
212   DataRegionData Data = { Kind, Start, nullptr };
213   std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
214   Regions.push_back(Data);
215 }
216 
217 void MCMachOStreamer::EmitDataRegionEnd() {
218   std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
219   assert(!Regions.empty() && "Mismatched .end_data_region!");
220   DataRegionData &Data = Regions.back();
221   assert(!Data.End && "Mismatched .end_data_region!");
222   // Create a temporary label to mark the end of the data region.
223   Data.End = getContext().createTempSymbol();
224   EmitLabel(Data.End);
225 }
226 
227 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
228   // Let the target do whatever target specific stuff it needs to do.
229   getAssembler().getBackend().handleAssemblerFlag(Flag);
230   // Do any generic stuff we need to do.
231   switch (Flag) {
232   case MCAF_SyntaxUnified: return; // no-op here.
233   case MCAF_Code16: return; // Change parsing mode; no-op here.
234   case MCAF_Code32: return; // Change parsing mode; no-op here.
235   case MCAF_Code64: return; // Change parsing mode; no-op here.
236   case MCAF_SubsectionsViaSymbols:
237     getAssembler().setSubsectionsViaSymbols(true);
238     return;
239   }
240 }
241 
242 void MCMachOStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
243   getAssembler().getLinkerOptions().push_back(Options);
244 }
245 
246 void MCMachOStreamer::EmitDataRegion(MCDataRegionType Kind) {
247   switch (Kind) {
248   case MCDR_DataRegion:
249     EmitDataRegion(DataRegionData::Data);
250     return;
251   case MCDR_DataRegionJT8:
252     EmitDataRegion(DataRegionData::JumpTable8);
253     return;
254   case MCDR_DataRegionJT16:
255     EmitDataRegion(DataRegionData::JumpTable16);
256     return;
257   case MCDR_DataRegionJT32:
258     EmitDataRegion(DataRegionData::JumpTable32);
259     return;
260   case MCDR_DataRegionEnd:
261     EmitDataRegionEnd();
262     return;
263   }
264 }
265 
266 void MCMachOStreamer::EmitVersionMin(MCVersionMinType Kind, unsigned Major,
267                                      unsigned Minor, unsigned Update) {
268   getAssembler().setVersionMinInfo(Kind, Major, Minor, Update);
269 }
270 
271 void MCMachOStreamer::EmitThumbFunc(MCSymbol *Symbol) {
272   // Remember that the function is a thumb function. Fixup and relocation
273   // values will need adjusted.
274   getAssembler().setIsThumbFunc(Symbol);
275   cast<MCSymbolMachO>(Symbol)->setThumbFunc();
276 }
277 
278 bool MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Sym,
279                                           MCSymbolAttr Attribute) {
280   MCSymbolMachO *Symbol = cast<MCSymbolMachO>(Sym);
281 
282   // Indirect symbols are handled differently, to match how 'as' handles
283   // them. This makes writing matching .o files easier.
284   if (Attribute == MCSA_IndirectSymbol) {
285     // Note that we intentionally cannot use the symbol data here; this is
286     // important for matching the string table that 'as' generates.
287     IndirectSymbolData ISD;
288     ISD.Symbol = Symbol;
289     ISD.Section = getCurrentSectionOnly();
290     getAssembler().getIndirectSymbols().push_back(ISD);
291     return true;
292   }
293 
294   // Adding a symbol attribute always introduces the symbol, note that an
295   // important side effect of calling registerSymbol here is to register
296   // the symbol with the assembler.
297   getAssembler().registerSymbol(*Symbol);
298 
299   // The implementation of symbol attributes is designed to match 'as', but it
300   // leaves much to desired. It doesn't really make sense to arbitrarily add and
301   // remove flags, but 'as' allows this (in particular, see .desc).
302   //
303   // In the future it might be worth trying to make these operations more well
304   // defined.
305   switch (Attribute) {
306   case MCSA_Invalid:
307   case MCSA_ELF_TypeFunction:
308   case MCSA_ELF_TypeIndFunction:
309   case MCSA_ELF_TypeObject:
310   case MCSA_ELF_TypeTLS:
311   case MCSA_ELF_TypeCommon:
312   case MCSA_ELF_TypeNoType:
313   case MCSA_ELF_TypeGnuUniqueObject:
314   case MCSA_Hidden:
315   case MCSA_IndirectSymbol:
316   case MCSA_Internal:
317   case MCSA_Protected:
318   case MCSA_Weak:
319   case MCSA_Local:
320     return false;
321 
322   case MCSA_Global:
323     Symbol->setExternal(true);
324     // This effectively clears the undefined lazy bit, in Darwin 'as', although
325     // it isn't very consistent because it implements this as part of symbol
326     // lookup.
327     //
328     // FIXME: Cleanup this code, these bits should be emitted based on semantic
329     // properties, not on the order of definition, etc.
330     Symbol->setReferenceTypeUndefinedLazy(false);
331     break;
332 
333   case MCSA_LazyReference:
334     // FIXME: This requires -dynamic.
335     Symbol->setNoDeadStrip();
336     if (Symbol->isUndefined())
337       Symbol->setReferenceTypeUndefinedLazy(true);
338     break;
339 
340     // Since .reference sets the no dead strip bit, it is equivalent to
341     // .no_dead_strip in practice.
342   case MCSA_Reference:
343   case MCSA_NoDeadStrip:
344     Symbol->setNoDeadStrip();
345     break;
346 
347   case MCSA_SymbolResolver:
348     Symbol->setSymbolResolver();
349     break;
350 
351   case MCSA_AltEntry:
352     Symbol->setAltEntry();
353     break;
354 
355   case MCSA_PrivateExtern:
356     Symbol->setExternal(true);
357     Symbol->setPrivateExtern(true);
358     break;
359 
360   case MCSA_WeakReference:
361     // FIXME: This requires -dynamic.
362     if (Symbol->isUndefined())
363       Symbol->setWeakReference();
364     break;
365 
366   case MCSA_WeakDefinition:
367     // FIXME: 'as' enforces that this is defined and global. The manual claims
368     // it has to be in a coalesced section, but this isn't enforced.
369     Symbol->setWeakDefinition();
370     break;
371 
372   case MCSA_WeakDefAutoPrivate:
373     Symbol->setWeakDefinition();
374     Symbol->setWeakReference();
375     break;
376   }
377 
378   return true;
379 }
380 
381 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
382   // Encode the 'desc' value into the lowest implementation defined bits.
383   getAssembler().registerSymbol(*Symbol);
384   cast<MCSymbolMachO>(Symbol)->setDesc(DescValue);
385 }
386 
387 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
388                                        unsigned ByteAlignment) {
389   // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
390   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
391 
392   getAssembler().registerSymbol(*Symbol);
393   Symbol->setExternal(true);
394   Symbol->setCommon(Size, ByteAlignment);
395 }
396 
397 void MCMachOStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
398                                             unsigned ByteAlignment) {
399   // '.lcomm' is equivalent to '.zerofill'.
400   return EmitZerofill(getContext().getObjectFileInfo()->getDataBSSSection(),
401                       Symbol, Size, ByteAlignment);
402 }
403 
404 void MCMachOStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol,
405                                    uint64_t Size, unsigned ByteAlignment) {
406   getAssembler().registerSection(*Section);
407 
408   // The symbol may not be present, which only creates the section.
409   if (!Symbol)
410     return;
411 
412   // On darwin all virtual sections have zerofill type.
413   assert(Section->isVirtualSection() && "Section does not have zerofill type!");
414 
415   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
416 
417   getAssembler().registerSymbol(*Symbol);
418 
419   // Emit an align fragment if necessary.
420   if (ByteAlignment != 1)
421     new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, Section);
422 
423   MCFragment *F = new MCFillFragment(0, Size, Section);
424   Symbol->setFragment(F);
425 
426   // Update the maximum alignment on the zero fill section if necessary.
427   if (ByteAlignment > Section->getAlignment())
428     Section->setAlignment(ByteAlignment);
429 }
430 
431 // This should always be called with the thread local bss section.  Like the
432 // .zerofill directive this doesn't actually switch sections on us.
433 void MCMachOStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
434                                      uint64_t Size, unsigned ByteAlignment) {
435   EmitZerofill(Section, Symbol, Size, ByteAlignment);
436 }
437 
438 void MCMachOStreamer::EmitInstToData(const MCInst &Inst,
439                                      const MCSubtargetInfo &STI) {
440   MCDataFragment *DF = getOrCreateDataFragment();
441 
442   SmallVector<MCFixup, 4> Fixups;
443   SmallString<256> Code;
444   raw_svector_ostream VecOS(Code);
445   getAssembler().getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
446 
447   // Add the fixups and data.
448   for (MCFixup &Fixup : Fixups) {
449     Fixup.setOffset(Fixup.getOffset() + DF->getContents().size());
450     DF->getFixups().push_back(Fixup);
451   }
452   DF->getContents().append(Code.begin(), Code.end());
453 }
454 
455 void MCMachOStreamer::FinishImpl() {
456   EmitFrames(&getAssembler().getBackend());
457 
458   // We have to set the fragment atom associations so we can relax properly for
459   // Mach-O.
460 
461   // First, scan the symbol table to build a lookup table from fragments to
462   // defining symbols.
463   DenseMap<const MCFragment *, const MCSymbol *> DefiningSymbolMap;
464   for (const MCSymbol &Symbol : getAssembler().symbols()) {
465     if (getAssembler().isSymbolLinkerVisible(Symbol) && Symbol.isInSection() &&
466         !Symbol.isVariable()) {
467       // An atom defining symbol should never be internal to a fragment.
468       assert(Symbol.getOffset() == 0 &&
469              "Invalid offset in atom defining symbol!");
470       DefiningSymbolMap[Symbol.getFragment()] = &Symbol;
471     }
472   }
473 
474   // Set the fragment atom associations by tracking the last seen atom defining
475   // symbol.
476   for (MCSection &Sec : getAssembler()) {
477     const MCSymbol *CurrentAtom = nullptr;
478     for (MCFragment &Frag : Sec) {
479       if (const MCSymbol *Symbol = DefiningSymbolMap.lookup(&Frag))
480         CurrentAtom = Symbol;
481       Frag.setAtom(CurrentAtom);
482     }
483   }
484 
485   this->MCObjectStreamer::FinishImpl();
486 }
487 
488 MCStreamer *llvm::createMachOStreamer(MCContext &Context,
489                                       std::unique_ptr<MCAsmBackend> &&MAB,
490                                       raw_pwrite_stream &OS,
491                                       std::unique_ptr<MCCodeEmitter> &&CE,
492                                       bool RelaxAll, bool DWARFMustBeAtTheEnd,
493                                       bool LabelSections) {
494   MCMachOStreamer *S =
495       new MCMachOStreamer(Context, std::move(MAB), OS, std::move(CE),
496                           DWARFMustBeAtTheEnd, LabelSections);
497   const Triple &TT = Context.getObjectFileInfo()->getTargetTriple();
498   if (TT.isOSDarwin()) {
499     unsigned Major, Minor, Update;
500     TT.getOSVersion(Major, Minor, Update);
501     // If there is a version specified, Major will be non-zero.
502     if (Major) {
503       MCVersionMinType VersionType;
504       if (TT.isWatchOS())
505         VersionType = MCVM_WatchOSVersionMin;
506       else if (TT.isTvOS())
507         VersionType = MCVM_TvOSVersionMin;
508       else if (TT.isMacOSX())
509         VersionType = MCVM_OSXVersionMin;
510       else {
511         assert(TT.isiOS() && "Must only be iOS platform left");
512         VersionType = MCVM_IOSVersionMin;
513       }
514       S->EmitVersionMin(VersionType, Major, Minor, Update);
515     }
516   }
517   if (RelaxAll)
518     S->getAssembler().setRelaxAll(true);
519   return S;
520 }
521