1//===- lib/MC/MCELFStreamer.cpp - ELF Object Output -----------------------===//
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// This file assembles .s files and emits ELF .o object files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/MC/MCELFStreamer.h"
14#include "llvm/ADT/SmallVector.h"
15#include "llvm/BinaryFormat/ELF.h"
16#include "llvm/MC/MCAsmBackend.h"
17#include "llvm/MC/MCAsmInfo.h"
18#include "llvm/MC/MCAssembler.h"
19#include "llvm/MC/MCCodeEmitter.h"
20#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCDirectives.h"
22#include "llvm/MC/MCELFObjectWriter.h"
23#include "llvm/MC/MCExpr.h"
24#include "llvm/MC/MCFixup.h"
25#include "llvm/MC/MCLFI.h"
26#include "llvm/MC/MCObjectFileInfo.h"
27#include "llvm/MC/MCObjectWriter.h"
28#include "llvm/MC/MCSection.h"
29#include "llvm/MC/MCSectionELF.h"
30#include "llvm/MC/MCStreamer.h"
31#include "llvm/MC/MCSymbol.h"
32#include "llvm/MC/MCSymbolELF.h"
33#include "llvm/MC/MCTargetOptions.h"
34#include "llvm/MC/TargetRegistry.h"
35#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Support/LEB128.h"
37#include <cassert>
38#include <cstdint>
39
40using namespace llvm;
41
42MCELFStreamer::MCELFStreamer(MCContext &Context,
43 std::unique_ptr<MCAsmBackend> TAB,
44 std::unique_ptr<MCObjectWriter> OW,
45 std::unique_ptr<MCCodeEmitter> Emitter)
46 : MCObjectStreamer(Context, std::move(TAB), std::move(OW),
47 std::move(Emitter)) {}
48
49ELFObjectWriter &MCELFStreamer::getWriter() {
50 return static_cast<ELFObjectWriter &>(getAssembler().getWriter());
51}
52
53void MCELFStreamer::initSections(const MCSubtargetInfo &STI) {
54 MCContext &Ctx = getContext();
55 switchSection(Section: Ctx.getObjectFileInfo()->getTextSection());
56 emitCodeAlignment(ByteAlignment: Align(Ctx.getObjectFileInfo()->getTextSectionAlignment()),
57 STI);
58 if (Ctx.getTargetTriple().isLFI())
59 emitLFIBundleAlign(Streamer&: *this, Ctx);
60}
61
62void MCELFStreamer::emitLabel(MCSymbol *S, SMLoc Loc) {
63 auto *Symbol = static_cast<MCSymbolELF *>(S);
64 MCObjectStreamer::emitLabel(Symbol, Loc);
65
66 const MCSectionELF &Section =
67 static_cast<const MCSectionELF &>(*getCurrentSectionOnly());
68 if (Section.getFlags() & ELF::SHF_TLS)
69 Symbol->setType(ELF::STT_TLS);
70}
71
72void MCELFStreamer::emitLabelAtPos(MCSymbol *S, SMLoc Loc, MCFragment &F,
73 uint64_t Offset) {
74 auto *Symbol = static_cast<MCSymbolELF *>(S);
75 MCObjectStreamer::emitLabelAtPos(Symbol, Loc, F, Offset);
76
77 const MCSectionELF &Section =
78 static_cast<const MCSectionELF &>(*getCurrentSectionOnly());
79 if (Section.getFlags() & ELF::SHF_TLS)
80 Symbol->setType(ELF::STT_TLS);
81}
82
83void MCELFStreamer::changeSection(MCSection *Section, uint32_t Subsection) {
84 MCAssembler &Asm = getAssembler();
85 if (isBundleLocked()) {
86 getContext().reportError(
87 L: getStartTokLoc(), Msg: "unterminated .bundle_lock when changing a section");
88 // Clean up bundle state to allow continuing.
89 BundleLocked = false;
90 BundleBA = nullptr;
91 }
92 auto *SectionELF = static_cast<const MCSectionELF *>(Section);
93 const MCSymbol *Grp = SectionELF->getGroup();
94 if (Grp)
95 Asm.registerSymbol(Symbol: *Grp);
96 if (SectionELF->getFlags() & ELF::SHF_GNU_RETAIN)
97 getWriter().markGnuAbi();
98
99 MCObjectStreamer::changeSection(Section, Subsection);
100 auto *Sym = static_cast<MCSymbolELF *>(Section->getBeginSymbol());
101 Sym->setBinding(ELF::STB_LOCAL);
102 Sym->setType(ELF::STT_SECTION);
103}
104
105void MCELFStreamer::emitWeakReference(MCSymbol *Alias, const MCSymbol *Target) {
106 auto *A = static_cast<MCSymbolELF *>(Alias);
107 if (A->isDefined()) {
108 getContext().reportError(L: getStartTokLoc(), Msg: "symbol '" + A->getName() +
109 "' is already defined");
110 return;
111 }
112 A->setVariableValue(MCSymbolRefExpr::create(Symbol: Target, Ctx&: getContext()));
113 A->setIsWeakref();
114 getWriter().Weakrefs.push_back(Elt: A);
115}
116
117// When GNU as encounters more than one .type declaration for an object it seems
118// to use a mechanism similar to the one below to decide which type is actually
119// used in the object file. The greater of T1 and T2 is selected based on the
120// following ordering:
121// STT_NOTYPE < STT_OBJECT < STT_FUNC < STT_GNU_IFUNC < STT_TLS < anything else
122// If neither T1 < T2 nor T2 < T1 according to this ordering, use T2 (the user
123// provided type).
124static unsigned CombineSymbolTypes(unsigned T1, unsigned T2) {
125 for (unsigned Type : {ELF::STT_NOTYPE, ELF::STT_OBJECT, ELF::STT_FUNC,
126 ELF::STT_GNU_IFUNC, ELF::STT_TLS}) {
127 if (T1 == Type)
128 return T2;
129 if (T2 == Type)
130 return T1;
131 }
132
133 return T2;
134}
135
136bool MCELFStreamer::emitSymbolAttribute(MCSymbol *S, MCSymbolAttr Attribute) {
137 auto *Symbol = static_cast<MCSymbolELF *>(S);
138
139 // Adding a symbol attribute always introduces the symbol, note that an
140 // important side effect of calling registerSymbol here is to register
141 // the symbol with the assembler.
142 getAssembler().registerSymbol(Symbol: *Symbol);
143
144 // The implementation of symbol attributes is designed to match 'as', but it
145 // leaves much to desired. It doesn't really make sense to arbitrarily add and
146 // remove flags, but 'as' allows this (in particular, see .desc).
147 //
148 // In the future it might be worth trying to make these operations more well
149 // defined.
150 switch (Attribute) {
151 case MCSA_Cold:
152 case MCSA_Extern:
153 case MCSA_LazyReference:
154 case MCSA_Reference:
155 case MCSA_SymbolResolver:
156 case MCSA_PrivateExtern:
157 case MCSA_WeakDefinition:
158 case MCSA_WeakDefAutoPrivate:
159 case MCSA_Invalid:
160 case MCSA_IndirectSymbol:
161 case MCSA_Exported:
162 case MCSA_WeakAntiDep:
163 case MCSA_OSLinkage:
164 case MCSA_XPLinkage:
165 return false;
166
167 case MCSA_NoDeadStrip:
168 // Ignore for now.
169 break;
170
171 case MCSA_ELF_TypeGnuUniqueObject:
172 Symbol->setType(CombineSymbolTypes(T1: Symbol->getType(), T2: ELF::STT_OBJECT));
173 Symbol->setBinding(ELF::STB_GNU_UNIQUE);
174 getWriter().markGnuAbi();
175 break;
176
177 case MCSA_Global:
178 // For `.weak x; .global x`, GNU as sets the binding to STB_WEAK while we
179 // traditionally set the binding to STB_GLOBAL. This is error-prone, so we
180 // error on such cases. Note, we also disallow changed binding from .local.
181 if (Symbol->isBindingSet() && Symbol->getBinding() != ELF::STB_GLOBAL)
182 getContext().reportError(L: getStartTokLoc(),
183 Msg: Symbol->getName() +
184 " changed binding to STB_GLOBAL");
185 Symbol->setBinding(ELF::STB_GLOBAL);
186 break;
187
188 case MCSA_WeakReference:
189 case MCSA_Weak:
190 // For `.global x; .weak x`, both MC and GNU as set the binding to STB_WEAK.
191 // We emit a warning for now but may switch to an error in the future.
192 if (Symbol->isBindingSet() && Symbol->getBinding() != ELF::STB_WEAK)
193 getContext().reportWarning(
194 L: getStartTokLoc(), Msg: Symbol->getName() + " changed binding to STB_WEAK");
195 Symbol->setBinding(ELF::STB_WEAK);
196 break;
197
198 case MCSA_Local:
199 if (Symbol->isBindingSet() && Symbol->getBinding() != ELF::STB_LOCAL)
200 getContext().reportError(L: getStartTokLoc(),
201 Msg: Symbol->getName() +
202 " changed binding to STB_LOCAL");
203 Symbol->setBinding(ELF::STB_LOCAL);
204 break;
205
206 case MCSA_ELF_TypeFunction:
207 Symbol->setType(CombineSymbolTypes(T1: Symbol->getType(), T2: ELF::STT_FUNC));
208 break;
209
210 case MCSA_ELF_TypeIndFunction:
211 Symbol->setType(CombineSymbolTypes(T1: Symbol->getType(), T2: ELF::STT_GNU_IFUNC));
212 getWriter().markGnuAbi();
213 break;
214
215 case MCSA_ELF_TypeObject:
216 Symbol->setType(CombineSymbolTypes(T1: Symbol->getType(), T2: ELF::STT_OBJECT));
217 break;
218
219 case MCSA_ELF_TypeTLS:
220 Symbol->setType(CombineSymbolTypes(T1: Symbol->getType(), T2: ELF::STT_TLS));
221 break;
222
223 case MCSA_ELF_TypeCommon:
224 // TODO: Emit these as a common symbol.
225 Symbol->setType(CombineSymbolTypes(T1: Symbol->getType(), T2: ELF::STT_OBJECT));
226 break;
227
228 case MCSA_ELF_TypeNoType:
229 Symbol->setType(CombineSymbolTypes(T1: Symbol->getType(), T2: ELF::STT_NOTYPE));
230 break;
231
232 case MCSA_Protected:
233 Symbol->setVisibility(ELF::STV_PROTECTED);
234 break;
235
236 case MCSA_Memtag:
237 Symbol->setMemtag(true);
238 break;
239
240 case MCSA_Hidden:
241 Symbol->setVisibility(ELF::STV_HIDDEN);
242 break;
243
244 case MCSA_Internal:
245 Symbol->setVisibility(ELF::STV_INTERNAL);
246 break;
247
248 case MCSA_AltEntry:
249 llvm_unreachable("ELF doesn't support the .alt_entry attribute");
250
251 case MCSA_LGlobal:
252 llvm_unreachable("ELF doesn't support the .lglobl attribute");
253 }
254
255 return true;
256}
257
258void MCELFStreamer::emitCommonSymbol(MCSymbol *S, uint64_t Size,
259 Align ByteAlignment) {
260 auto *Symbol = static_cast<MCSymbolELF *>(S);
261 getAssembler().registerSymbol(Symbol: *Symbol);
262
263 if (!Symbol->isBindingSet())
264 Symbol->setBinding(ELF::STB_GLOBAL);
265
266 Symbol->setType(ELF::STT_OBJECT);
267
268 if (Symbol->getBinding() == ELF::STB_LOCAL) {
269 MCSection &Section = *getAssembler().getContext().getELFSection(
270 Section: ".bss", Type: ELF::SHT_NOBITS, Flags: ELF::SHF_WRITE | ELF::SHF_ALLOC);
271 MCSectionSubPair P = getCurrentSection();
272 switchSection(Section: &Section);
273
274 emitValueToAlignment(Alignment: ByteAlignment, Fill: 0, FillLen: 1, MaxBytesToEmit: 0);
275 emitLabel(S: Symbol);
276 emitZeros(NumBytes: Size);
277
278 switchSection(Section: P.first, Subsec: P.second);
279 } else {
280 if (Symbol->declareCommon(Size, Alignment: ByteAlignment))
281 report_fatal_error(reason: Twine("Symbol: ") + Symbol->getName() +
282 " redeclared as different type");
283 }
284
285 Symbol->setSize(MCConstantExpr::create(Value: Size, Ctx&: getContext()));
286}
287
288void MCELFStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
289 static_cast<MCSymbolELF *>(Symbol)->setSize(Value);
290}
291
292void MCELFStreamer::emitELFSymverDirective(const MCSymbol *OriginalSym,
293 StringRef Name,
294 bool KeepOriginalSym) {
295 getWriter().Symvers.push_back(Elt: ELFObjectWriter::Symver{
296 .Loc: getStartTokLoc(), .Sym: OriginalSym, .Name: Name, .KeepOriginalSym: KeepOriginalSym});
297}
298
299void MCELFStreamer::emitLocalCommonSymbol(MCSymbol *S, uint64_t Size,
300 Align ByteAlignment) {
301 auto *Symbol = static_cast<MCSymbolELF *>(S);
302 // FIXME: Should this be caught and done earlier?
303 getAssembler().registerSymbol(Symbol: *Symbol);
304 Symbol->setBinding(ELF::STB_LOCAL);
305 emitCommonSymbol(S: Symbol, Size, ByteAlignment);
306}
307
308void MCELFStreamer::emitCGProfileEntry(const MCSymbolRefExpr *From,
309 const MCSymbolRefExpr *To,
310 uint64_t Count) {
311 getWriter().getCGProfile().push_back(Elt: {.From: From, .To: To, .Count: Count});
312}
313
314void MCELFStreamer::emitIdent(StringRef IdentString) {
315 MCSection *Comment = getAssembler().getContext().getELFSection(
316 Section: ".comment", Type: ELF::SHT_PROGBITS, Flags: ELF::SHF_MERGE | ELF::SHF_STRINGS, EntrySize: 1);
317 pushSection();
318 switchSection(Section: Comment);
319 if (!SeenIdent) {
320 emitInt8(Value: 0);
321 SeenIdent = true;
322 }
323 emitBytes(Data: IdentString);
324 emitInt8(Value: 0);
325 popSection();
326}
327
328void MCELFStreamer::emitBundleAlignMode(Align Alignment) {
329 MCAssembler &Asm = getAssembler();
330 SMLoc Loc = getStartTokLoc();
331
332 if (!Asm.getBackend().allowBundling())
333 return getContext().reportError(
334 L: Loc, Msg: "aligned bundling is not supported by this target");
335 if (Asm.isBundlingEnabled()) {
336 if (Asm.getBundleAlign() != Alignment)
337 getContext().reportError(L: Loc,
338 Msg: ".bundle_align_mode cannot be changed once set");
339 return;
340 }
341 // Enable bundling even after the error, to avoid cascading diagnostics from
342 // later .bundle_lock directives.
343 if (Asm.getBackend().allowAutoPadding())
344 getContext().reportError(
345 L: Loc, Msg: ".bundle_align_mode is incompatible with branch alignment");
346
347 setAllowAutoPadding(true);
348 Asm.setBundleAlign(Alignment);
349}
350
351void MCELFStreamer::emitBundleLock(bool AlignToEnd,
352 const MCSubtargetInfo &STI) {
353 MCAssembler &Asm = getAssembler();
354 SMLoc Loc = getStartTokLoc();
355
356 if (!Asm.isBundlingEnabled())
357 return getContext().reportError(
358 L: Loc, Msg: ".bundle_lock forbidden when bundling is disabled");
359 if (isBundleLocked())
360 return getContext().reportError(L: Loc, Msg: "nested .bundle_lock is not allowed");
361 // Padding a group is only meaningful where nops are instructions.
362 if (!getCurrentSectionOnly()->isText())
363 return getContext().reportError(
364 L: Loc, Msg: ".bundle_lock is only allowed in an executable section");
365
366 BundleLocked = true;
367 BundleBA =
368 newSpecialFragment<MCBoundaryAlignFragment>(args: Asm.getBundleAlign(), args: STI);
369 BundleBA->setAlignToEnd(AlignToEnd);
370}
371
372void MCELFStreamer::emitBundleUnlock(const MCSubtargetInfo &STI) {
373 MCAssembler &Asm = getAssembler();
374 SMLoc Loc = getStartTokLoc();
375
376 if (!Asm.isBundlingEnabled())
377 return getContext().reportError(
378 L: Loc, Msg: ".bundle_unlock forbidden when bundling is disabled");
379 if (!isBundleLocked())
380 return getContext().reportError(L: Loc,
381 Msg: ".bundle_unlock without matching lock");
382
383 BundleLocked = false;
384 MCFragment *CF = getCurrentFragment();
385 BundleBA->setLastFragment(CF);
386
387 uint64_t GroupSize = 0;
388 for (const MCFragment *F = BundleBA->getNext();; F = F->getNext()) {
389 if (F->getKind() == MCFragment::FT_Align ||
390 F->getKind() == MCFragment::FT_Org) {
391 getContext().reportError(L: Loc, Msg: "alignment and .org directives are not "
392 "supported inside a .bundle_lock group");
393 break;
394 }
395 GroupSize += Asm.computeFragmentSize(F: *F);
396 if (F == BundleBA->getLastFragment())
397 break;
398 }
399 BundleBA = nullptr;
400
401 if (GroupSize > Asm.getBundleAlign().value())
402 getContext().reportError(
403 L: Loc, Msg: ".bundle_lock group is larger than the bundle size");
404
405 newFragment();
406
407 CF->getParent()->ensureMinAlignment(MinAlignment: Asm.getBundleAlign());
408}
409
410void MCELFStreamer::finalizeCGProfileEntry(const MCSymbolRefExpr *Sym,
411 uint64_t Offset,
412 const MCSymbolRefExpr *&SRE) {
413 const MCSymbol *S = &SRE->getSymbol();
414 if (S->isTemporary()) {
415 if (!S->isInSection()) {
416 getContext().reportError(
417 L: SRE->getLoc(), Msg: Twine("Reference to undefined temporary symbol ") +
418 "`" + S->getName() + "`");
419 return;
420 }
421 S = S->getSection().getBeginSymbol();
422 S->setUsedInReloc();
423 SRE = MCSymbolRefExpr::create(Symbol: S, Ctx&: getContext(), Loc: SRE->getLoc());
424 }
425 auto *O = MCBinaryExpr::createAdd(
426 LHS: Sym, RHS: MCConstantExpr::create(Value: Offset, Ctx&: getContext()), Ctx&: getContext());
427 MCObjectStreamer::emitRelocDirective(Offset: *O, Name: "BFD_RELOC_NONE", Expr: SRE);
428}
429
430void MCELFStreamer::finalizeCGProfile() {
431 ELFObjectWriter &W = getWriter();
432 if (W.getCGProfile().empty())
433 return;
434 MCSection *CGProfile = getAssembler().getContext().getELFSection(
435 Section: ".llvm.call-graph-profile", Type: ELF::SHT_LLVM_CALL_GRAPH_PROFILE,
436 Flags: ELF::SHF_EXCLUDE, /*sizeof(Elf_CGProfile_Impl<>)=*/EntrySize: 8);
437 pushSection();
438 switchSection(Section: CGProfile);
439 uint64_t Offset = 0;
440 auto *Sym =
441 MCSymbolRefExpr::create(Symbol: CGProfile->getBeginSymbol(), Ctx&: getContext());
442 for (auto &E : W.getCGProfile()) {
443 finalizeCGProfileEntry(Sym, Offset, SRE&: E.From);
444 finalizeCGProfileEntry(Sym, Offset, SRE&: E.To);
445 emitIntValue(Value: E.Count, Size: sizeof(uint64_t));
446 Offset += sizeof(uint64_t);
447 }
448 popSection();
449}
450
451void MCELFStreamer::finishImpl() {
452 if (isBundleLocked())
453 getContext().reportError(L: getStartTokLoc(), Msg: "unterminated .bundle_lock");
454
455 // Emit .note.GNU-stack, similar to AsmPrinter::doFinalization.
456 MCContext &Ctx = getContext();
457 auto *StackSec = Ctx.getAsmInfo().getStackSection(Ctx,
458 /*Exec=*/false);
459 if (StackSec && Ctx.getTargetOptions().MCNoExecStack)
460 switchSection(Section: StackSec);
461
462 // Emit the .gnu attributes section if any attributes have been added.
463 if (!GNUAttributes.empty()) {
464 MCSection *DummyAttributeSection = nullptr;
465 createAttributesSection(Vendor: "gnu", Section: ".gnu.attributes", Type: ELF::SHT_GNU_ATTRIBUTES,
466 AttributeSection&: DummyAttributeSection, AttrsVec&: GNUAttributes);
467 }
468
469 if (Ctx.getTargetTriple().isLFI())
470 emitLFINoteSection(Streamer&: *this, Ctx);
471
472 finalizeCGProfile();
473 emitFrames();
474
475 this->MCObjectStreamer::finishImpl();
476}
477
478void MCELFStreamer::setAttributeItem(unsigned Attribute, unsigned Value,
479 bool OverwriteExisting) {
480 // Look for existing attribute item
481 if (AttributeItem *Item = getAttributeItem(Attribute)) {
482 if (!OverwriteExisting)
483 return;
484 Item->Type = AttributeItem::NumericAttribute;
485 Item->IntValue = Value;
486 return;
487 }
488
489 // Create new attribute item
490 AttributeItem Item = {AttributeItem::NumericAttribute, Attribute, Value,
491 std::string(StringRef(""))};
492 Contents.push_back(Elt: Item);
493}
494
495void MCELFStreamer::setAttributeItem(unsigned Attribute, StringRef Value,
496 bool OverwriteExisting) {
497 // Look for existing attribute item
498 if (AttributeItem *Item = getAttributeItem(Attribute)) {
499 if (!OverwriteExisting)
500 return;
501 Item->Type = AttributeItem::TextAttribute;
502 Item->StringValue = std::string(Value);
503 return;
504 }
505
506 // Create new attribute item
507 AttributeItem Item = {AttributeItem::TextAttribute, Attribute, 0,
508 std::string(Value)};
509 Contents.push_back(Elt: Item);
510}
511
512void MCELFStreamer::setAttributeItems(unsigned Attribute, unsigned IntValue,
513 StringRef StringValue,
514 bool OverwriteExisting) {
515 // Look for existing attribute item
516 if (AttributeItem *Item = getAttributeItem(Attribute)) {
517 if (!OverwriteExisting)
518 return;
519 Item->Type = AttributeItem::NumericAndTextAttributes;
520 Item->IntValue = IntValue;
521 Item->StringValue = std::string(StringValue);
522 return;
523 }
524
525 // Create new attribute item
526 AttributeItem Item = {AttributeItem::NumericAndTextAttributes, Attribute,
527 IntValue, std::string(StringValue)};
528 Contents.push_back(Elt: Item);
529}
530
531MCELFStreamer::AttributeItem *
532MCELFStreamer::getAttributeItem(unsigned Attribute) {
533 for (AttributeItem &Item : Contents)
534 if (Item.Tag == Attribute)
535 return &Item;
536 return nullptr;
537}
538
539size_t MCELFStreamer::calculateContentSize(
540 SmallVector<AttributeItem, 64> &AttrsVec) const {
541 size_t Result = 0;
542 for (const AttributeItem &Item : AttrsVec) {
543 switch (Item.Type) {
544 case AttributeItem::HiddenAttribute:
545 break;
546 case AttributeItem::NumericAttribute:
547 Result += getULEB128Size(Value: Item.Tag);
548 Result += getULEB128Size(Value: Item.IntValue);
549 break;
550 case AttributeItem::TextAttribute:
551 Result += getULEB128Size(Value: Item.Tag);
552 Result += Item.StringValue.size() + 1; // string + '\0'
553 break;
554 case AttributeItem::NumericAndTextAttributes:
555 Result += getULEB128Size(Value: Item.Tag);
556 Result += getULEB128Size(Value: Item.IntValue);
557 Result += Item.StringValue.size() + 1; // string + '\0';
558 break;
559 }
560 }
561 return Result;
562}
563
564void MCELFStreamer::createAttributesSection(
565 StringRef Vendor, const Twine &Section, unsigned Type,
566 MCSection *&AttributeSection, SmallVector<AttributeItem, 64> &AttrsVec) {
567 // <format-version>
568 // [ <section-length> "vendor-name"
569 // [ <file-tag> <size> <attribute>*
570 // | <section-tag> <size> <section-number>* 0 <attribute>*
571 // | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
572 // ]+
573 // ]*
574
575 // Switch section to AttributeSection or get/create the section.
576 if (AttributeSection) {
577 switchSection(Section: AttributeSection);
578 } else {
579 AttributeSection = getContext().getELFSection(Section, Type, Flags: 0);
580 switchSection(Section: AttributeSection);
581
582 // Format version
583 emitInt8(Value: 0x41);
584 }
585
586 // Vendor size + Vendor name + '\0'
587 const size_t VendorHeaderSize = 4 + Vendor.size() + 1;
588
589 // Tag + Tag Size
590 const size_t TagHeaderSize = 1 + 4;
591
592 const size_t ContentsSize = calculateContentSize(AttrsVec);
593
594 emitInt32(Value: VendorHeaderSize + TagHeaderSize + ContentsSize);
595 emitBytes(Data: Vendor);
596 emitInt8(Value: 0); // '\0'
597
598 emitInt8(Value: ARMBuildAttrs::File);
599 emitInt32(Value: TagHeaderSize + ContentsSize);
600
601 // Size should have been accounted for already, now
602 // emit each field as its type (ULEB or String)
603 for (const AttributeItem &Item : AttrsVec) {
604 emitULEB128IntValue(Value: Item.Tag);
605 switch (Item.Type) {
606 default:
607 llvm_unreachable("Invalid attribute type");
608 case AttributeItem::NumericAttribute:
609 emitULEB128IntValue(Value: Item.IntValue);
610 break;
611 case AttributeItem::TextAttribute:
612 emitBytes(Data: Item.StringValue);
613 emitInt8(Value: 0); // '\0'
614 break;
615 case AttributeItem::NumericAndTextAttributes:
616 emitULEB128IntValue(Value: Item.IntValue);
617 emitBytes(Data: Item.StringValue);
618 emitInt8(Value: 0); // '\0'
619 break;
620 }
621 }
622
623 AttrsVec.clear();
624}
625
626void MCELFStreamer::createAttributesWithSubsection(
627 MCSection *&AttributeSection, const Twine &Section, unsigned Type,
628 SmallVector<AttributeSubSection, 64> &SubSectionVec) {
629 // <format-version: 'A'>
630 // [ <uint32: subsection-length> NTBS: vendor-name
631 // <bytes: vendor-data>
632 // ]*
633 // vendor-data expends to:
634 // <uint8: optional> <uint8: parameter type> <attribute>*
635 if (0 == SubSectionVec.size()) {
636 return;
637 }
638
639 // Switch section to AttributeSection or get/create the section.
640 if (AttributeSection) {
641 switchSection(Section: AttributeSection);
642 } else {
643 AttributeSection = getContext().getELFSection(Section, Type, Flags: 0);
644 switchSection(Section: AttributeSection);
645
646 // Format version
647 emitInt8(Value: 0x41);
648 }
649
650 for (AttributeSubSection &SubSection : SubSectionVec) {
651 // subsection-length + vendor-name + '\0'
652 const size_t VendorHeaderSize = 4 + SubSection.VendorName.size() + 1;
653 // optional + parameter-type
654 const size_t VendorParameters = 1 + 1;
655 const size_t ContentsSize = calculateContentSize(AttrsVec&: SubSection.Content);
656
657 emitInt32(Value: VendorHeaderSize + VendorParameters + ContentsSize);
658 emitBytes(Data: SubSection.VendorName);
659 emitInt8(Value: 0); // '\0'
660 emitInt8(Value: SubSection.IsOptional);
661 emitInt8(Value: SubSection.ParameterType);
662
663 for (AttributeItem &Item : SubSection.Content) {
664 emitULEB128IntValue(Value: Item.Tag);
665 switch (Item.Type) {
666 default:
667 assert(0 && "Invalid attribute type");
668 break;
669 case AttributeItem::NumericAttribute:
670 emitULEB128IntValue(Value: Item.IntValue);
671 break;
672 case AttributeItem::TextAttribute:
673 emitBytes(Data: Item.StringValue);
674 emitInt8(Value: 0); // '\0'
675 break;
676 case AttributeItem::NumericAndTextAttributes:
677 emitULEB128IntValue(Value: Item.IntValue);
678 emitBytes(Data: Item.StringValue);
679 emitInt8(Value: 0); // '\0'
680 break;
681 }
682 }
683 }
684 SubSectionVec.clear();
685}
686
687MCStreamer *llvm::createELFStreamer(MCContext &Context,
688 std::unique_ptr<MCAsmBackend> &&MAB,
689 std::unique_ptr<MCObjectWriter> &&OW,
690 std::unique_ptr<MCCodeEmitter> &&CE) {
691 MCELFStreamer *S =
692 new MCELFStreamer(Context, std::move(MAB), std::move(OW), std::move(CE));
693 return S;
694}
695