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