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