Coverage Report

Created: 2019-07-24 05:18

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