LLVM  16.0.0git
ELFObjectWriter.cpp
Go to the documentation of this file.
1 //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -----------------------===//
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 implements ELF object file writer information.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/ArrayRef.h"
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/ADT/iterator.h"
20 #include "llvm/BinaryFormat/ELF.h"
21 #include "llvm/MC/MCAsmBackend.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCAsmLayout.h"
24 #include "llvm/MC/MCAssembler.h"
25 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCExpr.h"
28 #include "llvm/MC/MCFixup.h"
30 #include "llvm/MC/MCFragment.h"
31 #include "llvm/MC/MCObjectWriter.h"
32 #include "llvm/MC/MCSection.h"
33 #include "llvm/MC/MCSectionELF.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/MC/MCSymbolELF.h"
37 #include "llvm/MC/MCValue.h"
39 #include "llvm/Support/Alignment.h"
40 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/Endian.h"
44 #include "llvm/Support/Error.h"
46 #include "llvm/Support/Host.h"
47 #include "llvm/Support/LEB128.h"
49 #include "llvm/Support/SMLoc.h"
51 #include <algorithm>
52 #include <cassert>
53 #include <cstddef>
54 #include <cstdint>
55 #include <map>
56 #include <memory>
57 #include <string>
58 #include <utility>
59 #include <vector>
60 
61 using namespace llvm;
62 
63 #undef DEBUG_TYPE
64 #define DEBUG_TYPE "reloc-info"
65 
66 namespace {
67 
68 using SectionIndexMapTy = DenseMap<const MCSectionELF *, uint32_t>;
69 
70 class ELFObjectWriter;
71 struct ELFWriter;
72 
73 bool isDwoSection(const MCSectionELF &Sec) {
74  return Sec.getName().endswith(".dwo");
75 }
76 
77 class SymbolTableWriter {
78  ELFWriter &EWriter;
79  bool Is64Bit;
80 
81  // indexes we are going to write to .symtab_shndx.
82  std::vector<uint32_t> ShndxIndexes;
83 
84  // The numbel of symbols written so far.
85  unsigned NumWritten;
86 
87  void createSymtabShndx();
88 
89  template <typename T> void write(T Value);
90 
91 public:
92  SymbolTableWriter(ELFWriter &EWriter, bool Is64Bit);
93 
94  void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
95  uint8_t other, uint32_t shndx, bool Reserved);
96 
97  ArrayRef<uint32_t> getShndxIndexes() const { return ShndxIndexes; }
98 };
99 
100 struct ELFWriter {
101  ELFObjectWriter &OWriter;
103 
104  enum DwoMode {
105  AllSections,
106  NonDwoOnly,
107  DwoOnly,
108  } Mode;
109 
110  static uint64_t SymbolValue(const MCSymbol &Sym, const MCAsmLayout &Layout);
111  static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolELF &Symbol,
112  bool Used, bool Renamed);
113 
114  /// Helper struct for containing some precomputed information on symbols.
115  struct ELFSymbolData {
116  const MCSymbolELF *Symbol;
117  StringRef Name;
118  uint32_t SectionIndex;
119  uint32_t Order;
120  };
121 
122  /// @}
123  /// @name Symbol Table Data
124  /// @{
125 
127 
128  /// @}
129 
130  // This holds the symbol table index of the last local symbol.
131  unsigned LastLocalSymbolIndex;
132  // This holds the .strtab section index.
133  unsigned StringTableIndex;
134  // This holds the .symtab section index.
135  unsigned SymbolTableIndex;
136 
137  // Sections in the order they are to be output in the section table.
138  std::vector<const MCSectionELF *> SectionTable;
139  unsigned addToSectionTable(const MCSectionELF *Sec);
140 
141  // TargetObjectWriter wrappers.
142  bool is64Bit() const;
143  bool usesRela(const MCSectionELF &Sec) const;
144 
145  uint64_t align(Align Alignment);
146 
147  bool maybeWriteCompression(uint32_t ChType, uint64_t Size,
148  SmallVectorImpl<uint8_t> &CompressedContents,
149  Align Alignment);
150 
151 public:
152  ELFWriter(ELFObjectWriter &OWriter, raw_pwrite_stream &OS,
153  bool IsLittleEndian, DwoMode Mode)
154  : OWriter(OWriter),
155  W(OS, IsLittleEndian ? support::little : support::big), Mode(Mode) {}
156 
157  void WriteWord(uint64_t Word) {
158  if (is64Bit())
159  W.write<uint64_t>(Word);
160  else
161  W.write<uint32_t>(Word);
162  }
163 
164  template <typename T> void write(T Val) {
165  W.write(Val);
166  }
167 
168  void writeHeader(const MCAssembler &Asm);
169 
170  void writeSymbol(SymbolTableWriter &Writer, uint32_t StringIndex,
171  ELFSymbolData &MSD, const MCAsmLayout &Layout);
172 
173  // Start and end offset of each section
174  using SectionOffsetsTy =
175  std::map<const MCSectionELF *, std::pair<uint64_t, uint64_t>>;
176 
177  // Map from a signature symbol to the group section index
178  using RevGroupMapTy = DenseMap<const MCSymbol *, unsigned>;
179 
180  /// Compute the symbol table data
181  ///
182  /// \param Asm - The assembler.
183  /// \param SectionIndexMap - Maps a section to its index.
184  /// \param RevGroupMap - Maps a signature symbol to the group section.
185  void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
186  const SectionIndexMapTy &SectionIndexMap,
187  const RevGroupMapTy &RevGroupMap,
188  SectionOffsetsTy &SectionOffsets);
189 
190  void writeAddrsigSection();
191 
192  MCSectionELF *createRelocationSection(MCContext &Ctx,
193  const MCSectionELF &Sec);
194 
195  void writeSectionHeader(const MCAsmLayout &Layout,
196  const SectionIndexMapTy &SectionIndexMap,
197  const SectionOffsetsTy &SectionOffsets);
198 
199  void writeSectionData(const MCAssembler &Asm, MCSection &Sec,
200  const MCAsmLayout &Layout);
201 
202  void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
203  uint64_t Address, uint64_t Offset, uint64_t Size,
204  uint32_t Link, uint32_t Info, MaybeAlign Alignment,
205  uint64_t EntrySize);
206 
207  void writeRelocations(const MCAssembler &Asm, const MCSectionELF &Sec);
208 
209  uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout);
210  void writeSection(const SectionIndexMapTy &SectionIndexMap,
211  uint32_t GroupSymbolIndex, uint64_t Offset, uint64_t Size,
212  const MCSectionELF &Section);
213 };
214 
215 class ELFObjectWriter : public MCObjectWriter {
216  /// The target specific ELF writer instance.
217  std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
218 
220 
222 
223  bool SeenGnuAbi = false;
224 
225  bool hasRelocationAddend() const;
226 
227  bool shouldRelocateWithSymbol(const MCAssembler &Asm,
228  const MCSymbolRefExpr *RefA,
229  const MCSymbolELF *Sym, uint64_t C,
230  unsigned Type) const;
231 
232 public:
233  ELFObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW)
234  : TargetObjectWriter(std::move(MOTW)) {}
235 
236  void reset() override {
237  SeenGnuAbi = false;
238  Relocations.clear();
239  Renames.clear();
241  }
242 
243  bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
244  const MCSymbol &SymA,
245  const MCFragment &FB, bool InSet,
246  bool IsPCRel) const override;
247 
248  virtual bool checkRelocation(MCContext &Ctx, SMLoc Loc,
249  const MCSectionELF *From,
250  const MCSectionELF *To) {
251  return true;
252  }
253 
254  void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
255  const MCFragment *Fragment, const MCFixup &Fixup,
256  MCValue Target, uint64_t &FixedValue) override;
257 
258  void executePostLayoutBinding(MCAssembler &Asm,
259  const MCAsmLayout &Layout) override;
260 
261  void markGnuAbi() override { SeenGnuAbi = true; }
262  bool seenGnuAbi() const { return SeenGnuAbi; }
263 
264  friend struct ELFWriter;
265 };
266 
267 class ELFSingleObjectWriter : public ELFObjectWriter {
268  raw_pwrite_stream &OS;
269  bool IsLittleEndian;
270 
271 public:
272  ELFSingleObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
273  raw_pwrite_stream &OS, bool IsLittleEndian)
274  : ELFObjectWriter(std::move(MOTW)), OS(OS),
275  IsLittleEndian(IsLittleEndian) {}
276 
277  uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override {
278  return ELFWriter(*this, OS, IsLittleEndian, ELFWriter::AllSections)
279  .writeObject(Asm, Layout);
280  }
281 
282  friend struct ELFWriter;
283 };
284 
285 class ELFDwoObjectWriter : public ELFObjectWriter {
286  raw_pwrite_stream &OS, &DwoOS;
287  bool IsLittleEndian;
288 
289 public:
290  ELFDwoObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
292  bool IsLittleEndian)
293  : ELFObjectWriter(std::move(MOTW)), OS(OS), DwoOS(DwoOS),
294  IsLittleEndian(IsLittleEndian) {}
295 
296  bool checkRelocation(MCContext &Ctx, SMLoc Loc, const MCSectionELF *From,
297  const MCSectionELF *To) override {
298  if (isDwoSection(*From)) {
299  Ctx.reportError(Loc, "A dwo section may not contain relocations");
300  return false;
301  }
302  if (To && isDwoSection(*To)) {
303  Ctx.reportError(Loc, "A relocation may not refer to a dwo section");
304  return false;
305  }
306  return true;
307  }
308 
309  uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override {
310  uint64_t Size = ELFWriter(*this, OS, IsLittleEndian, ELFWriter::NonDwoOnly)
311  .writeObject(Asm, Layout);
312  Size += ELFWriter(*this, DwoOS, IsLittleEndian, ELFWriter::DwoOnly)
313  .writeObject(Asm, Layout);
314  return Size;
315  }
316 };
317 
318 } // end anonymous namespace
319 
320 uint64_t ELFWriter::align(Align Alignment) {
321  uint64_t Offset = W.OS.tell();
322  uint64_t NewOffset = alignTo(Offset, Alignment);
323  W.OS.write_zeros(NewOffset - Offset);
324  return NewOffset;
325 }
326 
327 unsigned ELFWriter::addToSectionTable(const MCSectionELF *Sec) {
328  SectionTable.push_back(Sec);
329  StrTabBuilder.add(Sec->getName());
330  return SectionTable.size();
331 }
332 
333 void SymbolTableWriter::createSymtabShndx() {
334  if (!ShndxIndexes.empty())
335  return;
336 
337  ShndxIndexes.resize(NumWritten);
338 }
339 
340 template <typename T> void SymbolTableWriter::write(T Value) {
341  EWriter.write(Value);
342 }
343 
344 SymbolTableWriter::SymbolTableWriter(ELFWriter &EWriter, bool Is64Bit)
345  : EWriter(EWriter), Is64Bit(Is64Bit), NumWritten(0) {}
346 
347 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
348  uint64_t size, uint8_t other,
349  uint32_t shndx, bool Reserved) {
350  bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
351 
352  if (LargeIndex)
353  createSymtabShndx();
354 
355  if (!ShndxIndexes.empty()) {
356  if (LargeIndex)
357  ShndxIndexes.push_back(shndx);
358  else
359  ShndxIndexes.push_back(0);
360  }
361 
362  uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
363 
364  if (Is64Bit) {
365  write(name); // st_name
366  write(info); // st_info
367  write(other); // st_other
368  write(Index); // st_shndx
369  write(value); // st_value
370  write(size); // st_size
371  } else {
372  write(name); // st_name
373  write(uint32_t(value)); // st_value
374  write(uint32_t(size)); // st_size
375  write(info); // st_info
376  write(other); // st_other
377  write(Index); // st_shndx
378  }
379 
380  ++NumWritten;
381 }
382 
383 bool ELFWriter::is64Bit() const {
384  return OWriter.TargetObjectWriter->is64Bit();
385 }
386 
387 bool ELFWriter::usesRela(const MCSectionELF &Sec) const {
388  return OWriter.hasRelocationAddend() &&
390 }
391 
392 // Emit the ELF header.
393 void ELFWriter::writeHeader(const MCAssembler &Asm) {
394  // ELF Header
395  // ----------
396  //
397  // Note
398  // ----
399  // emitWord method behaves differently for ELF32 and ELF64, writing
400  // 4 bytes in the former and 8 in the latter.
401 
402  W.OS << ELF::ElfMagic; // e_ident[EI_MAG0] to e_ident[EI_MAG3]
403 
404  W.OS << char(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
405 
406  // e_ident[EI_DATA]
407  W.OS << char(W.Endian == support::little ? ELF::ELFDATA2LSB
408  : ELF::ELFDATA2MSB);
409 
410  W.OS << char(ELF::EV_CURRENT); // e_ident[EI_VERSION]
411  // e_ident[EI_OSABI]
412  uint8_t OSABI = OWriter.TargetObjectWriter->getOSABI();
413  W.OS << char(OSABI == ELF::ELFOSABI_NONE && OWriter.seenGnuAbi()
414  ? int(ELF::ELFOSABI_GNU)
415  : OSABI);
416  // e_ident[EI_ABIVERSION]
417  W.OS << char(OWriter.TargetObjectWriter->getABIVersion());
418 
419  W.OS.write_zeros(ELF::EI_NIDENT - ELF::EI_PAD);
420 
421  W.write<uint16_t>(ELF::ET_REL); // e_type
422 
423  W.write<uint16_t>(OWriter.TargetObjectWriter->getEMachine()); // e_machine = target
424 
425  W.write<uint32_t>(ELF::EV_CURRENT); // e_version
426  WriteWord(0); // e_entry, no entry point in .o file
427  WriteWord(0); // e_phoff, no program header for .o
428  WriteWord(0); // e_shoff = sec hdr table off in bytes
429 
430  // e_flags = whatever the target wants
431  W.write<uint32_t>(Asm.getELFHeaderEFlags());
432 
433  // e_ehsize = ELF header size
434  W.write<uint16_t>(is64Bit() ? sizeof(ELF::Elf64_Ehdr)
435  : sizeof(ELF::Elf32_Ehdr));
436 
437  W.write<uint16_t>(0); // e_phentsize = prog header entry size
438  W.write<uint16_t>(0); // e_phnum = # prog header entries = 0
439 
440  // e_shentsize = Section header entry size
441  W.write<uint16_t>(is64Bit() ? sizeof(ELF::Elf64_Shdr)
442  : sizeof(ELF::Elf32_Shdr));
443 
444  // e_shnum = # of section header ents
445  W.write<uint16_t>(0);
446 
447  // e_shstrndx = Section # of '.strtab'
448  assert(StringTableIndex < ELF::SHN_LORESERVE);
449  W.write<uint16_t>(StringTableIndex);
450 }
451 
452 uint64_t ELFWriter::SymbolValue(const MCSymbol &Sym,
453  const MCAsmLayout &Layout) {
454  if (Sym.isCommon())
455  return Sym.getCommonAlignment();
456 
457  uint64_t Res;
458  if (!Layout.getSymbolOffset(Sym, Res))
459  return 0;
460 
461  if (Layout.getAssembler().isThumbFunc(&Sym))
462  Res |= 1;
463 
464  return Res;
465 }
466 
467 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
468  uint8_t Type = newType;
469 
470  // Propagation rules:
471  // IFUNC > FUNC > OBJECT > NOTYPE
472  // TLS_OBJECT > OBJECT > NOTYPE
473  //
474  // dont let the new type degrade the old type
475  switch (origType) {
476  default:
477  break;
478  case ELF::STT_GNU_IFUNC:
479  if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
482  break;
483  case ELF::STT_FUNC:
484  if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
485  Type == ELF::STT_TLS)
487  break;
488  case ELF::STT_OBJECT:
489  if (Type == ELF::STT_NOTYPE)
491  break;
492  case ELF::STT_TLS:
493  if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
495  Type = ELF::STT_TLS;
496  break;
497  }
498 
499  return Type;
500 }
501 
502 static bool isIFunc(const MCSymbolELF *Symbol) {
503  while (Symbol->getType() != ELF::STT_GNU_IFUNC) {
504  const MCSymbolRefExpr *Value;
505  if (!Symbol->isVariable() ||
506  !(Value = dyn_cast<MCSymbolRefExpr>(Symbol->getVariableValue())) ||
507  Value->getKind() != MCSymbolRefExpr::VK_None ||
509  return false;
510  Symbol = &cast<MCSymbolELF>(Value->getSymbol());
511  }
512  return true;
513 }
514 
515 void ELFWriter::writeSymbol(SymbolTableWriter &Writer, uint32_t StringIndex,
516  ELFSymbolData &MSD, const MCAsmLayout &Layout) {
517  const auto &Symbol = cast<MCSymbolELF>(*MSD.Symbol);
518  const MCSymbolELF *Base =
519  cast_or_null<MCSymbolELF>(Layout.getBaseSymbol(Symbol));
520 
521  // This has to be in sync with when computeSymbolTable uses SHN_ABS or
522  // SHN_COMMON.
523  bool IsReserved = !Base || Symbol.isCommon();
524 
525  // Binding and Type share the same byte as upper and lower nibbles
526  uint8_t Binding = Symbol.getBinding();
527  uint8_t Type = Symbol.getType();
528  if (isIFunc(&Symbol))
530  if (Base) {
531  Type = mergeTypeForSet(Type, Base->getType());
532  }
533  uint8_t Info = (Binding << 4) | Type;
534 
535  // Other and Visibility share the same byte with Visibility using the lower
536  // 2 bits
537  uint8_t Visibility = Symbol.getVisibility();
538  uint8_t Other = Symbol.getOther() | Visibility;
539 
540  uint64_t Value = SymbolValue(*MSD.Symbol, Layout);
541  uint64_t Size = 0;
542 
543  const MCExpr *ESize = MSD.Symbol->getSize();
544  if (!ESize && Base) {
545  // For expressions like .set y, x+1, if y's size is unset, inherit from x.
546  ESize = Base->getSize();
547 
548  // For `.size x, 2; y = x; .size y, 1; z = y; z1 = z; .symver y, y@v1`, z,
549  // z1, and y@v1's st_size equals y's. However, `Base` is `x` which will give
550  // us 2. Follow the MCSymbolRefExpr assignment chain, which covers most
551  // needs. MCBinaryExpr is not handled.
552  const MCSymbolELF *Sym = &Symbol;
553  while (Sym->isVariable()) {
554  if (auto *Expr =
555  dyn_cast<MCSymbolRefExpr>(Sym->getVariableValue(false))) {
556  Sym = cast<MCSymbolELF>(&Expr->getSymbol());
557  if (!Sym->getSize())
558  continue;
559  ESize = Sym->getSize();
560  }
561  break;
562  }
563  }
564 
565  if (ESize) {
566  int64_t Res;
567  if (!ESize->evaluateKnownAbsolute(Res, Layout))
568  report_fatal_error("Size expression must be absolute.");
569  Size = Res;
570  }
571 
572  // Write out the symbol table entry
573  Writer.writeSymbol(StringIndex, Info, Value, Size, Other, MSD.SectionIndex,
574  IsReserved);
575 }
576 
577 bool ELFWriter::isInSymtab(const MCAsmLayout &Layout, const MCSymbolELF &Symbol,
578  bool Used, bool Renamed) {
579  if (Symbol.isVariable()) {
580  const MCExpr *Expr = Symbol.getVariableValue();
581  // Target Expressions that are always inlined do not appear in the symtab
582  if (const auto *T = dyn_cast<MCTargetExpr>(Expr))
583  if (T->inlineAssignedExpr())
584  return false;
585  if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
586  if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
587  return false;
588  }
589  }
590 
591  if (Used)
592  return true;
593 
594  if (Renamed)
595  return false;
596 
597  if (Symbol.isVariable() && Symbol.isUndefined()) {
598  // FIXME: this is here just to diagnose the case of a var = commmon_sym.
599  Layout.getBaseSymbol(Symbol);
600  return false;
601  }
602 
603  if (Symbol.isTemporary())
604  return false;
605 
606  if (Symbol.getType() == ELF::STT_SECTION)
607  return false;
608 
609  return true;
610 }
611 
612 void ELFWriter::computeSymbolTable(
613  MCAssembler &Asm, const MCAsmLayout &Layout,
614  const SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap,
615  SectionOffsetsTy &SectionOffsets) {
616  MCContext &Ctx = Asm.getContext();
617  SymbolTableWriter Writer(*this, is64Bit());
618 
619  // Symbol table
620  unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
621  MCSectionELF *SymtabSection =
622  Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize);
623  SymtabSection->setAlignment(is64Bit() ? Align(8) : Align(4));
624  SymbolTableIndex = addToSectionTable(SymtabSection);
625 
626  uint64_t SecStart = align(SymtabSection->getAlign());
627 
628  // The first entry is the undefined symbol entry.
629  Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
630 
631  std::vector<ELFSymbolData> LocalSymbolData;
632  std::vector<ELFSymbolData> ExternalSymbolData;
634  Asm.getFileNames();
635  for (const std::pair<std::string, size_t> &F : FileNames)
636  StrTabBuilder.add(F.first);
637 
638  // Add the data for the symbols.
639  bool HasLargeSectionIndex = false;
640  for (auto It : llvm::enumerate(Asm.symbols())) {
641  const auto &Symbol = cast<MCSymbolELF>(It.value());
642  bool Used = Symbol.isUsedInReloc();
643  bool WeakrefUsed = Symbol.isWeakrefUsedInReloc();
644  bool isSignature = Symbol.isSignature();
645 
646  if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
647  OWriter.Renames.count(&Symbol)))
648  continue;
649 
650  if (Symbol.isTemporary() && Symbol.isUndefined()) {
651  Ctx.reportError(SMLoc(), "Undefined temporary symbol " + Symbol.getName());
652  continue;
653  }
654 
655  ELFSymbolData MSD;
656  MSD.Symbol = cast<MCSymbolELF>(&Symbol);
657  MSD.Order = It.index();
658 
659  bool Local = Symbol.getBinding() == ELF::STB_LOCAL;
660  assert(Local || !Symbol.isTemporary());
661 
662  if (Symbol.isAbsolute()) {
663  MSD.SectionIndex = ELF::SHN_ABS;
664  } else if (Symbol.isCommon()) {
665  if (Symbol.isTargetCommon()) {
666  MSD.SectionIndex = Symbol.getIndex();
667  } else {
668  assert(!Local);
669  MSD.SectionIndex = ELF::SHN_COMMON;
670  }
671  } else if (Symbol.isUndefined()) {
672  if (isSignature && !Used) {
673  MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
674  if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
675  HasLargeSectionIndex = true;
676  } else {
677  MSD.SectionIndex = ELF::SHN_UNDEF;
678  }
679  } else {
680  const MCSectionELF &Section =
681  static_cast<const MCSectionELF &>(Symbol.getSection());
682 
683  // We may end up with a situation when section symbol is technically
684  // defined, but should not be. That happens because we explicitly
685  // pre-create few .debug_* sections to have accessors.
686  // And if these sections were not really defined in the code, but were
687  // referenced, we simply error out.
688  if (!Section.isRegistered()) {
689  assert(static_cast<const MCSymbolELF &>(Symbol).getType() ==
691  Ctx.reportError(SMLoc(),
692  "Undefined section reference: " + Symbol.getName());
693  continue;
694  }
695 
696  if (Mode == NonDwoOnly && isDwoSection(Section))
697  continue;
698  MSD.SectionIndex = SectionIndexMap.lookup(&Section);
699  assert(MSD.SectionIndex && "Invalid section index!");
700  if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
701  HasLargeSectionIndex = true;
702  }
703 
704  StringRef Name = Symbol.getName();
705 
706  // Sections have their own string table
707  if (Symbol.getType() != ELF::STT_SECTION) {
708  MSD.Name = Name;
709  StrTabBuilder.add(Name);
710  }
711 
712  if (Local)
713  LocalSymbolData.push_back(MSD);
714  else
715  ExternalSymbolData.push_back(MSD);
716  }
717 
718  // This holds the .symtab_shndx section index.
719  unsigned SymtabShndxSectionIndex = 0;
720 
721  if (HasLargeSectionIndex) {
722  MCSectionELF *SymtabShndxSection =
723  Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0, 4);
724  SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
725  SymtabShndxSection->setAlignment(Align(4));
726  }
727 
728  StrTabBuilder.finalize();
729 
730  // Make the first STT_FILE precede previous local symbols.
731  unsigned Index = 1;
732  auto FileNameIt = FileNames.begin();
733  if (!FileNames.empty())
734  FileNames[0].second = 0;
735 
736  for (ELFSymbolData &MSD : LocalSymbolData) {
737  // Emit STT_FILE symbols before their associated local symbols.
738  for (; FileNameIt != FileNames.end() && FileNameIt->second <= MSD.Order;
739  ++FileNameIt) {
740  Writer.writeSymbol(StrTabBuilder.getOffset(FileNameIt->first),
742  ELF::SHN_ABS, true);
743  ++Index;
744  }
745 
746  unsigned StringIndex = MSD.Symbol->getType() == ELF::STT_SECTION
747  ? 0
748  : StrTabBuilder.getOffset(MSD.Name);
749  MSD.Symbol->setIndex(Index++);
750  writeSymbol(Writer, StringIndex, MSD, Layout);
751  }
752  for (; FileNameIt != FileNames.end(); ++FileNameIt) {
753  Writer.writeSymbol(StrTabBuilder.getOffset(FileNameIt->first),
755  ELF::SHN_ABS, true);
756  ++Index;
757  }
758 
759  // Write the symbol table entries.
760  LastLocalSymbolIndex = Index;
761 
762  for (ELFSymbolData &MSD : ExternalSymbolData) {
763  unsigned StringIndex = StrTabBuilder.getOffset(MSD.Name);
764  MSD.Symbol->setIndex(Index++);
765  writeSymbol(Writer, StringIndex, MSD, Layout);
766  assert(MSD.Symbol->getBinding() != ELF::STB_LOCAL);
767  }
768 
769  uint64_t SecEnd = W.OS.tell();
770  SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
771 
772  ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
773  if (ShndxIndexes.empty()) {
774  assert(SymtabShndxSectionIndex == 0);
775  return;
776  }
777  assert(SymtabShndxSectionIndex != 0);
778 
779  SecStart = W.OS.tell();
780  const MCSectionELF *SymtabShndxSection =
781  SectionTable[SymtabShndxSectionIndex - 1];
782  for (uint32_t Index : ShndxIndexes)
783  write(Index);
784  SecEnd = W.OS.tell();
785  SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
786 }
787 
788 void ELFWriter::writeAddrsigSection() {
789  for (const MCSymbol *Sym : OWriter.AddrsigSyms)
790  if (Sym->getIndex() != 0)
791  encodeULEB128(Sym->getIndex(), W.OS);
792 }
793 
794 MCSectionELF *ELFWriter::createRelocationSection(MCContext &Ctx,
795  const MCSectionELF &Sec) {
796  if (OWriter.Relocations[&Sec].empty())
797  return nullptr;
798 
799  const StringRef SectionName = Sec.getName();
800  bool Rela = usesRela(Sec);
801  std::string RelaSectionName = Rela ? ".rela" : ".rel";
802  RelaSectionName += SectionName;
803 
804  unsigned EntrySize;
805  if (Rela)
806  EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
807  else
808  EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
809 
810  unsigned Flags = ELF::SHF_INFO_LINK;
811  if (Sec.getFlags() & ELF::SHF_GROUP)
812  Flags = ELF::SHF_GROUP;
813 
814  MCSectionELF *RelaSection = Ctx.createELFRelSection(
815  RelaSectionName, Rela ? ELF::SHT_RELA : ELF::SHT_REL, Flags, EntrySize,
816  Sec.getGroup(), &Sec);
817  RelaSection->setAlignment(is64Bit() ? Align(8) : Align(4));
818  return RelaSection;
819 }
820 
821 // Include the debug info compression header.
822 bool ELFWriter::maybeWriteCompression(
823  uint32_t ChType, uint64_t Size,
824  SmallVectorImpl<uint8_t> &CompressedContents, Align Alignment) {
825  uint64_t HdrSize =
826  is64Bit() ? sizeof(ELF::Elf32_Chdr) : sizeof(ELF::Elf64_Chdr);
827  if (Size <= HdrSize + CompressedContents.size())
828  return false;
829  // Platform specific header is followed by compressed data.
830  if (is64Bit()) {
831  // Write Elf64_Chdr header.
832  write(static_cast<ELF::Elf64_Word>(ChType));
833  write(static_cast<ELF::Elf64_Word>(0)); // ch_reserved field.
834  write(static_cast<ELF::Elf64_Xword>(Size));
835  write(static_cast<ELF::Elf64_Xword>(Alignment.value()));
836  } else {
837  // Write Elf32_Chdr header otherwise.
838  write(static_cast<ELF::Elf32_Word>(ChType));
839  write(static_cast<ELF::Elf32_Word>(Size));
840  write(static_cast<ELF::Elf32_Word>(Alignment.value()));
841  }
842  return true;
843 }
844 
845 void ELFWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
846  const MCAsmLayout &Layout) {
847  MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
848  StringRef SectionName = Section.getName();
849 
850  auto &MC = Asm.getContext();
851  const auto &MAI = MC.getAsmInfo();
852 
853  const DebugCompressionType CompressionType = MAI->compressDebugSections();
854  if (CompressionType == DebugCompressionType::None ||
855  !SectionName.startswith(".debug_")) {
856  Asm.writeSectionData(W.OS, &Section, Layout);
857  return;
858  }
859 
860  SmallVector<char, 128> UncompressedData;
861  raw_svector_ostream VecOS(UncompressedData);
862  Asm.writeSectionData(VecOS, &Section, Layout);
863  ArrayRef<uint8_t> Uncompressed =
864  makeArrayRef(reinterpret_cast<uint8_t *>(UncompressedData.data()),
865  UncompressedData.size());
866 
867  SmallVector<uint8_t, 128> Compressed;
868  uint32_t ChType;
869  switch (CompressionType) {
871  llvm_unreachable("has been handled");
872  case DebugCompressionType::Zlib:
873  ChType = ELF::ELFCOMPRESS_ZLIB;
874  break;
875  case DebugCompressionType::Zstd:
876  ChType = ELF::ELFCOMPRESS_ZSTD;
877  break;
878  }
879  compression::compress(compression::Params(CompressionType), Uncompressed,
880  Compressed);
881  if (!maybeWriteCompression(ChType, UncompressedData.size(), Compressed,
882  Sec.getAlign())) {
883  W.OS << UncompressedData;
884  return;
885  }
886 
887  Section.setFlags(Section.getFlags() | ELF::SHF_COMPRESSED);
888  // Alignment field should reflect the requirements of
889  // the compressed section header.
890  Section.setAlignment(is64Bit() ? Align(8) : Align(4));
891  W.OS << toStringRef(Compressed);
892 }
893 
894 void ELFWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
895  uint64_t Address, uint64_t Offset,
897  MaybeAlign Alignment, uint64_t EntrySize) {
898  W.write<uint32_t>(Name); // sh_name: index into string table
899  W.write<uint32_t>(Type); // sh_type
900  WriteWord(Flags); // sh_flags
901  WriteWord(Address); // sh_addr
902  WriteWord(Offset); // sh_offset
903  WriteWord(Size); // sh_size
904  W.write<uint32_t>(Link); // sh_link
905  W.write<uint32_t>(Info); // sh_info
906  WriteWord(Alignment ? Alignment->value() : 0); // sh_addralign
907  WriteWord(EntrySize); // sh_entsize
908 }
909 
910 void ELFWriter::writeRelocations(const MCAssembler &Asm,
911  const MCSectionELF &Sec) {
912  std::vector<ELFRelocationEntry> &Relocs = OWriter.Relocations[&Sec];
913 
914  // We record relocations by pushing to the end of a vector. Reverse the vector
915  // to get the relocations in the order they were created.
916  // In most cases that is not important, but it can be for special sections
917  // (.eh_frame) or specific relocations (TLS optimizations on SystemZ).
918  std::reverse(Relocs.begin(), Relocs.end());
919 
920  // Sort the relocation entries. MIPS needs this.
921  OWriter.TargetObjectWriter->sortRelocs(Asm, Relocs);
922 
923  const bool Rela = usesRela(Sec);
924  for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
925  const ELFRelocationEntry &Entry = Relocs[e - i - 1];
926  unsigned Index = Entry.Symbol ? Entry.Symbol->getIndex() : 0;
927 
928  if (is64Bit()) {
929  write(Entry.Offset);
930  if (OWriter.TargetObjectWriter->getEMachine() == ELF::EM_MIPS) {
931  write(uint32_t(Index));
932 
933  write(OWriter.TargetObjectWriter->getRSsym(Entry.Type));
934  write(OWriter.TargetObjectWriter->getRType3(Entry.Type));
935  write(OWriter.TargetObjectWriter->getRType2(Entry.Type));
936  write(OWriter.TargetObjectWriter->getRType(Entry.Type));
937  } else {
938  struct ELF::Elf64_Rela ERE64;
939  ERE64.setSymbolAndType(Index, Entry.Type);
940  write(ERE64.r_info);
941  }
942  if (Rela)
943  write(Entry.Addend);
944  } else {
945  write(uint32_t(Entry.Offset));
946 
947  struct ELF::Elf32_Rela ERE32;
948  ERE32.setSymbolAndType(Index, Entry.Type);
949  write(ERE32.r_info);
950 
951  if (Rela)
952  write(uint32_t(Entry.Addend));
953 
954  if (OWriter.TargetObjectWriter->getEMachine() == ELF::EM_MIPS) {
955  if (uint32_t RType =
956  OWriter.TargetObjectWriter->getRType2(Entry.Type)) {
957  write(uint32_t(Entry.Offset));
958 
959  ERE32.setSymbolAndType(0, RType);
960  write(ERE32.r_info);
961  write(uint32_t(0));
962  }
963  if (uint32_t RType =
964  OWriter.TargetObjectWriter->getRType3(Entry.Type)) {
965  write(uint32_t(Entry.Offset));
966 
967  ERE32.setSymbolAndType(0, RType);
968  write(ERE32.r_info);
969  write(uint32_t(0));
970  }
971  }
972  }
973  }
974 }
975 
976 void ELFWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
977  uint32_t GroupSymbolIndex, uint64_t Offset,
978  uint64_t Size, const MCSectionELF &Section) {
979  uint64_t sh_link = 0;
980  uint64_t sh_info = 0;
981 
982  switch(Section.getType()) {
983  default:
984  // Nothing to do.
985  break;
986 
987  case ELF::SHT_DYNAMIC:
988  llvm_unreachable("SHT_DYNAMIC in a relocatable object");
989 
990  case ELF::SHT_REL:
991  case ELF::SHT_RELA: {
992  sh_link = SymbolTableIndex;
993  assert(sh_link && ".symtab not found");
994  const MCSection *InfoSection = Section.getLinkedToSection();
995  sh_info = SectionIndexMap.lookup(cast<MCSectionELF>(InfoSection));
996  break;
997  }
998 
999  case ELF::SHT_SYMTAB:
1000  sh_link = StringTableIndex;
1001  sh_info = LastLocalSymbolIndex;
1002  break;
1003 
1004  case ELF::SHT_SYMTAB_SHNDX:
1006  case ELF::SHT_LLVM_ADDRSIG:
1007  sh_link = SymbolTableIndex;
1008  break;
1009 
1010  case ELF::SHT_GROUP:
1011  sh_link = SymbolTableIndex;
1012  sh_info = GroupSymbolIndex;
1013  break;
1014  }
1015 
1016  if (Section.getFlags() & ELF::SHF_LINK_ORDER) {
1017  // If the value in the associated metadata is not a definition, Sym will be
1018  // undefined. Represent this with sh_link=0.
1019  const MCSymbol *Sym = Section.getLinkedToSymbol();
1020  if (Sym && Sym->isInSection()) {
1021  const MCSectionELF *Sec = cast<MCSectionELF>(&Sym->getSection());
1022  sh_link = SectionIndexMap.lookup(Sec);
1023  }
1024  }
1025 
1026  WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getName()),
1027  Section.getType(), Section.getFlags(), 0, Offset, Size,
1028  sh_link, sh_info, Section.getAlign(),
1029  Section.getEntrySize());
1030 }
1031 
1032 void ELFWriter::writeSectionHeader(
1033  const MCAsmLayout &Layout, const SectionIndexMapTy &SectionIndexMap,
1034  const SectionOffsetsTy &SectionOffsets) {
1035  const unsigned NumSections = SectionTable.size();
1036 
1037  // Null section first.
1038  uint64_t FirstSectionSize =
1039  (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1040  WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, None, 0);
1041 
1042  for (const MCSectionELF *Section : SectionTable) {
1043  uint32_t GroupSymbolIndex;
1044  unsigned Type = Section->getType();
1045  if (Type != ELF::SHT_GROUP)
1046  GroupSymbolIndex = 0;
1047  else
1048  GroupSymbolIndex = Section->getGroup()->getIndex();
1049 
1050  const std::pair<uint64_t, uint64_t> &Offsets =
1051  SectionOffsets.find(Section)->second;
1052  uint64_t Size;
1053  if (Type == ELF::SHT_NOBITS)
1055  else
1056  Size = Offsets.second - Offsets.first;
1057 
1058  writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1059  *Section);
1060  }
1061 }
1062 
1063 uint64_t ELFWriter::writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
1064  uint64_t StartOffset = W.OS.tell();
1065 
1066  MCContext &Ctx = Asm.getContext();
1067  MCSectionELF *StrtabSection =
1068  Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1069  StringTableIndex = addToSectionTable(StrtabSection);
1070 
1071  RevGroupMapTy RevGroupMap;
1072  SectionIndexMapTy SectionIndexMap;
1073 
1074  std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
1075 
1076  // Write out the ELF header ...
1077  writeHeader(Asm);
1078 
1079  // ... then the sections ...
1080  SectionOffsetsTy SectionOffsets;
1081  std::vector<MCSectionELF *> Groups;
1082  std::vector<MCSectionELF *> Relocations;
1083  for (MCSection &Sec : Asm) {
1084  MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1085  if (Mode == NonDwoOnly && isDwoSection(Section))
1086  continue;
1087  if (Mode == DwoOnly && !isDwoSection(Section))
1088  continue;
1089 
1090  // Remember the offset into the file for this section.
1091  const uint64_t SecStart = align(Section.getAlign());
1092 
1093  const MCSymbolELF *SignatureSymbol = Section.getGroup();
1094  writeSectionData(Asm, Section, Layout);
1095 
1096  uint64_t SecEnd = W.OS.tell();
1097  SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1098 
1099  MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
1100 
1101  if (SignatureSymbol) {
1102  unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1103  if (!GroupIdx) {
1104  MCSectionELF *Group =
1105  Ctx.createELFGroupSection(SignatureSymbol, Section.isComdat());
1106  GroupIdx = addToSectionTable(Group);
1107  Group->setAlignment(Align(4));
1108  Groups.push_back(Group);
1109  }
1110  std::vector<const MCSectionELF *> &Members =
1111  GroupMembers[SignatureSymbol];
1112  Members.push_back(&Section);
1113  if (RelSection)
1114  Members.push_back(RelSection);
1115  }
1116 
1117  SectionIndexMap[&Section] = addToSectionTable(&Section);
1118  if (RelSection) {
1119  SectionIndexMap[RelSection] = addToSectionTable(RelSection);
1120  Relocations.push_back(RelSection);
1121  }
1122 
1123  OWriter.TargetObjectWriter->addTargetSectionFlags(Ctx, Section);
1124  }
1125 
1126  for (MCSectionELF *Group : Groups) {
1127  // Remember the offset into the file for this section.
1128  const uint64_t SecStart = align(Group->getAlign());
1129 
1130  const MCSymbol *SignatureSymbol = Group->getGroup();
1131  assert(SignatureSymbol);
1132  write(uint32_t(Group->isComdat() ? unsigned(ELF::GRP_COMDAT) : 0));
1133  for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
1134  uint32_t SecIndex = SectionIndexMap.lookup(Member);
1135  write(SecIndex);
1136  }
1137 
1138  uint64_t SecEnd = W.OS.tell();
1139  SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
1140  }
1141 
1142  if (Mode == DwoOnly) {
1143  // dwo files don't have symbol tables or relocations, but they do have
1144  // string tables.
1145  StrTabBuilder.finalize();
1146  } else {
1147  MCSectionELF *AddrsigSection;
1148  if (OWriter.EmitAddrsigSection) {
1149  AddrsigSection = Ctx.getELFSection(".llvm_addrsig", ELF::SHT_LLVM_ADDRSIG,
1151  addToSectionTable(AddrsigSection);
1152  }
1153 
1154  // Compute symbol table information.
1155  computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1156  SectionOffsets);
1157 
1158  for (MCSectionELF *RelSection : Relocations) {
1159  // Remember the offset into the file for this section.
1160  const uint64_t SecStart = align(RelSection->getAlign());
1161 
1162  writeRelocations(Asm,
1163  cast<MCSectionELF>(*RelSection->getLinkedToSection()));
1164 
1165  uint64_t SecEnd = W.OS.tell();
1166  SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
1167  }
1168 
1169  if (OWriter.EmitAddrsigSection) {
1170  uint64_t SecStart = W.OS.tell();
1171  writeAddrsigSection();
1172  uint64_t SecEnd = W.OS.tell();
1173  SectionOffsets[AddrsigSection] = std::make_pair(SecStart, SecEnd);
1174  }
1175  }
1176 
1177  {
1178  uint64_t SecStart = W.OS.tell();
1179  StrTabBuilder.write(W.OS);
1180  SectionOffsets[StrtabSection] = std::make_pair(SecStart, W.OS.tell());
1181  }
1182 
1183  const uint64_t SectionHeaderOffset = align(is64Bit() ? Align(8) : Align(4));
1184 
1185  // ... then the section header table ...
1186  writeSectionHeader(Layout, SectionIndexMap, SectionOffsets);
1187 
1188  uint16_t NumSections = support::endian::byte_swap<uint16_t>(
1189  (SectionTable.size() + 1 >= ELF::SHN_LORESERVE) ? (uint16_t)ELF::SHN_UNDEF
1190  : SectionTable.size() + 1,
1191  W.Endian);
1192  unsigned NumSectionsOffset;
1193 
1194  auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
1195  if (is64Bit()) {
1196  uint64_t Val =
1197  support::endian::byte_swap<uint64_t>(SectionHeaderOffset, W.Endian);
1198  Stream.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1199  offsetof(ELF::Elf64_Ehdr, e_shoff));
1200  NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
1201  } else {
1202  uint32_t Val =
1203  support::endian::byte_swap<uint32_t>(SectionHeaderOffset, W.Endian);
1204  Stream.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1205  offsetof(ELF::Elf32_Ehdr, e_shoff));
1206  NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
1207  }
1208  Stream.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
1209  NumSectionsOffset);
1210 
1211  return W.OS.tell() - StartOffset;
1212 }
1213 
1214 bool ELFObjectWriter::hasRelocationAddend() const {
1215  return TargetObjectWriter->hasRelocationAddend();
1216 }
1217 
1218 void ELFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
1219  const MCAsmLayout &Layout) {
1220  // The presence of symbol versions causes undefined symbols and
1221  // versions declared with @@@ to be renamed.
1222  for (const MCAssembler::Symver &S : Asm.Symvers) {
1223  StringRef AliasName = S.Name;
1224  const auto &Symbol = cast<MCSymbolELF>(*S.Sym);
1225  size_t Pos = AliasName.find('@');
1226  assert(Pos != StringRef::npos);
1227 
1228  StringRef Prefix = AliasName.substr(0, Pos);
1229  StringRef Rest = AliasName.substr(Pos);
1230  StringRef Tail = Rest;
1231  if (Rest.startswith("@@@"))
1232  Tail = Rest.substr(Symbol.isUndefined() ? 2 : 1);
1233 
1234  auto *Alias =
1235  cast<MCSymbolELF>(Asm.getContext().getOrCreateSymbol(Prefix + Tail));
1236  Asm.registerSymbol(*Alias);
1237  const MCExpr *Value = MCSymbolRefExpr::create(&Symbol, Asm.getContext());
1238  Alias->setVariableValue(Value);
1239 
1240  // Aliases defined with .symvar copy the binding from the symbol they alias.
1241  // This is the first place we are able to copy this information.
1242  Alias->setBinding(Symbol.getBinding());
1243  Alias->setVisibility(Symbol.getVisibility());
1244  Alias->setOther(Symbol.getOther());
1245 
1246  if (!Symbol.isUndefined() && S.KeepOriginalSym)
1247  continue;
1248 
1249  if (Symbol.isUndefined() && Rest.startswith("@@") &&
1250  !Rest.startswith("@@@")) {
1251  Asm.getContext().reportError(S.Loc, "default version symbol " +
1252  AliasName + " must be defined");
1253  continue;
1254  }
1255 
1256  if (Renames.count(&Symbol) && Renames[&Symbol] != Alias) {
1257  Asm.getContext().reportError(S.Loc, Twine("multiple versions for ") +
1258  Symbol.getName());
1259  continue;
1260  }
1261 
1262  Renames.insert(std::make_pair(&Symbol, Alias));
1263  }
1264 
1265  for (const MCSymbol *&Sym : AddrsigSyms) {
1266  if (const MCSymbol *R = Renames.lookup(cast<MCSymbolELF>(Sym)))
1267  Sym = R;
1268  if (Sym->isInSection() && Sym->getName().startswith(".L"))
1269  Sym = Sym->getSection().getBeginSymbol();
1270  Sym->setUsedInReloc();
1271  }
1272 }
1273 
1274 // It is always valid to create a relocation with a symbol. It is preferable
1275 // to use a relocation with a section if that is possible. Using the section
1276 // allows us to omit some local symbols from the symbol table.
1277 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
1278  const MCSymbolRefExpr *RefA,
1279  const MCSymbolELF *Sym,
1280  uint64_t C,
1281  unsigned Type) const {
1282  // A PCRel relocation to an absolute value has no symbol (or section). We
1283  // represent that with a relocation to a null section.
1284  if (!RefA)
1285  return false;
1286 
1288  switch (Kind) {
1289  default:
1290  break;
1291  // The .odp creation emits a relocation against the symbol ".TOC." which
1292  // create a R_PPC64_TOC relocation. However the relocation symbol name
1293  // in final object creation should be NULL, since the symbol does not
1294  // really exist, it is just the reference to TOC base for the current
1295  // object file. Since the symbol is undefined, returning false results
1296  // in a relocation with a null section which is the desired result.
1297  case MCSymbolRefExpr::VK_PPC_TOCBASE:
1298  return false;
1299 
1300  // These VariantKind cause the relocation to refer to something other than
1301  // the symbol itself, like a linker generated table. Since the address of
1302  // symbol is not relevant, we cannot replace the symbol with the
1303  // section and patch the difference in the addend.
1304  case MCSymbolRefExpr::VK_GOT:
1305  case MCSymbolRefExpr::VK_PLT:
1306  case MCSymbolRefExpr::VK_GOTPCREL:
1307  case MCSymbolRefExpr::VK_GOTPCREL_NORELAX:
1308  case MCSymbolRefExpr::VK_PPC_GOT_LO:
1309  case MCSymbolRefExpr::VK_PPC_GOT_HI:
1310  case MCSymbolRefExpr::VK_PPC_GOT_HA:
1311  return true;
1312  }
1313 
1314  // An undefined symbol is not in any section, so the relocation has to point
1315  // to the symbol itself.
1316  assert(Sym && "Expected a symbol");
1317  if (Sym->isUndefined())
1318  return true;
1319 
1320  unsigned Binding = Sym->getBinding();
1321  switch(Binding) {
1322  default:
1323  llvm_unreachable("Invalid Binding");
1324  case ELF::STB_LOCAL:
1325  break;
1326  case ELF::STB_WEAK:
1327  // If the symbol is weak, it might be overridden by a symbol in another
1328  // file. The relocation has to point to the symbol so that the linker
1329  // can update it.
1330  return true;
1331  case ELF::STB_GLOBAL:
1332  case ELF::STB_GNU_UNIQUE:
1333  // Global ELF symbols can be preempted by the dynamic linker. The relocation
1334  // has to point to the symbol for a reason analogous to the STB_WEAK case.
1335  return true;
1336  }
1337 
1338  // Keep symbol type for a local ifunc because it may result in an IRELATIVE
1339  // reloc that the dynamic loader will use to resolve the address at startup
1340  // time.
1341  if (Sym->getType() == ELF::STT_GNU_IFUNC)
1342  return true;
1343 
1344  // If a relocation points to a mergeable section, we have to be careful.
1345  // If the offset is zero, a relocation with the section will encode the
1346  // same information. With a non-zero offset, the situation is different.
1347  // For example, a relocation can point 42 bytes past the end of a string.
1348  // If we change such a relocation to use the section, the linker would think
1349  // that it pointed to another string and subtracting 42 at runtime will
1350  // produce the wrong value.
1351  if (Sym->isInSection()) {
1352  auto &Sec = cast<MCSectionELF>(Sym->getSection());
1353  unsigned Flags = Sec.getFlags();
1354  if (Flags & ELF::SHF_MERGE) {
1355  if (C != 0)
1356  return true;
1357 
1358  // gold<2.34 incorrectly ignored the addend for R_386_GOTOFF (9)
1359  // (http://sourceware.org/PR16794).
1360  if (TargetObjectWriter->getEMachine() == ELF::EM_386 &&
1361  Type == ELF::R_386_GOTOFF)
1362  return true;
1363 
1364  // ld.lld handles R_MIPS_HI16/R_MIPS_LO16 separately, not as a whole, so
1365  // it doesn't know that an R_MIPS_HI16 with implicit addend 1 and an
1366  // R_MIPS_LO16 with implicit addend -32768 represents 32768, which is in
1367  // range of a MergeInputSection. We could introduce a new RelExpr member
1368  // (like R_RISCV_PC_INDIRECT for R_RISCV_PCREL_HI20 / R_RISCV_PCREL_LO12)
1369  // but the complexity is unnecessary given that GNU as keeps the original
1370  // symbol for this case as well.
1371  if (TargetObjectWriter->getEMachine() == ELF::EM_MIPS &&
1372  !hasRelocationAddend())
1373  return true;
1374  }
1375 
1376  // Most TLS relocations use a got, so they need the symbol. Even those that
1377  // are just an offset (@tpoff), require a symbol in gold versions before
1378  // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
1379  // http://sourceware.org/PR16773.
1380  if (Flags & ELF::SHF_TLS)
1381  return true;
1382  }
1383 
1384  // If the symbol is a thumb function the final relocation must set the lowest
1385  // bit. With a symbol that is done by just having the symbol have that bit
1386  // set, so we would lose the bit if we relocated with the section.
1387  // FIXME: We could use the section but add the bit to the relocation value.
1388  if (Asm.isThumbFunc(Sym))
1389  return true;
1390 
1391  if (TargetObjectWriter->needsRelocateWithSymbol(*Sym, Type))
1392  return true;
1393  return false;
1394 }
1395 
1396 void ELFObjectWriter::recordRelocation(MCAssembler &Asm,
1397  const MCAsmLayout &Layout,
1398  const MCFragment *Fragment,
1399  const MCFixup &Fixup, MCValue Target,
1400  uint64_t &FixedValue) {
1401  MCAsmBackend &Backend = Asm.getBackend();
1402  bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
1403  MCFixupKindInfo::FKF_IsPCRel;
1404  const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent());
1405  uint64_t C = Target.getConstant();
1406  uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1407  MCContext &Ctx = Asm.getContext();
1408 
1409  if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1410  const auto &SymB = cast<MCSymbolELF>(RefB->getSymbol());
1411  if (SymB.isUndefined()) {
1412  Ctx.reportError(Fixup.getLoc(),
1413  Twine("symbol '") + SymB.getName() +
1414  "' can not be undefined in a subtraction expression");
1415  return;
1416  }
1417 
1418  assert(!SymB.isAbsolute() && "Should have been folded");
1419  const MCSection &SecB = SymB.getSection();
1420  if (&SecB != &FixupSection) {
1421  Ctx.reportError(Fixup.getLoc(),
1422  "Cannot represent a difference across sections");
1423  return;
1424  }
1425 
1426  assert(!IsPCRel && "should have been folded");
1427  IsPCRel = true;
1428  C += FixupOffset - Layout.getSymbolOffset(SymB);
1429  }
1430 
1431  // We either rejected the fixup or folded B into C at this point.
1432  const MCSymbolRefExpr *RefA = Target.getSymA();
1433  const auto *SymA = RefA ? cast<MCSymbolELF>(&RefA->getSymbol()) : nullptr;
1434 
1435  bool ViaWeakRef = false;
1436  if (SymA && SymA->isVariable()) {
1437  const MCExpr *Expr = SymA->getVariableValue();
1438  if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
1439  if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
1440  SymA = cast<MCSymbolELF>(&Inner->getSymbol());
1441  ViaWeakRef = true;
1442  }
1443  }
1444  }
1445 
1446  const MCSectionELF *SecA = (SymA && SymA->isInSection())
1447  ? cast<MCSectionELF>(&SymA->getSection())
1448  : nullptr;
1449  if (!checkRelocation(Ctx, Fixup.getLoc(), &FixupSection, SecA))
1450  return;
1451 
1452  unsigned Type = TargetObjectWriter->getRelocType(Ctx, Target, Fixup, IsPCRel);
1453  const auto *Parent = cast<MCSectionELF>(Fragment->getParent());
1454  // Emiting relocation with sybmol for CG Profile to help with --cg-profile.
1455  bool RelocateWithSymbol =
1456  shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type) ||
1457  (Parent->getType() == ELF::SHT_LLVM_CALL_GRAPH_PROFILE);
1458  uint64_t Addend = 0;
1459 
1460  FixedValue = !RelocateWithSymbol && SymA && !SymA->isUndefined()
1461  ? C + Layout.getSymbolOffset(*SymA)
1462  : C;
1463  if (hasRelocationAddend()) {
1464  Addend = FixedValue;
1465  FixedValue = 0;
1466  }
1467 
1468  if (!RelocateWithSymbol) {
1469  const auto *SectionSymbol =
1470  SecA ? cast<MCSymbolELF>(SecA->getBeginSymbol()) : nullptr;
1471  if (SectionSymbol)
1472  SectionSymbol->setUsedInReloc();
1473  ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend, SymA, C);
1474  Relocations[&FixupSection].push_back(Rec);
1475  return;
1476  }
1477 
1478  const MCSymbolELF *RenamedSymA = SymA;
1479  if (SymA) {
1480  if (const MCSymbolELF *R = Renames.lookup(SymA))
1481  RenamedSymA = R;
1482 
1483  if (ViaWeakRef)
1484  RenamedSymA->setIsWeakrefUsedInReloc();
1485  else
1486  RenamedSymA->setUsedInReloc();
1487  }
1488  ELFRelocationEntry Rec(FixupOffset, RenamedSymA, Type, Addend, SymA, C);
1489  Relocations[&FixupSection].push_back(Rec);
1490 }
1491 
1492 bool ELFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
1493  const MCAssembler &Asm, const MCSymbol &SA, const MCFragment &FB,
1494  bool InSet, bool IsPCRel) const {
1495  const auto &SymA = cast<MCSymbolELF>(SA);
1496  if (IsPCRel) {
1497  assert(!InSet);
1498  if (SymA.getBinding() != ELF::STB_LOCAL ||
1499  SymA.getType() == ELF::STT_GNU_IFUNC)
1500  return false;
1501  }
1502  return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
1503  InSet, IsPCRel);
1504 }
1505 
1506 std::unique_ptr<MCObjectWriter>
1507 llvm::createELFObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
1508  raw_pwrite_stream &OS, bool IsLittleEndian) {
1509  return std::make_unique<ELFSingleObjectWriter>(std::move(MOTW), OS,
1510  IsLittleEndian);
1511 }
1512 
1513 std::unique_ptr<MCObjectWriter>
1514 llvm::createELFDwoObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
1516  bool IsLittleEndian) {
1517  return std::make_unique<ELFDwoObjectWriter>(std::move(MOTW), OS, DwoOS,
1518  IsLittleEndian);
1519 }
llvm::Check::Size
@ Size
Definition: FileCheck.h:77
llvm::MCSymbolRefExpr::getKind
VariantKind getKind() const
Definition: MCExpr.h:401
i
i
Definition: README.txt:29
llvm::ELF::STT_TLS
@ STT_TLS
Definition: ELF.h:1235
llvm::alignTo
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:156
llvm::logicalview::LVAttributeKind::Local
@ Local
Compression.h
llvm::ELF::SHT_GROUP
@ SHT_GROUP
Definition: ELF.h:994
MathExtras.h
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
llvm::ELF::STB_GLOBAL
@ STB_GLOBAL
Definition: ELF.h:1218
llvm::MCSymbol
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
llvm::createELFObjectWriter
std::unique_ptr< MCObjectWriter > createELFObjectWriter(std::unique_ptr< MCELFObjectTargetWriter > MOTW, raw_pwrite_stream &OS, bool IsLittleEndian)
Construct a new ELF writer instance.
Definition: ELFObjectWriter.cpp:1507
llvm::MCAsmBackend::getFixupKindInfo
virtual const MCFixupKindInfo & getFixupKindInfo(MCFixupKind Kind) const
Get information on a fixup kind.
Definition: MCAsmBackend.cpp:81
llvm::compression::Params
Definition: Compression.h:93
MCTargetOptions.h
llvm::cl::Prefix
@ Prefix
Definition: CommandLine.h:161
T
llvm::MCContext
Context object for machine code objects.
Definition: MCContext.h:76
StringRef.h
is64Bit
static bool is64Bit(const char *name)
Definition: X86Disassembler.cpp:1018
llvm::write
Error write(MCStreamer &Out, ArrayRef< std::string > Inputs)
Definition: DWP.cpp:549
name
static const char * name
Definition: SMEABIPass.cpp:49
llvm::Target
Target - Wrapper for Target specific information.
Definition: TargetRegistry.h:149
MCSectionELF.h
Host.h
offsetof
#define offsetof(TYPE, MEMBER)
Definition: AMDHSAKernelDescriptor.h:23
llvm::MCSection::getBeginSymbol
MCSymbol * getBeginSymbol()
Definition: MCSection.h:129
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1199
llvm::RISCVFenceField::W
@ W
Definition: RISCVBaseInfo.h:266
llvm::ELF::EI_PAD
@ EI_PAD
Definition: ELF.h:57
llvm::enumerate
detail::enumerator< R > enumerate(R &&TheRange)
Given an input range, returns a new range whose values are are pair (A,B) such that A is the 0-based ...
Definition: STLExtras.h:2263
llvm::MCSymbolELF::getSize
const MCExpr * getSize() const
Definition: MCSymbolELF.h:24
ErrorHandling.h
MCFragment.h
llvm::MCSymbol::isUndefined
bool isUndefined(bool SetUsed=true) const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).
Definition: MCSymbol.h:252
llvm::MCSectionELF::getGroup
const MCSymbolELF * getGroup() const
Definition: MCSectionELF.h:76
Error.h
MCAssembler.h
llvm::ELF::SHT_NOBITS
@ SHT_NOBITS
Definition: ELF.h:987
llvm::ELF::STT_NOTYPE
@ STT_NOTYPE
Definition: ELF.h:1229
llvm::Type
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
DenseMap.h
llvm::ELF::SHT_SYMTAB
@ SHT_SYMTAB
Definition: ELF.h:981
llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Used
@ Used
Groups
static const X86InstrFMA3Group Groups[]
Definition: X86InstrFMA3Info.cpp:73
llvm::ELF::SHF_MERGE
@ SHF_MERGE
Definition: ELF.h:1070
llvm::MCFragment::getParent
MCSection * getParent() const
Definition: MCFragment.h:95
MCFixupKindInfo.h
llvm::StringRef::substr
StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:564
Offset
uint64_t Offset
Definition: ELFObjHandler.cpp:80
llvm::ELF::SHF_TLS
@ SHF_TLS
Definition: ELF.h:1089
llvm::ELFRelocationEntry
Definition: MCELFObjectWriter.h:30
llvm::ELF::SHT_STRTAB
@ SHT_STRTAB
Definition: ELF.h:982
mergeTypeForSet
static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType)
Definition: ELFObjectWriter.cpp:467
llvm::codeview::Link
@ Link
Definition: CodeView.h:151
STLExtras.h
llvm::MCSectionELF
This represents a section on linux, lots of unix variants and some bare metal systems.
Definition: MCSectionELF.h:26
llvm::ELF::SHF_INFO_LINK
@ SHF_INFO_LINK
Definition: ELF.h:1076
llvm::ELF::SHF_COMPRESSED
@ SHF_COMPRESSED
Definition: ELF.h:1092
llvm::support::endian::Writer
Adapter to write values to a stream in a particular byte order.
Definition: EndianStream.h:52
llvm::ELF::Elf64_Rela
Definition: ELF.h:1317
llvm::ELF::SHN_LORESERVE
@ SHN_LORESERVE
Definition: ELF.h:966
llvm::ArrayRef::empty
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:159
F
#define F(x, y, z)
Definition: MD5.cpp:55
llvm::RISCVFenceField::R
@ R
Definition: RISCVBaseInfo.h:265
llvm::ELF::STT_FUNC
@ STT_FUNC
Definition: ELF.h:1231
llvm::MCAssembler::isThumbFunc
bool isThumbFunc(const MCSymbol *Func) const
Check whether a given symbol has been flagged with .thumb_func.
Definition: MCAssembler.cpp:135
llvm::MCSymbolELF
Definition: MCSymbolELF.h:14
llvm::ELF::ELFCOMPRESS_ZLIB
@ ELFCOMPRESS_ZLIB
Definition: ELF.h:1807
llvm::ARMBuildAttrs::Section
@ Section
Legacy Tags.
Definition: ARMBuildAttributes.h:82
llvm::MCFragment
Definition: MCFragment.h:30
StringTableBuilder.h
llvm::ELF::ELFOSABI_NONE
@ ELFOSABI_NONE
Definition: ELF.h:341
llvm::ELF::Elf32_Rel
Definition: ELF.h:1265
llvm::MCAsmBackend
Generic interface to target specific assembler backends.
Definition: MCAsmBackend.h:42
ELF.h
llvm::MCSymbol::getSection
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
Definition: MCSymbol.h:262
MCAsmBackend.h
llvm::MutableArrayRef
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:28
llvm::SMLoc
Represents a location in source code.
Definition: SMLoc.h:23
llvm::StringRef::startswith
bool startswith(StringRef Prefix) const
Definition: StringRef.h:260
llvm::ModRefInfo::Ref
@ Ref
The access may reference the value stored in memory.
llvm::ELF::Elf32_Rela::setSymbolAndType
void setSymbolAndType(Elf32_Word s, unsigned char t)
Definition: ELF.h:1292
llvm::ELF::STB_GNU_UNIQUE
@ STB_GNU_UNIQUE
Definition: ELF.h:1220
llvm::support::little
@ little
Definition: Endian.h:27
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
Twine.h
MCSymbolELF.h
MCContext.h
llvm::ELF::ELFCOMPRESS_ZSTD
@ ELFCOMPRESS_ZSTD
Definition: ELF.h:1808
MCSymbol.h
llvm::MCContext::getELFSection
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition: MCContext.h:564
llvm::MCSymbol::getVariableValue
const MCExpr * getVariableValue(bool SetUsed=true) const
getVariableValue - Get the value for variable symbols.
Definition: MCSymbol.h:298
llvm::dwarf::Index
Index
Definition: Dwarf.h:472
llvm::MaybeAlign
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:117
llvm::dwarf::toStringRef
StringRef toStringRef(const Optional< DWARFFormValue > &V, StringRef Default={})
Take an optional DWARFFormValue and try to extract a string value from it.
Definition: DWARFFormValue.h:193
llvm::MCSection::getAlign
Align getAlign() const
Definition: MCSection.h:140
SMLoc.h
llvm::report_fatal_error
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:145
llvm::AMDGPU::ElfNote::SectionName
const char SectionName[]
Definition: AMDGPUPTNote.h:24
llvm::MCSymbolRefExpr::getSymbol
const MCSymbol & getSymbol() const
Definition: MCExpr.h:399
llvm::MCExpr::evaluateKnownAbsolute
bool evaluateKnownAbsolute(int64_t &Res, const MCAsmLayout &Layout) const
Definition: MCExpr.cpp:561
Info
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
isIFunc
static bool isIFunc(const MCSymbolELF *Symbol)
Definition: ELFObjectWriter.cpp:502
llvm::MCSymbol::getName
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:198
llvm::ELF::SHF_EXCLUDE
@ SHF_EXCLUDE
Definition: ELF.h:1098
Align
uint64_t Align
Definition: ELFObjHandler.cpp:82
llvm::Align
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
llvm::MCSectionELF::isComdat
bool isComdat() const
Definition: MCSectionELF.h:77
llvm::MCFixupKindInfo::Flags
unsigned Flags
Flags describing additional information on this fixup kind.
Definition: MCFixupKindInfo.h:45
llvm::lltok::Kind
Kind
Definition: LLToken.h:18
llvm::MCSymbol::getIndex
uint32_t getIndex() const
Get the (implementation defined) index.
Definition: MCSymbol.h:309
llvm::ELF::SHF_LINK_ORDER
@ SHF_LINK_ORDER
Definition: ELF.h:1079
llvm::ELF::STT_GNU_IFUNC
@ STT_GNU_IFUNC
Definition: ELF.h:1236
llvm::ELF::STT_SECTION
@ STT_SECTION
Definition: ELF.h:1232
llvm::MCAssembler
Definition: MCAssembler.h:73
llvm::MCSectionELF::getLinkedToSection
const MCSection * getLinkedToSection() const
Definition: MCSectionELF.h:89
llvm::AMDGPU::Hwreg::Offset
Offset
Definition: SIDefines.h:416
llvm::MCSymbolRefExpr::VariantKind
VariantKind
Definition: MCExpr.h:194
llvm::DenseMapBase< DenseMap< KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >, KeyT, ValueT, DenseMapInfo< KeyT >, llvm::detail::DenseMapPair< KeyT, ValueT > >::clear
void clear()
Definition: DenseMap.h:110
Index
uint32_t Index
Definition: ELFObjHandler.cpp:83
uint64_t
llvm::raw_pwrite_stream
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:415
llvm::MCAsmLayout::getBaseSymbol
const MCSymbol * getBaseSymbol(const MCSymbol &Symbol) const
If this symbol is equivalent to A + Constant, return A.
Definition: MCFragment.cpp:162
MCELFObjectWriter.h
LEB128.h
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
llvm::numbers::e
constexpr double e
Definition: MathExtras.h:53
llvm::ELF::EM_MIPS
@ EM_MIPS
Definition: ELF.h:141
llvm::DenseMap
Definition: DenseMap.h:714
llvm::ELF::EV_CURRENT
@ EV_CURRENT
Definition: ELF.h:127
iterator.h
size
i< reg-> size
Definition: README.txt:166
ArrayRef.h
llvm::MCSymbol::isVariable
bool isVariable() const
isVariable - Check if this is a variable symbol.
Definition: MCSymbol.h:293
llvm::MCSymbol::setUsedInReloc
void setUsedInReloc() const
Definition: MCSymbol.h:208
llvm::MCContext::createELFGroupSection
MCSectionELF * createELFGroupSection(const MCSymbolELF *Group, bool IsComdat)
Definition: MCContext.cpp:604
llvm::ELF::SHT_LLVM_CALL_GRAPH_PROFILE
@ SHT_LLVM_CALL_GRAPH_PROFILE
Definition: ELF.h:1016
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::MCContext::reportError
void reportError(SMLoc L, const Twine &Msg)
Definition: MCContext.cpp:1055
llvm::MCSymbolELF::setIsWeakrefUsedInReloc
void setIsWeakrefUsedInReloc() const
Definition: MCSymbolELF.cpp:170
Mode
SI Whole Quad Mode
Definition: SIWholeQuadMode.cpp:264
llvm::MCSymbol::isCommon
bool isCommon() const
Is this a 'common' symbol.
Definition: MCSymbol.h:382
llvm::ELF::SHT_LLVM_ADDRSIG
@ SHT_LLVM_ADDRSIG
Definition: ELF.h:1006
llvm::MCSymbolRefExpr
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:192
llvm::irsymtab::storage::Word
support::ulittle32_t Word
Definition: IRSymtab.h:52
info
lazy value info
Definition: LazyValueInfo.cpp:59
MCSection.h
getType
static M68kRelType getType(unsigned Kind, MCSymbolRefExpr::VariantKind &Modifier, bool &IsPCRel)
Definition: M68kELFObjectWriter.cpp:48
llvm::size
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1715
llvm::ELF::Elf64_Rel
Definition: ELF.h:1301
llvm::ArrayRef< uint32_t >
llvm::MCSectionELF::getFlags
unsigned getFlags() const
Definition: MCSectionELF.h:73
llvm::DebugCompressionType
DebugCompressionType
Definition: Compression.h:27
MCAsmInfo.h
Fixup
PowerPC TLS Dynamic Call Fixup
Definition: PPCTLSDynamicCall.cpp:215
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
llvm::ELF::ELFDATA2LSB
@ ELFDATA2LSB
Definition: ELF.h:335
llvm_unreachable
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:143
llvm::ELF::GRP_COMDAT
@ GRP_COMDAT
Definition: ELF.h:1164
llvm::MCAssembler::Symver
Definition: MCAssembler.h:228
llvm::ELF::SHN_XINDEX
@ SHN_XINDEX
Definition: ELF.h:973
llvm::ELF::SYMENTRY_SIZE64
@ SYMENTRY_SIZE64
Definition: ELF.h:1212
uint32_t
MCFixup.h
llvm::MCObjectWriter
Defines the object file and target independent interfaces used by the assembler backend to write nati...
Definition: MCObjectWriter.h:34
llvm::MCSection
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition: MCSection.h:39
S
add sub stmia L5 ldr r0 bl L_printf $stub Instead of a and a wouldn t it be better to do three moves *Return an aggregate type is even return S
Definition: README.txt:210
llvm::MCSymbolELF::getBinding
unsigned getBinding() const
Definition: MCSymbolELF.cpp:63
llvm::ELF::SYMENTRY_SIZE32
@ SYMENTRY_SIZE32
Definition: ELF.h:1211
llvm::MCAsmLayout::getFragmentOffset
uint64_t getFragmentOffset(const MCFragment *F) const
Get the offset of the given fragment inside its containing section.
Definition: MCFragment.cpp:96
llvm::MCSymbol::getCommonAlignment
unsigned getCommonAlignment() const
Return the alignment of a 'common' symbol.
Definition: MCSymbol.h:359
MCAsmLayout.h
llvm::MCSection::getName
StringRef getName() const
Definition: MCSection.h:124
llvm::MCSection::setAlignment
void setAlignment(Align Value)
Definition: MCSection.h:141
MCObjectWriter.h
llvm::AArch64::Alias
StringRef Alias
Definition: AArch64TargetParser.h:139
llvm::Twine
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
Alignment.h
llvm::GraphProgram::Name
Name
Definition: GraphWriter.h:50
EndianStream.h
llvm::MCObjectWriter::reset
virtual void reset()
lifetime management
Definition: MCObjectWriter.h:47
llvm::None
constexpr std::nullopt_t None
Definition: None.h:27
uint16_t
llvm::MCAsmLayout
Encapsulates the layout of an assembly file at a particular point in time.
Definition: MCAsmLayout.h:28
llvm::ELF::Elf64_Rela::setSymbolAndType
void setSymbolAndType(Elf64_Word s, Elf64_Word t)
Definition: ELF.h:1328
llvm::Align::value
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85
llvm::SectionName
Definition: DWARFSection.h:21
llvm::ELF::ELFDATA2MSB
@ ELFDATA2MSB
Definition: ELF.h:336
llvm::StringRef::endswith
bool endswith(StringRef Suffix) const
Definition: StringRef.h:276
llvm::compression::zlib::compress
void compress(ArrayRef< uint8_t > Input, SmallVectorImpl< uint8_t > &CompressedBuffer, int Level=DefaultCompression)
Definition: Compression.cpp:107
Casting.h
isInSymtab
static bool isInSymtab(const MCSymbolWasm &Sym)
Definition: WasmObjectWriter.cpp:1312
llvm::ELF::Elf32_Ehdr
Definition: ELF.h:61
llvm::ELF::Elf32_Shdr
Definition: ELF.h:936
llvm::TargetStackID::Value
Value
Definition: TargetFrameLowering.h:27
llvm::createELFDwoObjectWriter
std::unique_ptr< MCObjectWriter > createELFDwoObjectWriter(std::unique_ptr< MCELFObjectTargetWriter > MOTW, raw_pwrite_stream &OS, raw_pwrite_stream &DwoOS, bool IsLittleEndian)
Definition: ELFObjectWriter.cpp:1514
llvm::MCAsmLayout::getSymbolOffset
bool getSymbolOffset(const MCSymbol &S, uint64_t &Val) const
Get the offset of the given symbol, as computed in the current layout.
Definition: MCFragment.cpp:152
llvm::StringTableBuilder
Utility for building string tables with deduplicated suffixes.
Definition: StringTableBuilder.h:23
MCValue.h
llvm::ELF::ET_REL
@ ET_REL
Definition: ELF.h:116
llvm::ELF::Elf32_Rela
Definition: ELF.h:1281
llvm::MCSymbolELF::getType
unsigned getType() const
Definition: MCSymbolELF.cpp:122
llvm::makeArrayRef
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:475
llvm::ARMBuildAttrs::Symbol
@ Symbol
Definition: ARMBuildAttributes.h:83
llvm::ELF::Elf32_Chdr
Definition: ELF.h:1777
llvm::ELF::ElfMagic
static const char ElfMagic[]
Definition: ELF.h:44
align
mov r0 ldr L5 sub r0 lr needed for prologue ldmia ip add bx lr r2 The last stmia stores r2 into the address passed in there is one additional stmia that stores and r2 to some stack location The store is dead The llvm gcc generated code looks like align
Definition: README.txt:236
llvm::ELF::EI_NIDENT
@ EI_NIDENT
Definition: ELF.h:58
SmallVector.h
llvm::ELF::SHT_RELA
@ SHT_RELA
Definition: ELF.h:983
llvm::StringTableBuilder::ELF
@ ELF
Definition: StringTableBuilder.h:26
llvm::MCSymbol::isInSection
bool isInSection() const
isInSection - Check if this symbol is defined in some section (i.e., it is defined but not absolute).
Definition: MCSymbol.h:247
llvm::ELF::Elf64_Ehdr
Definition: ELF.h:87
llvm::ELF::STB_WEAK
@ STB_WEAK
Definition: ELF.h:1219
llvm::PseudoProbeAttributes::Reserved
@ Reserved
llvm::CallingConv::Tail
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition: CallingConv.h:76
llvm::ELF::SHT_SYMTAB_SHNDX
@ SHT_SYMTAB_SHNDX
Definition: ELF.h:995
llvm::ELF::Elf64_Shdr
Definition: ELF.h:950
llvm::ELF::ELFCLASS64
@ ELFCLASS64
Definition: ELF.h:329
llvm::ELF::STB_LOCAL
@ STB_LOCAL
Definition: ELF.h:1217
llvm::ELF::STV_DEFAULT
@ STV_DEFAULT
Definition: ELF.h:1247
llvm::raw_svector_ostream
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:659
llvm::ELF::SHF_GROUP
@ SHF_GROUP
Definition: ELF.h:1086
llvm::ELF::SHN_ABS
@ SHN_ABS
Definition: ELF.h:971
llvm::encodeULEB128
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition: LEB128.h:80
llvm::Optional::value
constexpr const T & value() const &
Definition: Optional.h:281
llvm::SmallVectorImpl< uint8_t >
llvm::ELF::SHN_UNDEF
@ SHN_UNDEF
Definition: ELF.h:965
llvm::reverse
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:485
llvm::msgpack::Type
Type
MessagePack types as defined in the standard, with the exception of Integer being divided into a sign...
Definition: MsgPackReader.h:48
llvm::HexStyle::Asm
@ Asm
0ffh
Definition: MCInstPrinter.h:34
llvm::StringRef::find
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:294
llvm::ELF::ELFOSABI_GNU
@ ELFOSABI_GNU
Definition: ELF.h:344
llvm::MCAsmLayout::getAssembler
MCAssembler & getAssembler() const
Get the assembler object this is a layout for.
Definition: MCAsmLayout.h:50
llvm::MCValue
This represents an "assembler immediate".
Definition: MCValue.h:36
llvm::omp::RTLDependInfoFields::Flags
@ Flags
llvm::MCContext::createELFRelSection
MCSectionELF * createELFRelSection(const Twine &Name, unsigned Type, unsigned Flags, unsigned EntrySize, const MCSymbolELF *Group, const MCSectionELF *RelInfoSection)
Definition: MCContext.cpp:501
From
BlockVerifier::State From
Definition: BlockVerifier.cpp:55
llvm::ELF::Elf64_Chdr
Definition: ELF.h:1784
llvm::MCAsmLayout::getSectionAddressSize
uint64_t getSectionAddressSize(const MCSection *Sec) const
Get the address space size of the given section, as it effects layout.
Definition: MCFragment.cpp:198
llvm::ELF::SHN_COMMON
@ SHN_COMMON
Definition: ELF.h:972
llvm::ELF::ELFCLASS32
@ ELFCLASS32
Definition: ELF.h:328
raw_ostream.h
llvm::SI::KernelInputOffsets::Offsets
Offsets
Offsets in bytes from the start of the input buffer.
Definition: SIInstrInfo.h:1314
Endian.h
llvm::ELF::STT_FILE
@ STT_FILE
Definition: ELF.h:1233
MCExpr.h
llvm::ELF::STT_OBJECT
@ STT_OBJECT
Definition: ELF.h:1230
llvm::MCFixup
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition: MCFixup.h:71
llvm::ELF::SHT_REL
@ SHT_REL
Definition: ELF.h:988
llvm::ELF::EM_386
@ EM_386
Definition: ELF.h:136
llvm::Value
LLVM Value Representation.
Definition: Value.h:74
llvm::ELF::SHT_DYNAMIC
@ SHT_DYNAMIC
Definition: ELF.h:985
llvm::MCExpr
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
llvm::MCSectionELF::getType
unsigned getType() const
Definition: MCSectionELF.h:72
llvm::support::big
@ big
Definition: Endian.h:27
llvm::sampleprof::Base
@ Base
Definition: Discriminator.h:58
Other
Optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1251
write
static void write(bool isBE, void *P, T V)
Definition: RuntimeDyldELF.cpp:37