1//===- MCMachOStreamer.cpp - MachO Streamer -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/ADT/DenseMap.h"
10#include "llvm/ADT/SmallVector.h"
11#include "llvm/ADT/StringRef.h"
12#include "llvm/BinaryFormat/MachO.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/MCDirectives.h"
18#include "llvm/MC/MCExpr.h"
19#include "llvm/MC/MCFixup.h"
20#include "llvm/MC/MCLinkerOptimizationHint.h"
21#include "llvm/MC/MCMachObjectWriter.h"
22#include "llvm/MC/MCObjectFileInfo.h"
23#include "llvm/MC/MCObjectStreamer.h"
24#include "llvm/MC/MCObjectWriter.h"
25#include "llvm/MC/MCSection.h"
26#include "llvm/MC/MCSectionMachO.h"
27#include "llvm/MC/MCSymbol.h"
28#include "llvm/MC/MCSymbolMachO.h"
29#include "llvm/MC/MCValue.h"
30#include "llvm/MC/SectionKind.h"
31#include "llvm/MC/TargetRegistry.h"
32#include "llvm/Support/Casting.h"
33#include "llvm/Support/ErrorHandling.h"
34#include <cassert>
35#include <vector>
36
37namespace llvm {
38class MCInst;
39class MCStreamer;
40class MCSubtargetInfo;
41class Triple;
42} // namespace llvm
43
44using namespace llvm;
45
46namespace {
47
48class MCMachOStreamer : public MCObjectStreamer {
49private:
50 /// LabelSections - true if each section change should emit a linker local
51 /// label for use in relocations for assembler local references. Obviates the
52 /// need for local relocations. False by default.
53 bool LabelSections;
54
55 /// HasSectionLabel - map of which sections have already had a non-local
56 /// label emitted to them. Used so we don't emit extraneous linker local
57 /// labels in the middle of the section.
58 DenseMap<const MCSection*, bool> HasSectionLabel;
59
60 void emitDataRegion(MachO::DataRegionType Kind);
61 void emitDataRegionEnd();
62
63public:
64 MCMachOStreamer(MCContext &Context, std::unique_ptr<MCAsmBackend> MAB,
65 std::unique_ptr<MCObjectWriter> OW,
66 std::unique_ptr<MCCodeEmitter> Emitter, bool label)
67 : MCObjectStreamer(Context, std::move(MAB), std::move(OW),
68 std::move(Emitter)),
69 LabelSections(label) {}
70
71 /// state management
72 void reset() override {
73 HasSectionLabel.clear();
74 MCObjectStreamer::reset();
75 }
76
77 MachObjectWriter &getWriter() {
78 return static_cast<MachObjectWriter &>(getAssembler().getWriter());
79 }
80
81 /// @name MCStreamer Interface
82 /// @{
83
84 void changeSection(MCSection *Sect, uint32_t Subsection = 0) override;
85 void emitLabel(MCSymbol *Symbol, SMLoc Loc = SMLoc()) override;
86 void emitAssignment(MCSymbol *Symbol, const MCExpr *Value) override;
87 void emitEHSymAttributes(const MCSymbol *Symbol, MCSymbol *EHSymbol) override;
88 void emitSubsectionsViaSymbols() override;
89 void emitLinkerOptions(ArrayRef<std::string> Options) override;
90 void emitDataRegion(MCDataRegionType Kind) override;
91 void emitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor,
92 unsigned Update, VersionTuple SDKVersion) override;
93 void emitBuildVersion(unsigned Platform, unsigned Major, unsigned Minor,
94 unsigned Update, VersionTuple SDKVersion) override;
95 void emitDarwinTargetVariantBuildVersion(unsigned Platform, unsigned Major,
96 unsigned Minor, unsigned Update,
97 VersionTuple SDKVersion) override;
98 void emitTargetTriple(StringRef TargetTriple) override;
99 bool emitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
100 void emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
101 void emitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
102 Align ByteAlignment) override;
103
104 void emitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
105 Align ByteAlignment) override;
106 void emitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
107 uint64_t Size = 0, Align ByteAlignment = Align(1),
108 SMLoc Loc = SMLoc()) override;
109 void emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
110 Align ByteAlignment = Align(1)) override;
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 getWriter().getLOHContainer().addDirective(Kind, Args);
118 }
119 void emitCGProfileEntry(const MCSymbolRefExpr *From,
120 const MCSymbolRefExpr *To, uint64_t Count) override {
121 if (!From->getSymbol().isTemporary() && !To->getSymbol().isTemporary())
122 getWriter().getCGProfile().push_back(Elt: {.From: From, .To: To, .Count: Count});
123 }
124
125 void finishImpl() override;
126
127 void finalizeCGProfileEntry(const MCSymbolRefExpr *&SRE);
128 void finalizeCGProfile();
129 void createAddrSigSection();
130};
131
132} // end anonymous namespace.
133
134void MCMachOStreamer::changeSection(MCSection *Section, uint32_t Subsection) {
135 MCObjectStreamer::changeSection(Section, Subsection);
136
137 // Output a linker-local symbol so we don't need section-relative local
138 // relocations. The linker hates us when we do that.
139 if (LabelSections && !HasSectionLabel[Section] &&
140 !Section->getBeginSymbol()) {
141 MCSymbol *Label = getContext().createLinkerPrivateTempSymbol();
142 Section->setBeginSymbol(Label);
143 HasSectionLabel[Section] = true;
144 if (!Label->isInSection())
145 emitLabel(Symbol: Label);
146 }
147}
148
149void MCMachOStreamer::emitEHSymAttributes(const MCSymbol *Symbol,
150 MCSymbol *EHSymbol) {
151 auto *Sym = static_cast<const MCSymbolMachO *>(Symbol);
152 getAssembler().registerSymbol(Symbol: *Symbol);
153 if (Sym->isExternal())
154 emitSymbolAttribute(Symbol: EHSymbol, Attribute: MCSA_Global);
155 if (Sym->isWeakDefinition())
156 emitSymbolAttribute(Symbol: EHSymbol, Attribute: MCSA_WeakDefinition);
157 if (Sym->isPrivateExtern())
158 emitSymbolAttribute(Symbol: EHSymbol, Attribute: MCSA_PrivateExtern);
159}
160
161void MCMachOStreamer::emitLabel(MCSymbol *Symbol, SMLoc Loc) {
162 // We have to create a new fragment if this is an atom defining symbol,
163 // fragments cannot span atoms.
164 if (static_cast<MCSymbolMachO *>(Symbol)->isSymbolLinkerVisible())
165 newFragment();
166
167 MCObjectStreamer::emitLabel(Symbol, Loc);
168
169 // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
170 // to clear the weak reference and weak definition bits too, but the
171 // implementation was buggy. For now we just try to match 'as', for
172 // diffability.
173 //
174 // FIXME: Cleanup this code, these bits should be emitted based on semantic
175 // properties, not on the order of definition, etc.
176 static_cast<MCSymbolMachO *>(Symbol)->clearReferenceType();
177}
178
179void MCMachOStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
180 MCValue Res;
181
182 if (Value->evaluateAsRelocatable(Res, Asm: nullptr)) {
183 if (const auto *SymA = Res.getAddSym()) {
184 if (!Res.getSubSym() &&
185 (SymA->getName().empty() || Res.getConstant() != 0))
186 static_cast<MCSymbolMachO *>(Symbol)->setAltEntry();
187 }
188 }
189 MCObjectStreamer::emitAssignment(Symbol, Value);
190}
191
192void MCMachOStreamer::emitDataRegion(MachO::DataRegionType Kind) {
193 // Create a temporary label to mark the start of the data region.
194 MCSymbol *Start = getContext().createTempSymbol();
195 emitLabel(Symbol: Start);
196 // Record the region for the object writer to use.
197 getWriter().getDataRegions().push_back(x: {.Kind: Kind, .Start: Start, .End: nullptr});
198}
199
200void MCMachOStreamer::emitDataRegionEnd() {
201 auto &Regions = getWriter().getDataRegions();
202 assert(!Regions.empty() && "Mismatched .end_data_region!");
203 auto &Data = Regions.back();
204 assert(!Data.End && "Mismatched .end_data_region!");
205 // Create a temporary label to mark the end of the data region.
206 Data.End = getContext().createTempSymbol();
207 emitLabel(Symbol: Data.End);
208}
209
210void MCMachOStreamer::emitSubsectionsViaSymbols() {
211 getWriter().setSubsectionsViaSymbols(true);
212}
213
214void MCMachOStreamer::emitLinkerOptions(ArrayRef<std::string> Options) {
215 getWriter().getLinkerOptions().push_back(x: Options);
216}
217
218void MCMachOStreamer::emitDataRegion(MCDataRegionType Kind) {
219 switch (Kind) {
220 case MCDR_DataRegion:
221 emitDataRegion(Kind: MachO::DataRegionType::DICE_KIND_DATA);
222 return;
223 case MCDR_DataRegionJT8:
224 emitDataRegion(Kind: MachO::DataRegionType::DICE_KIND_JUMP_TABLE8);
225 return;
226 case MCDR_DataRegionJT16:
227 emitDataRegion(Kind: MachO::DataRegionType::DICE_KIND_JUMP_TABLE16);
228 return;
229 case MCDR_DataRegionJT32:
230 emitDataRegion(Kind: MachO::DataRegionType::DICE_KIND_JUMP_TABLE32);
231 return;
232 case MCDR_DataRegionEnd:
233 emitDataRegionEnd();
234 return;
235 }
236}
237
238void MCMachOStreamer::emitVersionMin(MCVersionMinType Kind, unsigned Major,
239 unsigned Minor, unsigned Update,
240 VersionTuple SDKVersion) {
241 getWriter().setVersionMin(Type: Kind, Major, Minor, Update, SDKVersion);
242}
243
244void MCMachOStreamer::emitBuildVersion(unsigned Platform, unsigned Major,
245 unsigned Minor, unsigned Update,
246 VersionTuple SDKVersion) {
247 getWriter().setBuildVersion(Platform: (MachO::PlatformType)Platform, Major, Minor,
248 Update, SDKVersion);
249}
250
251void MCMachOStreamer::emitDarwinTargetVariantBuildVersion(
252 unsigned Platform, unsigned Major, unsigned Minor, unsigned Update,
253 VersionTuple SDKVersion) {
254 getWriter().setTargetVariantBuildVersion(Platform: (MachO::PlatformType)Platform, Major,
255 Minor, Update, SDKVersion);
256}
257
258void MCMachOStreamer::emitTargetTriple(StringRef TargetTriple) {
259 getWriter().setTargetTriple(TargetTriple);
260}
261
262bool MCMachOStreamer::emitSymbolAttribute(MCSymbol *Sym,
263 MCSymbolAttr Attribute) {
264 auto *Symbol = static_cast<MCSymbolMachO *>(Sym);
265
266 // Indirect symbols are handled differently, to match how 'as' handles
267 // them. This makes writing matching .o files easier.
268 if (Attribute == MCSA_IndirectSymbol) {
269 // Note that we intentionally cannot use the symbol data here; this is
270 // important for matching the string table that 'as' generates.
271 getWriter().getIndirectSymbols().push_back(
272 x: {.Symbol: Symbol, .Section: getCurrentSectionOnly()});
273 return true;
274 }
275
276 // Adding a symbol attribute always introduces the symbol, note that an
277 // important side effect of calling registerSymbol here is to register
278 // the symbol with the assembler.
279 getAssembler().registerSymbol(Symbol: *Symbol);
280
281 // The implementation of symbol attributes is designed to match 'as', but it
282 // leaves much to desired. It doesn't really make sense to arbitrarily add and
283 // remove flags, but 'as' allows this (in particular, see .desc).
284 //
285 // In the future it might be worth trying to make these operations more well
286 // defined.
287 switch (Attribute) {
288 case MCSA_Invalid:
289 case MCSA_ELF_TypeFunction:
290 case MCSA_ELF_TypeIndFunction:
291 case MCSA_ELF_TypeObject:
292 case MCSA_ELF_TypeTLS:
293 case MCSA_ELF_TypeCommon:
294 case MCSA_ELF_TypeNoType:
295 case MCSA_ELF_TypeGnuUniqueObject:
296 case MCSA_Extern:
297 case MCSA_Hidden:
298 case MCSA_IndirectSymbol:
299 case MCSA_Internal:
300 case MCSA_Protected:
301 case MCSA_Weak:
302 case MCSA_Local:
303 case MCSA_LGlobal:
304 case MCSA_Exported:
305 case MCSA_Memtag:
306 case MCSA_WeakAntiDep:
307 case MCSA_OSLinkage:
308 case MCSA_XPLinkage:
309 return false;
310
311 case MCSA_Global:
312 Symbol->setExternal(true);
313 // This effectively clears the undefined lazy bit, in Darwin 'as', although
314 // it isn't very consistent because it implements this as part of symbol
315 // lookup.
316 //
317 // FIXME: Cleanup this code, these bits should be emitted based on semantic
318 // properties, not on the order of definition, etc.
319 Symbol->setReferenceTypeUndefinedLazy(false);
320 break;
321
322 case MCSA_LazyReference:
323 // FIXME: This requires -dynamic.
324 Symbol->setNoDeadStrip();
325 if (Symbol->isUndefined())
326 Symbol->setReferenceTypeUndefinedLazy(true);
327 break;
328
329 // Since .reference sets the no dead strip bit, it is equivalent to
330 // .no_dead_strip in practice.
331 case MCSA_Reference:
332 case MCSA_NoDeadStrip:
333 Symbol->setNoDeadStrip();
334 break;
335
336 case MCSA_SymbolResolver:
337 Symbol->setSymbolResolver();
338 break;
339
340 case MCSA_AltEntry:
341 Symbol->setAltEntry();
342 break;
343
344 case MCSA_PrivateExtern:
345 Symbol->setExternal(true);
346 Symbol->setPrivateExtern(true);
347 break;
348
349 case MCSA_WeakReference:
350 // FIXME: This requires -dynamic.
351 if (Symbol->isUndefined())
352 Symbol->setWeakReference();
353 break;
354
355 case MCSA_WeakDefinition:
356 // FIXME: 'as' enforces that this is defined and global. The manual claims
357 // it has to be in a coalesced section, but this isn't enforced.
358 Symbol->setWeakDefinition();
359 break;
360
361 case MCSA_WeakDefAutoPrivate:
362 Symbol->setWeakDefinition();
363 Symbol->setWeakReference();
364 break;
365
366 case MCSA_Cold:
367 Symbol->setCold();
368 break;
369 }
370
371 return true;
372}
373
374void MCMachOStreamer::emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
375 // Encode the 'desc' value into the lowest implementation defined bits.
376 getAssembler().registerSymbol(Symbol: *Symbol);
377 static_cast<MCSymbolMachO *>(Symbol)->setDesc(DescValue);
378}
379
380void MCMachOStreamer::emitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
381 Align ByteAlignment) {
382 auto &Sym = static_cast<MCSymbolMachO &>(*Symbol);
383 // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
384 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
385
386 getAssembler().registerSymbol(Symbol: Sym);
387 Sym.setExternal(true);
388 Sym.setCommon(Size, Alignment: ByteAlignment);
389}
390
391void MCMachOStreamer::emitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
392 Align ByteAlignment) {
393 // '.lcomm' is equivalent to '.zerofill'.
394 return emitZerofill(Section: getContext().getObjectFileInfo()->getDataBSSSection(),
395 Symbol, Size, ByteAlignment);
396}
397
398void MCMachOStreamer::emitZerofill(MCSection *Section, MCSymbol *Symbol,
399 uint64_t Size, Align ByteAlignment,
400 SMLoc Loc) {
401 // On darwin all virtual sections have zerofill type. Disallow the usage of
402 // .zerofill in non-virtual functions. If something similar is needed, use
403 // .space or .zero.
404 if (!Section->isBssSection()) {
405 getContext().reportError(
406 L: Loc, Msg: "The usage of .zerofill is restricted to sections of "
407 "ZEROFILL type. Use .zero or .space instead.");
408 return; // Early returning here shouldn't harm. EmitZeros should work on any
409 // section.
410 }
411
412 pushSection();
413 switchSection(Section);
414
415 // The symbol may not be present, which only creates the section.
416 if (Symbol) {
417 emitValueToAlignment(Alignment: ByteAlignment, Fill: 0, FillLen: 1, MaxBytesToEmit: 0);
418 emitLabel(Symbol);
419 emitZeros(NumBytes: Size);
420 }
421 popSection();
422}
423
424// This should always be called with the thread local bss section. Like the
425// .zerofill directive this doesn't actually switch sections on us.
426void MCMachOStreamer::emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
427 uint64_t Size, Align ByteAlignment) {
428 emitZerofill(Section, Symbol, Size, ByteAlignment);
429}
430
431void MCMachOStreamer::finishImpl() {
432 emitFrames();
433
434 // We have to set the fragment atom associations so we can relax properly for
435 // Mach-O.
436
437 // First, scan the symbol table to build a lookup table from fragments to
438 // defining symbols.
439 DenseMap<const MCFragment *, const MCSymbol *> DefiningSymbolMap;
440 for (const MCSymbol &Symbol : getAssembler().symbols()) {
441 auto &Sym = static_cast<const MCSymbolMachO &>(Symbol);
442 if (Sym.isSymbolLinkerVisible() && Sym.isInSection() && !Sym.isVariable() &&
443 !Sym.isAltEntry()) {
444 // An atom defining symbol should never be internal to a fragment.
445 assert(Symbol.getOffset() == 0 &&
446 "Invalid offset in atom defining symbol!");
447 DefiningSymbolMap[Symbol.getFragment()] = &Symbol;
448 }
449 }
450
451 // Set the fragment atom associations by tracking the last seen atom defining
452 // symbol.
453 for (MCSection &Sec : getAssembler()) {
454 static_cast<MCSectionMachO &>(Sec).allocAtoms();
455 const MCSymbol *CurrentAtom = nullptr;
456 size_t I = 0;
457 for (MCFragment &Frag : Sec) {
458 if (const MCSymbol *Symbol = DefiningSymbolMap.lookup(Val: &Frag))
459 CurrentAtom = Symbol;
460 static_cast<MCSectionMachO &>(Sec).setAtom(I: I++, Sym: CurrentAtom);
461 }
462 }
463
464 finalizeCGProfile();
465
466 createAddrSigSection();
467 this->MCObjectStreamer::finishImpl();
468}
469
470void MCMachOStreamer::finalizeCGProfileEntry(const MCSymbolRefExpr *&SRE) {
471 auto *S =
472 static_cast<MCSymbolMachO *>(const_cast<MCSymbol *>(&SRE->getSymbol()));
473 if (getAssembler().registerSymbol(Symbol: *S))
474 S->setExternal(true);
475}
476
477void MCMachOStreamer::finalizeCGProfile() {
478 MCAssembler &Asm = getAssembler();
479 MCObjectWriter &W = getWriter();
480 if (W.getCGProfile().empty())
481 return;
482 for (auto &E : W.getCGProfile()) {
483 finalizeCGProfileEntry(SRE&: E.From);
484 finalizeCGProfileEntry(SRE&: E.To);
485 }
486 // We can't write the section out until symbol indices are finalized which
487 // doesn't happen until after section layout. We need to create the section
488 // and set its size now so that it's accounted for in layout.
489 MCSection *CGProfileSection = Asm.getContext().getMachOSection(
490 Segment: "__LLVM", Section: "__cg_profile", TypeAndAttributes: 0, K: SectionKind::getMetadata());
491 // Call the base class changeSection to omit the linker-local label.
492 MCObjectStreamer::changeSection(Section: CGProfileSection);
493 // For each entry, reserve space for 2 32-bit indices and a 64-bit count.
494 size_t SectionBytes =
495 W.getCGProfile().size() * (2 * sizeof(uint32_t) + sizeof(uint64_t));
496 (*CGProfileSection->begin())
497 .setVarContents(std::vector<char>(SectionBytes, 0));
498}
499
500MCStreamer *llvm::createMachOStreamer(MCContext &Context,
501 std::unique_ptr<MCAsmBackend> &&MAB,
502 std::unique_ptr<MCObjectWriter> &&OW,
503 std::unique_ptr<MCCodeEmitter> &&CE,
504 bool DWARFMustBeAtTheEnd,
505 bool LabelSections) {
506 return new MCMachOStreamer(Context, std::move(MAB), std::move(OW),
507 std::move(CE), LabelSections);
508}
509
510// The AddrSig section uses a series of relocations to refer to the symbols that
511// should be considered address-significant. The only interesting content of
512// these relocations is their symbol; the type, length etc will be ignored by
513// the linker. The reason we are not referring to the symbol indices directly is
514// that those indices will be invalidated by tools that update the symbol table.
515// Symbol relocations OTOH will have their indices updated by e.g. llvm-strip.
516void MCMachOStreamer::createAddrSigSection() {
517 MCAssembler &Asm = getAssembler();
518 MCObjectWriter &writer = Asm.getWriter();
519 if (!writer.getEmitAddrsigSection())
520 return;
521 // Create the AddrSig section and first data fragment here as its layout needs
522 // to be computed immediately after in order for it to be exported correctly.
523 MCSection *AddrSigSection =
524 Asm.getContext().getObjectFileInfo()->getAddrSigSection();
525 // Call the base class changeSection to omit the linker-local label.
526 MCObjectStreamer::changeSection(Section: AddrSigSection);
527 auto *Frag = cast<MCFragment>(Val: AddrSigSection->curFragList()->Head);
528 // We will generate a series of pointer-sized symbol relocations at offset
529 // 0x0. Set the section size to be large enough to contain a single pointer
530 // (instead of emitting a zero-sized section) so these relocations are
531 // technically valid, even though we don't expect these relocations to
532 // actually be applied by the linker.
533 constexpr char zero[8] = {};
534 Frag->setVarContents(zero);
535}
536