Coverage Report

Created: 2019-01-18 03:29

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/ELF/SyntheticSections.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- SyntheticSections.cpp ----------------------------------------------===//
2
//
3
//                             The LLVM Linker
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
//
10
// This file contains linker-synthesized sections. Currently,
11
// synthetic sections are created either output sections or input sections,
12
// but we are rewriting code so that all synthetic sections are created as
13
// input sections.
14
//
15
//===----------------------------------------------------------------------===//
16
17
#include "SyntheticSections.h"
18
#include "Bits.h"
19
#include "Config.h"
20
#include "InputFiles.h"
21
#include "LinkerScript.h"
22
#include "OutputSections.h"
23
#include "SymbolTable.h"
24
#include "Symbols.h"
25
#include "Target.h"
26
#include "Writer.h"
27
#include "lld/Common/ErrorHandler.h"
28
#include "lld/Common/Memory.h"
29
#include "lld/Common/Strings.h"
30
#include "lld/Common/Threads.h"
31
#include "lld/Common/Version.h"
32
#include "llvm/ADT/SetOperations.h"
33
#include "llvm/ADT/StringExtras.h"
34
#include "llvm/BinaryFormat/Dwarf.h"
35
#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
36
#include "llvm/Object/ELFObjectFile.h"
37
#include "llvm/Support/Compression.h"
38
#include "llvm/Support/Endian.h"
39
#include "llvm/Support/LEB128.h"
40
#include "llvm/Support/MD5.h"
41
#include "llvm/Support/RandomNumberGenerator.h"
42
#include "llvm/Support/SHA1.h"
43
#include "llvm/Support/xxhash.h"
44
#include <cstdlib>
45
#include <thread>
46
47
using namespace llvm;
48
using namespace llvm::dwarf;
49
using namespace llvm::ELF;
50
using namespace llvm::object;
51
using namespace llvm::support;
52
53
using namespace lld;
54
using namespace lld::elf;
55
56
using llvm::support::endian::read32le;
57
using llvm::support::endian::write32le;
58
using llvm::support::endian::write64le;
59
60
constexpr size_t MergeNoTailSection::NumShards;
61
62
// Returns an LLD version string.
63
2.33k
static ArrayRef<uint8_t> getVersion() {
64
2.33k
  // Check LLD_VERSION first for ease of testing.
65
2.33k
  // You can get consistent output by using the environment variable.
66
2.33k
  // This is only for testing.
67
2.33k
  StringRef S = getenv("LLD_VERSION");
68
2.33k
  if (S.empty())
69
0
    S = Saver.save(Twine("Linker: ") + getLLDVersion());
70
2.33k
71
2.33k
  // +1 to include the terminating '\0'.
72
2.33k
  return {(const uint8_t *)S.data(), S.size() + 1};
73
2.33k
}
74
75
// Creates a .comment section containing LLD version info.
76
// With this feature, you can identify LLD-generated binaries easily
77
// by "readelf --string-dump .comment <file>".
78
// The returned object is a mergeable string section.
79
2.33k
MergeInputSection *elf::createCommentSection() {
80
2.33k
  return make<MergeInputSection>(SHF_MERGE | SHF_STRINGS, SHT_PROGBITS, 1,
81
2.33k
                                 getVersion(), ".comment");
82
2.33k
}
83
84
// .MIPS.abiflags section.
85
template <class ELFT>
86
MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags)
87
    : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
88
186
      Flags(Flags) {
89
186
  this->Entsize = sizeof(Elf_Mips_ABIFlags);
90
186
}
lld::elf::MipsAbiFlagsSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::MipsAbiFlagsSection(llvm::object::Elf_Mips_ABIFlags<llvm::object::ELFType<(llvm::support::endianness)1, false> >)
Line
Count
Source
88
22
      Flags(Flags) {
89
22
  this->Entsize = sizeof(Elf_Mips_ABIFlags);
90
22
}
lld::elf::MipsAbiFlagsSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::MipsAbiFlagsSection(llvm::object::Elf_Mips_ABIFlags<llvm::object::ELFType<(llvm::support::endianness)0, false> >)
Line
Count
Source
88
118
      Flags(Flags) {
89
118
  this->Entsize = sizeof(Elf_Mips_ABIFlags);
90
118
}
lld::elf::MipsAbiFlagsSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::MipsAbiFlagsSection(llvm::object::Elf_Mips_ABIFlags<llvm::object::ELFType<(llvm::support::endianness)1, true> >)
Line
Count
Source
88
3
      Flags(Flags) {
89
3
  this->Entsize = sizeof(Elf_Mips_ABIFlags);
90
3
}
lld::elf::MipsAbiFlagsSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::MipsAbiFlagsSection(llvm::object::Elf_Mips_ABIFlags<llvm::object::ELFType<(llvm::support::endianness)0, true> >)
Line
Count
Source
88
43
      Flags(Flags) {
89
43
  this->Entsize = sizeof(Elf_Mips_ABIFlags);
90
43
}
91
92
180
template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
93
180
  memcpy(Buf, &Flags, sizeof(Flags));
94
180
}
lld::elf::MipsAbiFlagsSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::writeTo(unsigned char*)
Line
Count
Source
92
22
template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
93
22
  memcpy(Buf, &Flags, sizeof(Flags));
94
22
}
lld::elf::MipsAbiFlagsSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::writeTo(unsigned char*)
Line
Count
Source
92
117
template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
93
117
  memcpy(Buf, &Flags, sizeof(Flags));
94
117
}
lld::elf::MipsAbiFlagsSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::writeTo(unsigned char*)
Line
Count
Source
92
3
template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
93
3
  memcpy(Buf, &Flags, sizeof(Flags));
94
3
}
lld::elf::MipsAbiFlagsSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::writeTo(unsigned char*)
Line
Count
Source
92
38
template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
93
38
  memcpy(Buf, &Flags, sizeof(Flags));
94
38
}
95
96
template <class ELFT>
97
192
MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
98
192
  Elf_Mips_ABIFlags Flags = {};
99
192
  bool Create = false;
100
192
101
1.85k
  for (InputSectionBase *Sec : InputSections) {
102
1.85k
    if (Sec->Type != SHT_MIPS_ABIFLAGS)
103
1.60k
      continue;
104
241
    Sec->Live = false;
105
241
    Create = true;
106
241
107
241
    std::string Filename = toString(Sec->File);
108
241
    const size_t Size = Sec->data().size();
109
241
    // Older version of BFD (such as the default FreeBSD linker) concatenate
110
241
    // .MIPS.abiflags instead of merging. To allow for this case (or potential
111
241
    // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
112
241
    if (Size < sizeof(Elf_Mips_ABIFlags)) {
113
0
      error(Filename + ": invalid size of .MIPS.abiflags section: got " +
114
0
            Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
115
0
      return nullptr;
116
0
    }
117
241
    auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->data().data());
118
241
    if (S->version != 0) {
119
0
      error(Filename + ": unexpected .MIPS.abiflags version " +
120
0
            Twine(S->version));
121
0
      return nullptr;
122
0
    }
123
241
124
241
    // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
125
241
    // select the highest number of ISA/Rev/Ext.
126
241
    Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
127
241
    Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
128
241
    Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
129
241
    Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
130
241
    Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
131
241
    Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
132
241
    Flags.ases |= S->ases;
133
241
    Flags.flags1 |= S->flags1;
134
241
    Flags.flags2 |= S->flags2;
135
241
    Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
136
241
  };
137
192
138
192
  if (Create)
139
186
    return make<MipsAbiFlagsSection<ELFT>>(Flags);
140
6
  return nullptr;
141
6
}
lld::elf::MipsAbiFlagsSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::create()
Line
Count
Source
97
23
MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
98
23
  Elf_Mips_ABIFlags Flags = {};
99
23
  bool Create = false;
100
23
101
208
  for (InputSectionBase *Sec : InputSections) {
102
208
    if (Sec->Type != SHT_MIPS_ABIFLAGS)
103
181
      continue;
104
27
    Sec->Live = false;
105
27
    Create = true;
106
27
107
27
    std::string Filename = toString(Sec->File);
108
27
    const size_t Size = Sec->data().size();
109
27
    // Older version of BFD (such as the default FreeBSD linker) concatenate
110
27
    // .MIPS.abiflags instead of merging. To allow for this case (or potential
111
27
    // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
112
27
    if (Size < sizeof(Elf_Mips_ABIFlags)) {
113
0
      error(Filename + ": invalid size of .MIPS.abiflags section: got " +
114
0
            Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
115
0
      return nullptr;
116
0
    }
117
27
    auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->data().data());
118
27
    if (S->version != 0) {
119
0
      error(Filename + ": unexpected .MIPS.abiflags version " +
120
0
            Twine(S->version));
121
0
      return nullptr;
122
0
    }
123
27
124
27
    // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
125
27
    // select the highest number of ISA/Rev/Ext.
126
27
    Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
127
27
    Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
128
27
    Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
129
27
    Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
130
27
    Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
131
27
    Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
132
27
    Flags.ases |= S->ases;
133
27
    Flags.flags1 |= S->flags1;
134
27
    Flags.flags2 |= S->flags2;
135
27
    Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
136
27
  };
137
23
138
23
  if (Create)
139
22
    return make<MipsAbiFlagsSection<ELFT>>(Flags);
140
1
  return nullptr;
141
1
}
lld::elf::MipsAbiFlagsSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::create()
Line
Count
Source
97
121
MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
98
121
  Elf_Mips_ABIFlags Flags = {};
99
121
  bool Create = false;
100
121
101
1.20k
  for (InputSectionBase *Sec : InputSections) {
102
1.20k
    if (Sec->Type != SHT_MIPS_ABIFLAGS)
103
1.05k
      continue;
104
156
    Sec->Live = false;
105
156
    Create = true;
106
156
107
156
    std::string Filename = toString(Sec->File);
108
156
    const size_t Size = Sec->data().size();
109
156
    // Older version of BFD (such as the default FreeBSD linker) concatenate
110
156
    // .MIPS.abiflags instead of merging. To allow for this case (or potential
111
156
    // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
112
156
    if (Size < sizeof(Elf_Mips_ABIFlags)) {
113
0
      error(Filename + ": invalid size of .MIPS.abiflags section: got " +
114
0
            Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
115
0
      return nullptr;
116
0
    }
117
156
    auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->data().data());
118
156
    if (S->version != 0) {
119
0
      error(Filename + ": unexpected .MIPS.abiflags version " +
120
0
            Twine(S->version));
121
0
      return nullptr;
122
0
    }
123
156
124
156
    // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
125
156
    // select the highest number of ISA/Rev/Ext.
126
156
    Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
127
156
    Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
128
156
    Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
129
156
    Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
130
156
    Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
131
156
    Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
132
156
    Flags.ases |= S->ases;
133
156
    Flags.flags1 |= S->flags1;
134
156
    Flags.flags2 |= S->flags2;
135
156
    Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
136
156
  };
137
121
138
121
  if (Create)
139
118
    return make<MipsAbiFlagsSection<ELFT>>(Flags);
140
3
  return nullptr;
141
3
}
lld::elf::MipsAbiFlagsSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::create()
Line
Count
Source
97
3
MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
98
3
  Elf_Mips_ABIFlags Flags = {};
99
3
  bool Create = false;
100
3
101
24
  for (InputSectionBase *Sec : InputSections) {
102
24
    if (Sec->Type != SHT_MIPS_ABIFLAGS)
103
21
      continue;
104
3
    Sec->Live = false;
105
3
    Create = true;
106
3
107
3
    std::string Filename = toString(Sec->File);
108
3
    const size_t Size = Sec->data().size();
109
3
    // Older version of BFD (such as the default FreeBSD linker) concatenate
110
3
    // .MIPS.abiflags instead of merging. To allow for this case (or potential
111
3
    // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
112
3
    if (Size < sizeof(Elf_Mips_ABIFlags)) {
113
0
      error(Filename + ": invalid size of .MIPS.abiflags section: got " +
114
0
            Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
115
0
      return nullptr;
116
0
    }
117
3
    auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->data().data());
118
3
    if (S->version != 0) {
119
0
      error(Filename + ": unexpected .MIPS.abiflags version " +
120
0
            Twine(S->version));
121
0
      return nullptr;
122
0
    }
123
3
124
3
    // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
125
3
    // select the highest number of ISA/Rev/Ext.
126
3
    Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
127
3
    Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
128
3
    Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
129
3
    Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
130
3
    Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
131
3
    Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
132
3
    Flags.ases |= S->ases;
133
3
    Flags.flags1 |= S->flags1;
134
3
    Flags.flags2 |= S->flags2;
135
3
    Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
136
3
  };
137
3
138
3
  if (Create)
139
3
    return make<MipsAbiFlagsSection<ELFT>>(Flags);
140
0
  return nullptr;
141
0
}
lld::elf::MipsAbiFlagsSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::create()
Line
Count
Source
97
45
MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
98
45
  Elf_Mips_ABIFlags Flags = {};
99
45
  bool Create = false;
100
45
101
409
  for (InputSectionBase *Sec : InputSections) {
102
409
    if (Sec->Type != SHT_MIPS_ABIFLAGS)
103
354
      continue;
104
55
    Sec->Live = false;
105
55
    Create = true;
106
55
107
55
    std::string Filename = toString(Sec->File);
108
55
    const size_t Size = Sec->data().size();
109
55
    // Older version of BFD (such as the default FreeBSD linker) concatenate
110
55
    // .MIPS.abiflags instead of merging. To allow for this case (or potential
111
55
    // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
112
55
    if (Size < sizeof(Elf_Mips_ABIFlags)) {
113
0
      error(Filename + ": invalid size of .MIPS.abiflags section: got " +
114
0
            Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
115
0
      return nullptr;
116
0
    }
117
55
    auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->data().data());
118
55
    if (S->version != 0) {
119
0
      error(Filename + ": unexpected .MIPS.abiflags version " +
120
0
            Twine(S->version));
121
0
      return nullptr;
122
0
    }
123
55
124
55
    // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
125
55
    // select the highest number of ISA/Rev/Ext.
126
55
    Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
127
55
    Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
128
55
    Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
129
55
    Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
130
55
    Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
131
55
    Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
132
55
    Flags.ases |= S->ases;
133
55
    Flags.flags1 |= S->flags1;
134
55
    Flags.flags2 |= S->flags2;
135
55
    Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
136
55
  };
137
45
138
45
  if (Create)
139
43
    return make<MipsAbiFlagsSection<ELFT>>(Flags);
140
2
  return nullptr;
141
2
}
142
143
// .MIPS.options section.
144
template <class ELFT>
145
MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
146
    : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
147
42
      Reginfo(Reginfo) {
148
42
  this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
149
42
}
Unexecuted instantiation: lld::elf::MipsOptionsSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::MipsOptionsSection(llvm::object::Elf_Mips_RegInfo<llvm::object::ELFType<(llvm::support::endianness)1, false> >)
Unexecuted instantiation: lld::elf::MipsOptionsSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::MipsOptionsSection(llvm::object::Elf_Mips_RegInfo<llvm::object::ELFType<(llvm::support::endianness)0, false> >)
lld::elf::MipsOptionsSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::MipsOptionsSection(llvm::object::Elf_Mips_RegInfo<llvm::object::ELFType<(llvm::support::endianness)1, true> >)
Line
Count
Source
147
3
      Reginfo(Reginfo) {
148
3
  this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
149
3
}
lld::elf::MipsOptionsSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::MipsOptionsSection(llvm::object::Elf_Mips_RegInfo<llvm::object::ELFType<(llvm::support::endianness)0, true> >)
Line
Count
Source
147
39
      Reginfo(Reginfo) {
148
39
  this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
149
39
}
150
151
41
template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
152
41
  auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
153
41
  Options->kind = ODK_REGINFO;
154
41
  Options->size = getSize();
155
41
156
41
  if (!Config->Relocatable)
157
39
    Reginfo.ri_gp_value = In.MipsGot->getGp();
158
41
  memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
159
41
}
Unexecuted instantiation: lld::elf::MipsOptionsSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::writeTo(unsigned char*)
Unexecuted instantiation: lld::elf::MipsOptionsSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::writeTo(unsigned char*)
lld::elf::MipsOptionsSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::writeTo(unsigned char*)
Line
Count
Source
151
3
template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
152
3
  auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
153
3
  Options->kind = ODK_REGINFO;
154
3
  Options->size = getSize();
155
3
156
3
  if (!Config->Relocatable)
157
3
    Reginfo.ri_gp_value = In.MipsGot->getGp();
158
3
  memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
159
3
}
lld::elf::MipsOptionsSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::writeTo(unsigned char*)
Line
Count
Source
151
38
template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
152
38
  auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
153
38
  Options->kind = ODK_REGINFO;
154
38
  Options->size = getSize();
155
38
156
38
  if (!Config->Relocatable)
157
36
    Reginfo.ri_gp_value = In.MipsGot->getGp();
158
38
  memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
159
38
}
160
161
template <class ELFT>
162
192
MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
163
192
  // N64 ABI only.
164
192
  if (!ELFT::Is64Bits)
165
144
    return nullptr;
166
48
167
48
  std::vector<InputSectionBase *> Sections;
168
48
  for (InputSectionBase *Sec : InputSections)
169
479
    if (Sec->Type == SHT_MIPS_OPTIONS)
170
50
      Sections.push_back(Sec);
171
48
172
48
  if (Sections.empty())
173
6
    return nullptr;
174
42
175
42
  Elf_Mips_RegInfo Reginfo = {};
176
50
  for (InputSectionBase *Sec : Sections) {
177
50
    Sec->Live = false;
178
50
179
50
    std::string Filename = toString(Sec->File);
180
50
    ArrayRef<uint8_t> D = Sec->data();
181
50
182
50
    while (!D.empty()) {
183
50
      if (D.size() < sizeof(Elf_Mips_Options)) {
184
0
        error(Filename + ": invalid size of .MIPS.options section");
185
0
        break;
186
0
      }
187
50
188
50
      auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
189
50
      if (Opt->kind == ODK_REGINFO) {
190
50
        Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
191
50
        Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
192
50
        break;
193
50
      }
194
0
195
0
      if (!Opt->size)
196
0
        fatal(Filename + ": zero option descriptor size");
197
0
      D = D.slice(Opt->size);
198
0
    }
199
50
  };
200
42
201
42
  return make<MipsOptionsSection<ELFT>>(Reginfo);
202
42
}
lld::elf::MipsOptionsSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::create()
Line
Count
Source
162
23
MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
163
23
  // N64 ABI only.
164
23
  if (!ELFT::Is64Bits)
165
23
    return nullptr;
166
0
167
0
  std::vector<InputSectionBase *> Sections;
168
0
  for (InputSectionBase *Sec : InputSections)
169
0
    if (Sec->Type == SHT_MIPS_OPTIONS)
170
0
      Sections.push_back(Sec);
171
0
172
0
  if (Sections.empty())
173
0
    return nullptr;
174
0
175
0
  Elf_Mips_RegInfo Reginfo = {};
176
0
  for (InputSectionBase *Sec : Sections) {
177
0
    Sec->Live = false;
178
0
179
0
    std::string Filename = toString(Sec->File);
180
0
    ArrayRef<uint8_t> D = Sec->data();
181
0
182
0
    while (!D.empty()) {
183
0
      if (D.size() < sizeof(Elf_Mips_Options)) {
184
0
        error(Filename + ": invalid size of .MIPS.options section");
185
0
        break;
186
0
      }
187
0
188
0
      auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
189
0
      if (Opt->kind == ODK_REGINFO) {
190
0
        Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
191
0
        Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
192
0
        break;
193
0
      }
194
0
195
0
      if (!Opt->size)
196
0
        fatal(Filename + ": zero option descriptor size");
197
0
      D = D.slice(Opt->size);
198
0
    }
199
0
  };
200
0
201
0
  return make<MipsOptionsSection<ELFT>>(Reginfo);
202
0
}
lld::elf::MipsOptionsSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::create()
Line
Count
Source
162
121
MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
163
121
  // N64 ABI only.
164
121
  if (!ELFT::Is64Bits)
165
121
    return nullptr;
166
0
167
0
  std::vector<InputSectionBase *> Sections;
168
0
  for (InputSectionBase *Sec : InputSections)
169
0
    if (Sec->Type == SHT_MIPS_OPTIONS)
170
0
      Sections.push_back(Sec);
171
0
172
0
  if (Sections.empty())
173
0
    return nullptr;
174
0
175
0
  Elf_Mips_RegInfo Reginfo = {};
176
0
  for (InputSectionBase *Sec : Sections) {
177
0
    Sec->Live = false;
178
0
179
0
    std::string Filename = toString(Sec->File);
180
0
    ArrayRef<uint8_t> D = Sec->data();
181
0
182
0
    while (!D.empty()) {
183
0
      if (D.size() < sizeof(Elf_Mips_Options)) {
184
0
        error(Filename + ": invalid size of .MIPS.options section");
185
0
        break;
186
0
      }
187
0
188
0
      auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
189
0
      if (Opt->kind == ODK_REGINFO) {
190
0
        Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
191
0
        Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
192
0
        break;
193
0
      }
194
0
195
0
      if (!Opt->size)
196
0
        fatal(Filename + ": zero option descriptor size");
197
0
      D = D.slice(Opt->size);
198
0
    }
199
0
  };
200
0
201
0
  return make<MipsOptionsSection<ELFT>>(Reginfo);
202
0
}
lld::elf::MipsOptionsSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::create()
Line
Count
Source
162
3
MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
163
3
  // N64 ABI only.
164
3
  if (!ELFT::Is64Bits)
165
0
    return nullptr;
166
3
167
3
  std::vector<InputSectionBase *> Sections;
168
3
  for (InputSectionBase *Sec : InputSections)
169
27
    if (Sec->Type == SHT_MIPS_OPTIONS)
170
3
      Sections.push_back(Sec);
171
3
172
3
  if (Sections.empty())
173
0
    return nullptr;
174
3
175
3
  Elf_Mips_RegInfo Reginfo = {};
176
3
  for (InputSectionBase *Sec : Sections) {
177
3
    Sec->Live = false;
178
3
179
3
    std::string Filename = toString(Sec->File);
180
3
    ArrayRef<uint8_t> D = Sec->data();
181
3
182
3
    while (!D.empty()) {
183
3
      if (D.size() < sizeof(Elf_Mips_Options)) {
184
0
        error(Filename + ": invalid size of .MIPS.options section");
185
0
        break;
186
0
      }
187
3
188
3
      auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
189
3
      if (Opt->kind == ODK_REGINFO) {
190
3
        Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
191
3
        Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
192
3
        break;
193
3
      }
194
0
195
0
      if (!Opt->size)
196
0
        fatal(Filename + ": zero option descriptor size");
197
0
      D = D.slice(Opt->size);
198
0
    }
199
3
  };
200
3
201
3
  return make<MipsOptionsSection<ELFT>>(Reginfo);
202
3
}
lld::elf::MipsOptionsSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::create()
Line
Count
Source
162
45
MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
163
45
  // N64 ABI only.
164
45
  if (!ELFT::Is64Bits)
165
0
    return nullptr;
166
45
167
45
  std::vector<InputSectionBase *> Sections;
168
45
  for (InputSectionBase *Sec : InputSections)
169
452
    if (Sec->Type == SHT_MIPS_OPTIONS)
170
47
      Sections.push_back(Sec);
171
45
172
45
  if (Sections.empty())
173
6
    return nullptr;
174
39
175
39
  Elf_Mips_RegInfo Reginfo = {};
176
47
  for (InputSectionBase *Sec : Sections) {
177
47
    Sec->Live = false;
178
47
179
47
    std::string Filename = toString(Sec->File);
180
47
    ArrayRef<uint8_t> D = Sec->data();
181
47
182
47
    while (!D.empty()) {
183
47
      if (D.size() < sizeof(Elf_Mips_Options)) {
184
0
        error(Filename + ": invalid size of .MIPS.options section");
185
0
        break;
186
0
      }
187
47
188
47
      auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
189
47
      if (Opt->kind == ODK_REGINFO) {
190
47
        Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
191
47
        Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
192
47
        break;
193
47
      }
194
0
195
0
      if (!Opt->size)
196
0
        fatal(Filename + ": zero option descriptor size");
197
0
      D = D.slice(Opt->size);
198
0
    }
199
47
  };
200
39
201
39
  return make<MipsOptionsSection<ELFT>>(Reginfo);
202
39
}
203
204
// MIPS .reginfo section.
205
template <class ELFT>
206
MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
207
    : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
208
140
      Reginfo(Reginfo) {
209
140
  this->Entsize = sizeof(Elf_Mips_RegInfo);
210
140
}
lld::elf::MipsReginfoSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::MipsReginfoSection(llvm::object::Elf_Mips_RegInfo<llvm::object::ELFType<(llvm::support::endianness)1, false> >)
Line
Count
Source
208
22
      Reginfo(Reginfo) {
209
22
  this->Entsize = sizeof(Elf_Mips_RegInfo);
210
22
}
lld::elf::MipsReginfoSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::MipsReginfoSection(llvm::object::Elf_Mips_RegInfo<llvm::object::ELFType<(llvm::support::endianness)0, false> >)
Line
Count
Source
208
118
      Reginfo(Reginfo) {
209
118
  this->Entsize = sizeof(Elf_Mips_RegInfo);
210
118
}
Unexecuted instantiation: lld::elf::MipsReginfoSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::MipsReginfoSection(llvm::object::Elf_Mips_RegInfo<llvm::object::ELFType<(llvm::support::endianness)1, true> >)
Unexecuted instantiation: lld::elf::MipsReginfoSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::MipsReginfoSection(llvm::object::Elf_Mips_RegInfo<llvm::object::ELFType<(llvm::support::endianness)0, true> >)
211
212
139
template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
213
139
  if (!Config->Relocatable)
214
128
    Reginfo.ri_gp_value = In.MipsGot->getGp();
215
139
  memcpy(Buf, &Reginfo, sizeof(Reginfo));
216
139
}
lld::elf::MipsReginfoSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::writeTo(unsigned char*)
Line
Count
Source
212
22
template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
213
22
  if (!Config->Relocatable)
214
21
    Reginfo.ri_gp_value = In.MipsGot->getGp();
215
22
  memcpy(Buf, &Reginfo, sizeof(Reginfo));
216
22
}
lld::elf::MipsReginfoSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::writeTo(unsigned char*)
Line
Count
Source
212
117
template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
213
117
  if (!Config->Relocatable)
214
107
    Reginfo.ri_gp_value = In.MipsGot->getGp();
215
117
  memcpy(Buf, &Reginfo, sizeof(Reginfo));
216
117
}
Unexecuted instantiation: lld::elf::MipsReginfoSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::writeTo(unsigned char*)
Unexecuted instantiation: lld::elf::MipsReginfoSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::writeTo(unsigned char*)
217
218
template <class ELFT>
219
192
MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
220
192
  // Section should be alive for O32 and N32 ABIs only.
221
192
  if (ELFT::Is64Bits)
222
48
    return nullptr;
223
144
224
144
  std::vector<InputSectionBase *> Sections;
225
144
  for (InputSectionBase *Sec : InputSections)
226
1.55k
    if (Sec->Type == SHT_MIPS_REGINFO)
227
183
      Sections.push_back(Sec);
228
144
229
144
  if (Sections.empty())
230
4
    return nullptr;
231
140
232
140
  Elf_Mips_RegInfo Reginfo = {};
233
183
  for (InputSectionBase *Sec : Sections) {
234
183
    Sec->Live = false;
235
183
236
183
    if (Sec->data().size() != sizeof(Elf_Mips_RegInfo)) {
237
0
      error(toString(Sec->File) + ": invalid size of .reginfo section");
238
0
      return nullptr;
239
0
    }
240
183
241
183
    auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->data().data());
242
183
    Reginfo.ri_gprmask |= R->ri_gprmask;
243
183
    Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
244
183
  };
245
140
246
140
  return make<MipsReginfoSection<ELFT>>(Reginfo);
247
140
}
lld::elf::MipsReginfoSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::create()
Line
Count
Source
219
23
MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
220
23
  // Section should be alive for O32 and N32 ABIs only.
221
23
  if (ELFT::Is64Bits)
222
0
    return nullptr;
223
23
224
23
  std::vector<InputSectionBase *> Sections;
225
23
  for (InputSectionBase *Sec : InputSections)
226
230
    if (Sec->Type == SHT_MIPS_REGINFO)
227
27
      Sections.push_back(Sec);
228
23
229
23
  if (Sections.empty())
230
1
    return nullptr;
231
22
232
22
  Elf_Mips_RegInfo Reginfo = {};
233
27
  for (InputSectionBase *Sec : Sections) {
234
27
    Sec->Live = false;
235
27
236
27
    if (Sec->data().size() != sizeof(Elf_Mips_RegInfo)) {
237
0
      error(toString(Sec->File) + ": invalid size of .reginfo section");
238
0
      return nullptr;
239
0
    }
240
27
241
27
    auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->data().data());
242
27
    Reginfo.ri_gprmask |= R->ri_gprmask;
243
27
    Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
244
27
  };
245
22
246
22
  return make<MipsReginfoSection<ELFT>>(Reginfo);
247
22
}
lld::elf::MipsReginfoSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::create()
Line
Count
Source
219
121
MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
220
121
  // Section should be alive for O32 and N32 ABIs only.
221
121
  if (ELFT::Is64Bits)
222
0
    return nullptr;
223
121
224
121
  std::vector<InputSectionBase *> Sections;
225
121
  for (InputSectionBase *Sec : InputSections)
226
1.32k
    if (Sec->Type == SHT_MIPS_REGINFO)
227
156
      Sections.push_back(Sec);
228
121
229
121
  if (Sections.empty())
230
3
    return nullptr;
231
118
232
118
  Elf_Mips_RegInfo Reginfo = {};
233
156
  for (InputSectionBase *Sec : Sections) {
234
156
    Sec->Live = false;
235
156
236
156
    if (Sec->data().size() != sizeof(Elf_Mips_RegInfo)) {
237
0
      error(toString(Sec->File) + ": invalid size of .reginfo section");
238
0
      return nullptr;
239
0
    }
240
156
241
156
    auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->data().data());
242
156
    Reginfo.ri_gprmask |= R->ri_gprmask;
243
156
    Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
244
156
  };
245
118
246
118
  return make<MipsReginfoSection<ELFT>>(Reginfo);
247
118
}
lld::elf::MipsReginfoSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::create()
Line
Count
Source
219
3
MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
220
3
  // Section should be alive for O32 and N32 ABIs only.
221
3
  if (ELFT::Is64Bits)
222
3
    return nullptr;
223
0
224
0
  std::vector<InputSectionBase *> Sections;
225
0
  for (InputSectionBase *Sec : InputSections)
226
0
    if (Sec->Type == SHT_MIPS_REGINFO)
227
0
      Sections.push_back(Sec);
228
0
229
0
  if (Sections.empty())
230
0
    return nullptr;
231
0
232
0
  Elf_Mips_RegInfo Reginfo = {};
233
0
  for (InputSectionBase *Sec : Sections) {
234
0
    Sec->Live = false;
235
0
236
0
    if (Sec->data().size() != sizeof(Elf_Mips_RegInfo)) {
237
0
      error(toString(Sec->File) + ": invalid size of .reginfo section");
238
0
      return nullptr;
239
0
    }
240
0
241
0
    auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->data().data());
242
0
    Reginfo.ri_gprmask |= R->ri_gprmask;
243
0
    Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
244
0
  };
245
0
246
0
  return make<MipsReginfoSection<ELFT>>(Reginfo);
247
0
}
lld::elf::MipsReginfoSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::create()
Line
Count
Source
219
45
MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
220
45
  // Section should be alive for O32 and N32 ABIs only.
221
45
  if (ELFT::Is64Bits)
222
45
    return nullptr;
223
0
224
0
  std::vector<InputSectionBase *> Sections;
225
0
  for (InputSectionBase *Sec : InputSections)
226
0
    if (Sec->Type == SHT_MIPS_REGINFO)
227
0
      Sections.push_back(Sec);
228
0
229
0
  if (Sections.empty())
230
0
    return nullptr;
231
0
232
0
  Elf_Mips_RegInfo Reginfo = {};
233
0
  for (InputSectionBase *Sec : Sections) {
234
0
    Sec->Live = false;
235
0
236
0
    if (Sec->data().size() != sizeof(Elf_Mips_RegInfo)) {
237
0
      error(toString(Sec->File) + ": invalid size of .reginfo section");
238
0
      return nullptr;
239
0
    }
240
0
241
0
    auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->data().data());
242
0
    Reginfo.ri_gprmask |= R->ri_gprmask;
243
0
    Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
244
0
  };
245
0
246
0
  return make<MipsReginfoSection<ELFT>>(Reginfo);
247
0
}
248
249
10
InputSection *elf::createInterpSection() {
250
10
  // StringSaver guarantees that the returned string ends with '\0'.
251
10
  StringRef S = Saver.save(Config->DynamicLinker);
252
10
  ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1};
253
10
254
10
  auto *Sec = make<InputSection>(nullptr, SHF_ALLOC, SHT_PROGBITS, 1, Contents,
255
10
                                 ".interp");
256
10
  Sec->Live = true;
257
10
  return Sec;
258
10
}
259
260
Defined *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
261
520
                                uint64_t Size, InputSectionBase &Section) {
262
520
  auto *S = make<Defined>(Section.File, Name, STB_LOCAL, STV_DEFAULT, Type,
263
520
                          Value, Size, &Section);
264
520
  if (In.SymTab)
265
520
    In.SymTab->addSymbol(S);
266
520
  return S;
267
520
}
268
269
17
static size_t getHashSize() {
270
17
  switch (Config->BuildId) {
271
17
  case BuildIdKind::Fast:
272
6
    return 8;
273
17
  case BuildIdKind::Md5:
274
4
  case BuildIdKind::Uuid:
275
4
    return 16;
276
4
  case BuildIdKind::Sha1:
277
4
    return 20;
278
4
  case BuildIdKind::Hexstring:
279
3
    return Config->BuildIdVector.size();
280
4
  default:
281
0
    llvm_unreachable("unknown BuildIdKind");
282
17
  }
283
17
}
284
285
BuildIdSection::BuildIdSection()
286
    : SyntheticSection(SHF_ALLOC, SHT_NOTE, 4, ".note.gnu.build-id"),
287
17
      HashSize(getHashSize()) {}
288
289
17
void BuildIdSection::writeTo(uint8_t *Buf) {
290
17
  write32(Buf, 4);                      // Name size
291
17
  write32(Buf + 4, HashSize);           // Content size
292
17
  write32(Buf + 8, NT_GNU_BUILD_ID);    // Type
293
17
  memcpy(Buf + 12, "GNU", 4);           // Name string
294
17
  HashBuf = Buf + 16;
295
17
}
296
297
// Split one uint8 array into small pieces of uint8 arrays.
298
static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
299
13
                                            size_t ChunkSize) {
300
13
  std::vector<ArrayRef<uint8_t>> Ret;
301
13
  while (Arr.size() > ChunkSize) {
302
0
    Ret.push_back(Arr.take_front(ChunkSize));
303
0
    Arr = Arr.drop_front(ChunkSize);
304
0
  }
305
13
  if (!Arr.empty())
306
13
    Ret.push_back(Arr);
307
13
  return Ret;
308
13
}
309
310
// Computes a hash value of Data using a given hash function.
311
// In order to utilize multiple cores, we first split data into 1MB
312
// chunks, compute a hash for each chunk, and then compute a hash value
313
// of the hash values.
314
void BuildIdSection::computeHash(
315
    llvm::ArrayRef<uint8_t> Data,
316
13
    std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
317
13
  std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
318
13
  std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
319
13
320
13
  // Compute hash values.
321
13
  parallelForEachN(0, Chunks.size(), [&](size_t I) {
322
13
    HashFn(Hashes.data() + I * HashSize, Chunks[I]);
323
13
  });
324
13
325
13
  // Write to the final output buffer.
326
13
  HashFn(HashBuf, Hashes);
327
13
}
328
329
BssSection::BssSection(StringRef Name, uint64_t Size, uint32_t Alignment)
330
4.97k
    : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, Alignment, Name) {
331
4.97k
  this->Bss = true;
332
4.97k
  this->Size = Size;
333
4.97k
}
334
335
17
void BuildIdSection::writeBuildId(ArrayRef<uint8_t> Buf) {
336
17
  switch (Config->BuildId) {
337
17
  case BuildIdKind::Fast:
338
12
    computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
339
12
      write64le(Dest, xxHash64(Arr));
340
12
    });
341
6
    break;
342
17
  case BuildIdKind::Md5:
343
6
    computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
344
6
      memcpy(Dest, MD5::hash(Arr).data(), 16);
345
6
    });
346
3
    break;
347
17
  case BuildIdKind::Sha1:
348
8
    computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
349
8
      memcpy(Dest, SHA1::hash(Arr).data(), 20);
350
8
    });
351
4
    break;
352
17
  case BuildIdKind::Uuid:
353
1
    if (auto EC = getRandomBytes(HashBuf, HashSize))
354
0
      error("entropy source failure: " + EC.message());
355
1
    break;
356
17
  case BuildIdKind::Hexstring:
357
3
    memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
358
3
    break;
359
17
  default:
360
0
    llvm_unreachable("unknown BuildIdKind");
361
17
  }
362
17
}
363
364
EhFrameSection::EhFrameSection()
365
2.33k
    : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
366
367
// Search for an existing CIE record or create a new one.
368
// CIE records from input object files are uniquified by their contents
369
// and where their relocations point to.
370
template <class ELFT, class RelTy>
371
104
CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) {
372
104
  Symbol *Personality = nullptr;
373
104
  unsigned FirstRelI = Cie.FirstRelocation;
374
104
  if (FirstRelI != (unsigned)-1)
375
11
    Personality =
376
11
        &Cie.Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
377
104
378
104
  // Search for an existing CIE by CIE contents/relocation target pair.
379
104
  CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
380
104
381
104
  // If not found, create a new one.
382
104
  if (!Rec) {
383
90
    Rec = make<CieRecord>();
384
90
    Rec->Cie = &Cie;
385
90
    CieRecords.push_back(Rec);
386
90
  }
387
104
  return Rec;
388
104
}
Unexecuted instantiation: lld::elf::CieRecord* lld::elf::EhFrameSection::addCie<llvm::object::ELFType<(llvm::support::endianness)1, false>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, true> >(lld::elf::EhSectionPiece&, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, true> >)
lld::elf::CieRecord* lld::elf::EhFrameSection::addCie<llvm::object::ELFType<(llvm::support::endianness)1, false>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, false> >(lld::elf::EhSectionPiece&, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, false> >)
Line
Count
Source
371
4
CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) {
372
4
  Symbol *Personality = nullptr;
373
4
  unsigned FirstRelI = Cie.FirstRelocation;
374
4
  if (FirstRelI != (unsigned)-1)
375
2
    Personality =
376
2
        &Cie.Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
377
4
378
4
  // Search for an existing CIE by CIE contents/relocation target pair.
379
4
  CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
380
4
381
4
  // If not found, create a new one.
382
4
  if (!Rec) {
383
3
    Rec = make<CieRecord>();
384
3
    Rec->Cie = &Cie;
385
3
    CieRecords.push_back(Rec);
386
3
  }
387
4
  return Rec;
388
4
}
Unexecuted instantiation: lld::elf::CieRecord* lld::elf::EhFrameSection::addCie<llvm::object::ELFType<(llvm::support::endianness)0, false>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, true> >(lld::elf::EhSectionPiece&, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, true> >)
lld::elf::CieRecord* lld::elf::EhFrameSection::addCie<llvm::object::ELFType<(llvm::support::endianness)0, false>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, false> >(lld::elf::EhSectionPiece&, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, false> >)
Line
Count
Source
371
1
CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) {
372
1
  Symbol *Personality = nullptr;
373
1
  unsigned FirstRelI = Cie.FirstRelocation;
374
1
  if (FirstRelI != (unsigned)-1)
375
0
    Personality =
376
0
        &Cie.Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
377
1
378
1
  // Search for an existing CIE by CIE contents/relocation target pair.
379
1
  CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
380
1
381
1
  // If not found, create a new one.
382
1
  if (!Rec) {
383
1
    Rec = make<CieRecord>();
384
1
    Rec->Cie = &Cie;
385
1
    CieRecords.push_back(Rec);
386
1
  }
387
1
  return Rec;
388
1
}
lld::elf::CieRecord* lld::elf::EhFrameSection::addCie<llvm::object::ELFType<(llvm::support::endianness)1, true>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, true> >(lld::elf::EhSectionPiece&, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, true> >)
Line
Count
Source
371
88
CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) {
372
88
  Symbol *Personality = nullptr;
373
88
  unsigned FirstRelI = Cie.FirstRelocation;
374
88
  if (FirstRelI != (unsigned)-1)
375
8
    Personality =
376
8
        &Cie.Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
377
88
378
88
  // Search for an existing CIE by CIE contents/relocation target pair.
379
88
  CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
380
88
381
88
  // If not found, create a new one.
382
88
  if (!Rec) {
383
75
    Rec = make<CieRecord>();
384
75
    Rec->Cie = &Cie;
385
75
    CieRecords.push_back(Rec);
386
75
  }
387
88
  return Rec;
388
88
}
lld::elf::CieRecord* lld::elf::EhFrameSection::addCie<llvm::object::ELFType<(llvm::support::endianness)1, true>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, false> >(lld::elf::EhSectionPiece&, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, false> >)
Line
Count
Source
371
7
CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) {
372
7
  Symbol *Personality = nullptr;
373
7
  unsigned FirstRelI = Cie.FirstRelocation;
374
7
  if (FirstRelI != (unsigned)-1)
375
0
    Personality =
376
0
        &Cie.Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
377
7
378
7
  // Search for an existing CIE by CIE contents/relocation target pair.
379
7
  CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
380
7
381
7
  // If not found, create a new one.
382
7
  if (!Rec) {
383
7
    Rec = make<CieRecord>();
384
7
    Rec->Cie = &Cie;
385
7
    CieRecords.push_back(Rec);
386
7
  }
387
7
  return Rec;
388
7
}
lld::elf::CieRecord* lld::elf::EhFrameSection::addCie<llvm::object::ELFType<(llvm::support::endianness)0, true>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, true> >(lld::elf::EhSectionPiece&, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, true> >)
Line
Count
Source
371
3
CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) {
372
3
  Symbol *Personality = nullptr;
373
3
  unsigned FirstRelI = Cie.FirstRelocation;
374
3
  if (FirstRelI != (unsigned)-1)
375
1
    Personality =
376
1
        &Cie.Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
377
3
378
3
  // Search for an existing CIE by CIE contents/relocation target pair.
379
3
  CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
380
3
381
3
  // If not found, create a new one.
382
3
  if (!Rec) {
383
3
    Rec = make<CieRecord>();
384
3
    Rec->Cie = &Cie;
385
3
    CieRecords.push_back(Rec);
386
3
  }
387
3
  return Rec;
388
3
}
lld::elf::CieRecord* lld::elf::EhFrameSection::addCie<llvm::object::ELFType<(llvm::support::endianness)0, true>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, false> >(lld::elf::EhSectionPiece&, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, false> >)
Line
Count
Source
371
1
CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) {
372
1
  Symbol *Personality = nullptr;
373
1
  unsigned FirstRelI = Cie.FirstRelocation;
374
1
  if (FirstRelI != (unsigned)-1)
375
0
    Personality =
376
0
        &Cie.Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
377
1
378
1
  // Search for an existing CIE by CIE contents/relocation target pair.
379
1
  CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
380
1
381
1
  // If not found, create a new one.
382
1
  if (!Rec) {
383
1
    Rec = make<CieRecord>();
384
1
    Rec->Cie = &Cie;
385
1
    CieRecords.push_back(Rec);
386
1
  }
387
1
  return Rec;
388
1
}
389
390
// There is one FDE per function. Returns true if a given FDE
391
// points to a live function.
392
template <class ELFT, class RelTy>
393
128
bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef<RelTy> Rels) {
394
128
  auto *Sec = cast<EhInputSection>(Fde.Sec);
395
128
  unsigned FirstRelI = Fde.FirstRelocation;
396
128
397
128
  // An FDE should point to some function because FDEs are to describe
398
128
  // functions. That's however not always the case due to an issue of
399
128
  // ld.gold with -r. ld.gold may discard only functions and leave their
400
128
  // corresponding FDEs, which results in creating bad .eh_frame sections.
401
128
  // To deal with that, we ignore such FDEs.
402
128
  if (FirstRelI == (unsigned)-1)
403
1
    return false;
404
127
405
127
  const RelTy &Rel = Rels[FirstRelI];
406
127
  Symbol &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
407
127
408
127
  // FDEs for garbage-collected or merged-by-ICF sections are dead.
409
127
  if (auto *D = dyn_cast<Defined>(&B))
410
126
    if (SectionBase *Sec = D->Section)
411
126
      return Sec->Live;
412
1
  return false;
413
1
}
Unexecuted instantiation: bool lld::elf::EhFrameSection::isFdeLive<llvm::object::ELFType<(llvm::support::endianness)1, false>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, true> >(lld::elf::EhSectionPiece&, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, true> >)
bool lld::elf::EhFrameSection::isFdeLive<llvm::object::ELFType<(llvm::support::endianness)1, false>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, false> >(lld::elf::EhSectionPiece&, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, false> >)
Line
Count
Source
393
4
bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef<RelTy> Rels) {
394
4
  auto *Sec = cast<EhInputSection>(Fde.Sec);
395
4
  unsigned FirstRelI = Fde.FirstRelocation;
396
4
397
4
  // An FDE should point to some function because FDEs are to describe
398
4
  // functions. That's however not always the case due to an issue of
399
4
  // ld.gold with -r. ld.gold may discard only functions and leave their
400
4
  // corresponding FDEs, which results in creating bad .eh_frame sections.
401
4
  // To deal with that, we ignore such FDEs.
402
4
  if (FirstRelI == (unsigned)-1)
403
0
    return false;
404
4
405
4
  const RelTy &Rel = Rels[FirstRelI];
406
4
  Symbol &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
407
4
408
4
  // FDEs for garbage-collected or merged-by-ICF sections are dead.
409
4
  if (auto *D = dyn_cast<Defined>(&B))
410
4
    if (SectionBase *Sec = D->Section)
411
4
      return Sec->Live;
412
0
  return false;
413
0
}
Unexecuted instantiation: bool lld::elf::EhFrameSection::isFdeLive<llvm::object::ELFType<(llvm::support::endianness)0, false>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, true> >(lld::elf::EhSectionPiece&, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, true> >)
bool lld::elf::EhFrameSection::isFdeLive<llvm::object::ELFType<(llvm::support::endianness)0, false>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, false> >(lld::elf::EhSectionPiece&, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, false> >)
Line
Count
Source
393
1
bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef<RelTy> Rels) {
394
1
  auto *Sec = cast<EhInputSection>(Fde.Sec);
395
1
  unsigned FirstRelI = Fde.FirstRelocation;
396
1
397
1
  // An FDE should point to some function because FDEs are to describe
398
1
  // functions. That's however not always the case due to an issue of
399
1
  // ld.gold with -r. ld.gold may discard only functions and leave their
400
1
  // corresponding FDEs, which results in creating bad .eh_frame sections.
401
1
  // To deal with that, we ignore such FDEs.
402
1
  if (FirstRelI == (unsigned)-1)
403
0
    return false;
404
1
405
1
  const RelTy &Rel = Rels[FirstRelI];
406
1
  Symbol &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
407
1
408
1
  // FDEs for garbage-collected or merged-by-ICF sections are dead.
409
1
  if (auto *D = dyn_cast<Defined>(&B))
410
1
    if (SectionBase *Sec = D->Section)
411
1
      return Sec->Live;
412
0
  return false;
413
0
}
bool lld::elf::EhFrameSection::isFdeLive<llvm::object::ELFType<(llvm::support::endianness)1, true>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, true> >(lld::elf::EhSectionPiece&, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, true> >)
Line
Count
Source
393
119
bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef<RelTy> Rels) {
394
119
  auto *Sec = cast<EhInputSection>(Fde.Sec);
395
119
  unsigned FirstRelI = Fde.FirstRelocation;
396
119
397
119
  // An FDE should point to some function because FDEs are to describe
398
119
  // functions. That's however not always the case due to an issue of
399
119
  // ld.gold with -r. ld.gold may discard only functions and leave their
400
119
  // corresponding FDEs, which results in creating bad .eh_frame sections.
401
119
  // To deal with that, we ignore such FDEs.
402
119
  if (FirstRelI == (unsigned)-1)
403
0
    return false;
404
119
405
119
  const RelTy &Rel = Rels[FirstRelI];
406
119
  Symbol &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
407
119
408
119
  // FDEs for garbage-collected or merged-by-ICF sections are dead.
409
119
  if (auto *D = dyn_cast<Defined>(&B))
410
118
    if (SectionBase *Sec = D->Section)
411
118
      return Sec->Live;
412
1
  return false;
413
1
}
bool lld::elf::EhFrameSection::isFdeLive<llvm::object::ELFType<(llvm::support::endianness)1, true>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, false> >(lld::elf::EhSectionPiece&, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, false> >)
Line
Count
Source
393
1
bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef<RelTy> Rels) {
394
1
  auto *Sec = cast<EhInputSection>(Fde.Sec);
395
1
  unsigned FirstRelI = Fde.FirstRelocation;
396
1
397
1
  // An FDE should point to some function because FDEs are to describe
398
1
  // functions. That's however not always the case due to an issue of
399
1
  // ld.gold with -r. ld.gold may discard only functions and leave their
400
1
  // corresponding FDEs, which results in creating bad .eh_frame sections.
401
1
  // To deal with that, we ignore such FDEs.
402
1
  if (FirstRelI == (unsigned)-1)
403
1
    return false;
404
0
405
0
  const RelTy &Rel = Rels[FirstRelI];
406
0
  Symbol &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
407
0
408
0
  // FDEs for garbage-collected or merged-by-ICF sections are dead.
409
0
  if (auto *D = dyn_cast<Defined>(&B))
410
0
    if (SectionBase *Sec = D->Section)
411
0
      return Sec->Live;
412
0
  return false;
413
0
}
bool lld::elf::EhFrameSection::isFdeLive<llvm::object::ELFType<(llvm::support::endianness)0, true>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, true> >(lld::elf::EhSectionPiece&, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, true> >)
Line
Count
Source
393
3
bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef<RelTy> Rels) {
394
3
  auto *Sec = cast<EhInputSection>(Fde.Sec);
395
3
  unsigned FirstRelI = Fde.FirstRelocation;
396
3
397
3
  // An FDE should point to some function because FDEs are to describe
398
3
  // functions. That's however not always the case due to an issue of
399
3
  // ld.gold with -r. ld.gold may discard only functions and leave their
400
3
  // corresponding FDEs, which results in creating bad .eh_frame sections.
401
3
  // To deal with that, we ignore such FDEs.
402
3
  if (FirstRelI == (unsigned)-1)
403
0
    return false;
404
3
405
3
  const RelTy &Rel = Rels[FirstRelI];
406
3
  Symbol &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
407
3
408
3
  // FDEs for garbage-collected or merged-by-ICF sections are dead.
409
3
  if (auto *D = dyn_cast<Defined>(&B))
410
3
    if (SectionBase *Sec = D->Section)
411
3
      return Sec->Live;
412
0
  return false;
413
0
}
Unexecuted instantiation: bool lld::elf::EhFrameSection::isFdeLive<llvm::object::ELFType<(llvm::support::endianness)0, true>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, false> >(lld::elf::EhSectionPiece&, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, false> >)
414
415
// .eh_frame is a sequence of CIE or FDE records. In general, there
416
// is one CIE record per input object file which is followed by
417
// a list of FDEs. This function searches an existing CIE or create a new
418
// one and associates FDEs to the CIE.
419
template <class ELFT, class RelTy>
420
108
void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
421
108
  OffsetToCie.clear();
422
238
  for (EhSectionPiece &Piece : Sec->Pieces) {
423
238
    // The empty record is the end marker.
424
238
    if (Piece.Size == 4)
425
6
      return;
426
232
427
232
    size_t Offset = Piece.InputOff;
428
232
    uint32_t ID = read32(Piece.data().data() + 4);
429
232
    if (ID == 0) {
430
104
      OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
431
104
      continue;
432
104
    }
433
128
434
128
    uint32_t CieOffset = Offset + 4 - ID;
435
128
    CieRecord *Rec = OffsetToCie[CieOffset];
436
128
    if (!Rec)
437
0
      fatal(toString(Sec) + ": invalid CIE reference");
438
128
439
128
    if (!isFdeLive<ELFT>(Piece, Rels))
440
10
      continue;
441
118
    Rec->Fdes.push_back(&Piece);
442
118
    NumFdes++;
443
118
  }
444
108
}
Unexecuted instantiation: void lld::elf::EhFrameSection::addSectionAux<llvm::object::ELFType<(llvm::support::endianness)1, false>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, true> >(lld::elf::EhInputSection*, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, true> >)
void lld::elf::EhFrameSection::addSectionAux<llvm::object::ELFType<(llvm::support::endianness)1, false>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, false> >(lld::elf::EhInputSection*, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, false> >)
Line
Count
Source
420
4
void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
421
4
  OffsetToCie.clear();
422
8
  for (EhSectionPiece &Piece : Sec->Pieces) {
423
8
    // The empty record is the end marker.
424
8
    if (Piece.Size == 4)
425
0
      return;
426
8
427
8
    size_t Offset = Piece.InputOff;
428
8
    uint32_t ID = read32(Piece.data().data() + 4);
429
8
    if (ID == 0) {
430
4
      OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
431
4
      continue;
432
4
    }
433
4
434
4
    uint32_t CieOffset = Offset + 4 - ID;
435
4
    CieRecord *Rec = OffsetToCie[CieOffset];
436
4
    if (!Rec)
437
0
      fatal(toString(Sec) + ": invalid CIE reference");
438
4
439
4
    if (!isFdeLive<ELFT>(Piece, Rels))
440
0
      continue;
441
4
    Rec->Fdes.push_back(&Piece);
442
4
    NumFdes++;
443
4
  }
444
4
}
Unexecuted instantiation: void lld::elf::EhFrameSection::addSectionAux<llvm::object::ELFType<(llvm::support::endianness)0, false>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, true> >(lld::elf::EhInputSection*, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, true> >)
void lld::elf::EhFrameSection::addSectionAux<llvm::object::ELFType<(llvm::support::endianness)0, false>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, false> >(lld::elf::EhInputSection*, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, false> >)
Line
Count
Source
420
1
void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
421
1
  OffsetToCie.clear();
422
2
  for (EhSectionPiece &Piece : Sec->Pieces) {
423
2
    // The empty record is the end marker.
424
2
    if (Piece.Size == 4)
425
0
      return;
426
2
427
2
    size_t Offset = Piece.InputOff;
428
2
    uint32_t ID = read32(Piece.data().data() + 4);
429
2
    if (ID == 0) {
430
1
      OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
431
1
      continue;
432
1
    }
433
1
434
1
    uint32_t CieOffset = Offset + 4 - ID;
435
1
    CieRecord *Rec = OffsetToCie[CieOffset];
436
1
    if (!Rec)
437
0
      fatal(toString(Sec) + ": invalid CIE reference");
438
1
439
1
    if (!isFdeLive<ELFT>(Piece, Rels))
440
0
      continue;
441
1
    Rec->Fdes.push_back(&Piece);
442
1
    NumFdes++;
443
1
  }
444
1
}
void lld::elf::EhFrameSection::addSectionAux<llvm::object::ELFType<(llvm::support::endianness)1, true>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, true> >(lld::elf::EhInputSection*, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, true> >)
Line
Count
Source
420
86
void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
421
86
  OffsetToCie.clear();
422
207
  for (EhSectionPiece &Piece : Sec->Pieces) {
423
207
    // The empty record is the end marker.
424
207
    if (Piece.Size == 4)
425
0
      return;
426
207
427
207
    size_t Offset = Piece.InputOff;
428
207
    uint32_t ID = read32(Piece.data().data() + 4);
429
207
    if (ID == 0) {
430
88
      OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
431
88
      continue;
432
88
    }
433
119
434
119
    uint32_t CieOffset = Offset + 4 - ID;
435
119
    CieRecord *Rec = OffsetToCie[CieOffset];
436
119
    if (!Rec)
437
0
      fatal(toString(Sec) + ": invalid CIE reference");
438
119
439
119
    if (!isFdeLive<ELFT>(Piece, Rels))
440
9
      continue;
441
110
    Rec->Fdes.push_back(&Piece);
442
110
    NumFdes++;
443
110
  }
444
86
}
void lld::elf::EhFrameSection::addSectionAux<llvm::object::ELFType<(llvm::support::endianness)1, true>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, false> >(lld::elf::EhInputSection*, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, false> >)
Line
Count
Source
420
13
void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
421
13
  OffsetToCie.clear();
422
14
  for (EhSectionPiece &Piece : Sec->Pieces) {
423
14
    // The empty record is the end marker.
424
14
    if (Piece.Size == 4)
425
6
      return;
426
8
427
8
    size_t Offset = Piece.InputOff;
428
8
    uint32_t ID = read32(Piece.data().data() + 4);
429
8
    if (ID == 0) {
430
7
      OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
431
7
      continue;
432
7
    }
433
1
434
1
    uint32_t CieOffset = Offset + 4 - ID;
435
1
    CieRecord *Rec = OffsetToCie[CieOffset];
436
1
    if (!Rec)
437
0
      fatal(toString(Sec) + ": invalid CIE reference");
438
1
439
1
    if (!isFdeLive<ELFT>(Piece, Rels))
440
1
      continue;
441
0
    Rec->Fdes.push_back(&Piece);
442
0
    NumFdes++;
443
0
  }
444
13
}
void lld::elf::EhFrameSection::addSectionAux<llvm::object::ELFType<(llvm::support::endianness)0, true>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, true> >(lld::elf::EhInputSection*, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, true> >)
Line
Count
Source
420
3
void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
421
3
  OffsetToCie.clear();
422
6
  for (EhSectionPiece &Piece : Sec->Pieces) {
423
6
    // The empty record is the end marker.
424
6
    if (Piece.Size == 4)
425
0
      return;
426
6
427
6
    size_t Offset = Piece.InputOff;
428
6
    uint32_t ID = read32(Piece.data().data() + 4);
429
6
    if (ID == 0) {
430
3
      OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
431
3
      continue;
432
3
    }
433
3
434
3
    uint32_t CieOffset = Offset + 4 - ID;
435
3
    CieRecord *Rec = OffsetToCie[CieOffset];
436
3
    if (!Rec)
437
0
      fatal(toString(Sec) + ": invalid CIE reference");
438
3
439
3
    if (!isFdeLive<ELFT>(Piece, Rels))
440
0
      continue;
441
3
    Rec->Fdes.push_back(&Piece);
442
3
    NumFdes++;
443
3
  }
444
3
}
void lld::elf::EhFrameSection::addSectionAux<llvm::object::ELFType<(llvm::support::endianness)0, true>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, false> >(lld::elf::EhInputSection*, llvm::ArrayRef<llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, false> >)
Line
Count
Source
420
1
void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
421
1
  OffsetToCie.clear();
422
1
  for (EhSectionPiece &Piece : Sec->Pieces) {
423
1
    // The empty record is the end marker.
424
1
    if (Piece.Size == 4)
425
0
      return;
426
1
427
1
    size_t Offset = Piece.InputOff;
428
1
    uint32_t ID = read32(Piece.data().data() + 4);
429
1
    if (ID == 0) {
430
1
      OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
431
1
      continue;
432
1
    }
433
0
434
0
    uint32_t CieOffset = Offset + 4 - ID;
435
0
    CieRecord *Rec = OffsetToCie[CieOffset];
436
0
    if (!Rec)
437
0
      fatal(toString(Sec) + ": invalid CIE reference");
438
0
439
0
    if (!isFdeLive<ELFT>(Piece, Rels))
440
0
      continue;
441
0
    Rec->Fdes.push_back(&Piece);
442
0
    NumFdes++;
443
0
  }
444
1
}
445
446
111
template <class ELFT> void EhFrameSection::addSection(InputSectionBase *C) {
447
111
  auto *Sec = cast<EhInputSection>(C);
448
111
  Sec->Parent = this;
449
111
450
111
  Alignment = std::max(Alignment, Sec->Alignment);
451
111
  Sections.push_back(Sec);
452
111
453
111
  for (auto *DS : Sec->DependentSections)
454
3
    DependentSections.push_back(DS);
455
111
456
111
  if (Sec->Pieces.empty())
457
3
    return;
458
108
459
108
  if (Sec->AreRelocsRela)
460
89
    addSectionAux<ELFT>(Sec, Sec->template relas<ELFT>());
461
19
  else
462
19
    addSectionAux<ELFT>(Sec, Sec->template rels<ELFT>());
463
108
}
void lld::elf::EhFrameSection::addSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >(lld::elf::InputSectionBase*)
Line
Count
Source
446
4
template <class ELFT> void EhFrameSection::addSection(InputSectionBase *C) {
447
4
  auto *Sec = cast<EhInputSection>(C);
448
4
  Sec->Parent = this;
449
4
450
4
  Alignment = std::max(Alignment, Sec->Alignment);
451
4
  Sections.push_back(Sec);
452
4
453
4
  for (auto *DS : Sec->DependentSections)
454
0
    DependentSections.push_back(DS);
455
4
456
4
  if (Sec->Pieces.empty())
457
0
    return;
458
4
459
4
  if (Sec->AreRelocsRela)
460
0
    addSectionAux<ELFT>(Sec, Sec->template relas<ELFT>());
461
4
  else
462
4
    addSectionAux<ELFT>(Sec, Sec->template rels<ELFT>());
463
4
}
void lld::elf::EhFrameSection::addSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >(lld::elf::InputSectionBase*)
Line
Count
Source
446
1
template <class ELFT> void EhFrameSection::addSection(InputSectionBase *C) {
447
1
  auto *Sec = cast<EhInputSection>(C);
448
1
  Sec->Parent = this;
449
1
450
1
  Alignment = std::max(Alignment, Sec->Alignment);
451
1
  Sections.push_back(Sec);
452
1
453
1
  for (auto *DS : Sec->DependentSections)
454
0
    DependentSections.push_back(DS);
455
1
456
1
  if (Sec->Pieces.empty())
457
0
    return;
458
1
459
1
  if (Sec->AreRelocsRela)
460
0
    addSectionAux<ELFT>(Sec, Sec->template relas<ELFT>());
461
1
  else
462
1
    addSectionAux<ELFT>(Sec, Sec->template rels<ELFT>());
463
1
}
void lld::elf::EhFrameSection::addSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >(lld::elf::InputSectionBase*)
Line
Count
Source
446
102
template <class ELFT> void EhFrameSection::addSection(InputSectionBase *C) {
447
102
  auto *Sec = cast<EhInputSection>(C);
448
102
  Sec->Parent = this;
449
102
450
102
  Alignment = std::max(Alignment, Sec->Alignment);
451
102
  Sections.push_back(Sec);
452
102
453
102
  for (auto *DS : Sec->DependentSections)
454
3
    DependentSections.push_back(DS);
455
102
456
102
  if (Sec->Pieces.empty())
457
3
    return;
458
99
459
99
  if (Sec->AreRelocsRela)
460
86
    addSectionAux<ELFT>(Sec, Sec->template relas<ELFT>());
461
13
  else
462
13
    addSectionAux<ELFT>(Sec, Sec->template rels<ELFT>());
463
99
}
void lld::elf::EhFrameSection::addSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >(lld::elf::InputSectionBase*)
Line
Count
Source
446
4
template <class ELFT> void EhFrameSection::addSection(InputSectionBase *C) {
447
4
  auto *Sec = cast<EhInputSection>(C);
448
4
  Sec->Parent = this;
449
4
450
4
  Alignment = std::max(Alignment, Sec->Alignment);
451
4
  Sections.push_back(Sec);
452
4
453
4
  for (auto *DS : Sec->DependentSections)
454
0
    DependentSections.push_back(DS);
455
4
456
4
  if (Sec->Pieces.empty())
457
0
    return;
458
4
459
4
  if (Sec->AreRelocsRela)
460
3
    addSectionAux<ELFT>(Sec, Sec->template relas<ELFT>());
461
1
  else
462
1
    addSectionAux<ELFT>(Sec, Sec->template rels<ELFT>());
463
4
}
464
465
200
static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
466
200
  memcpy(Buf, D.data(), D.size());
467
200
468
200
  size_t Aligned = alignTo(D.size(), Config->Wordsize);
469
200
470
200
  // Zero-clear trailing padding if it exists.
471
200
  memset(Buf + D.size(), 0, Aligned - D.size());
472
200
473
200
  // Fix the size field. -4 since size does not include the size field itself.
474
200
  write32(Buf, Aligned - 4);
475
200
}
476
477
94
void EhFrameSection::finalizeContents() {
478
94
  assert(!this->Size); // Not finalized.
479
94
  size_t Off = 0;
480
94
  for (CieRecord *Rec : CieRecords) {
481
88
    Rec->Cie->OutputOff = Off;
482
88
    Off += alignTo(Rec->Cie->Size, Config->Wordsize);
483
88
484
116
    for (EhSectionPiece *Fde : Rec->Fdes) {
485
116
      Fde->OutputOff = Off;
486
116
      Off += alignTo(Fde->Size, Config->Wordsize);
487
116
    }
488
88
  }
489
94
490
94
  // The LSB standard does not allow a .eh_frame section with zero
491
94
  // Call Frame Information records. glibc unwind-dw2-fde.c
492
94
  // classify_object_over_fdes expects there is a CIE record length 0 as a
493
94
  // terminator. Thus we add one unconditionally.
494
94
  Off += 4;
495
94
496
94
  this->Size = Off;
497
94
}
498
499
// Returns data for .eh_frame_hdr. .eh_frame_hdr is a binary search table
500
// to get an FDE from an address to which FDE is applied. This function
501
// returns a list of such pairs.
502
27
std::vector<EhFrameSection::FdeData> EhFrameSection::getFdeData() const {
503
27
  uint8_t *Buf = getParent()->Loc + OutSecOff;
504
27
  std::vector<FdeData> Ret;
505
27
506
27
  uint64_t VA = In.EhFrameHdr->getVA();
507
27
  for (CieRecord *Rec : CieRecords) {
508
27
    uint8_t Enc = getFdeEncoding(Rec->Cie);
509
27
    for (EhSectionPiece *Fde : Rec->Fdes) {
510
23
      uint64_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
511
23
      uint64_t FdeVA = getParent()->Addr + Fde->OutputOff;
512
23
      if (!isInt<32>(Pc - VA))
513
0
        fatal(toString(Fde->Sec) + ": PC offset is too large: 0x" +
514
0
              Twine::utohexstr(Pc - VA));
515
23
      Ret.push_back({uint32_t(Pc - VA), uint32_t(FdeVA - VA)});
516
23
    }
517
27
  }
518
27
519
27
  // Sort the FDE list by their PC and uniqueify. Usually there is only
520
27
  // one FDE for a PC (i.e. function), but if ICF merges two functions
521
27
  // into one, there can be more than one FDEs pointing to the address.
522
27
  auto Less = [](const FdeData &A, const FdeData &B) {
523
4
    return A.PcRel < B.PcRel;
524
4
  };
525
27
  std::stable_sort(Ret.begin(), Ret.end(), Less);
526
27
  auto Eq = [](const FdeData &A, const FdeData &B) {
527
4
    return A.PcRel == B.PcRel;
528
4
  };
529
27
  Ret.erase(std::unique(Ret.begin(), Ret.end(), Eq), Ret.end());
530
27
531
27
  return Ret;
532
27
}
533
534
23
static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
535
23
  switch (Size) {
536
23
  case DW_EH_PE_udata2:
537
1
    return read16(Buf);
538
23
  case DW_EH_PE_sdata2:
539
1
    return (int16_t)read16(Buf);
540
23
  case DW_EH_PE_udata4:
541
0
    return read32(Buf);
542
23
  case DW_EH_PE_sdata4:
543
16
    return (int32_t)read32(Buf);
544
23
  case DW_EH_PE_udata8:
545
3
  case DW_EH_PE_sdata8:
546
3
    return read64(Buf);
547
3
  case DW_EH_PE_absptr:
548
2
    return readUint(Buf);
549
0
  }
550
0
  fatal("unknown FDE size encoding");
551
0
}
552
553
// Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
554
// We need it to create .eh_frame_hdr section.
555
uint64_t EhFrameSection::getFdePc(uint8_t *Buf, size_t FdeOff,
556
23
                                  uint8_t Enc) const {
557
23
  // The starting address to which this FDE applies is
558
23
  // stored at FDE + 8 byte.
559
23
  size_t Off = FdeOff + 8;
560
23
  uint64_t Addr = readFdeAddr(Buf + Off, Enc & 0xf);
561
23
  if ((Enc & 0x70) == DW_EH_PE_absptr)
562
6
    return Addr;
563
17
  if ((Enc & 0x70) == DW_EH_PE_pcrel)
564
17
    return Addr + getParent()->Addr + Off;
565
0
  fatal("unknown FDE size relative encoding");
566
0
}
567
568
92
void EhFrameSection::writeTo(uint8_t *Buf) {
569
92
  // Write CIE and FDE records.
570
92
  for (CieRecord *Rec : CieRecords) {
571
86
    size_t CieOffset = Rec->Cie->OutputOff;
572
86
    writeCieFde(Buf + CieOffset, Rec->Cie->data());
573
86
574
114
    for (EhSectionPiece *Fde : Rec->Fdes) {
575
114
      size_t Off = Fde->OutputOff;
576
114
      writeCieFde(Buf + Off, Fde->data());
577
114
578
114
      // FDE's second word should have the offset to an associated CIE.
579
114
      // Write it.
580
114
      write32(Buf + Off + 4, Off + 4 - CieOffset);
581
114
    }
582
86
  }
583
92
584
92
  // Apply relocations. .eh_frame section contents are not contiguous
585
92
  // in the output buffer, but relocateAlloc() still works because
586
92
  // getOffset() takes care of discontiguous section pieces.
587
92
  for (EhInputSection *S : Sections)
588
106
    S->relocateAlloc(Buf, nullptr);
589
92
}
590
591
GotSection::GotSection()
592
    : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
593
2.21k
                       Target->GotEntrySize, ".got") {
594
2.21k
  // PPC64 saves the ElfSym::GlobalOffsetTable .TOC. as the first entry in the
595
2.21k
  // .got. If there are no references to .TOC. in the symbol table,
596
2.21k
  // ElfSym::GlobalOffsetTable will not be defined and we won't need to save
597
2.21k
  // .TOC. in the .got. When it is defined, we increase NumEntries by the number
598
2.21k
  // of entries used to emit ElfSym::GlobalOffsetTable.
599
2.21k
  if (ElfSym::GlobalOffsetTable && 
!Target->GotBaseSymInGotPlt116
)
600
85
    NumEntries += Target->GotHeaderEntriesNum;
601
2.21k
}
602
603
155
void GotSection::addEntry(Symbol &Sym) {
604
155
  Sym.GotIndex = NumEntries;
605
155
  ++NumEntries;
606
155
}
607
608
52
bool GotSection::addDynTlsEntry(Symbol &Sym) {
609
52
  if (Sym.GlobalDynIndex != -1U)
610
20
    return false;
611
32
  Sym.GlobalDynIndex = NumEntries;
612
32
  // Global Dynamic TLS entries take two GOT slots.
613
32
  NumEntries += 2;
614
32
  return true;
615
32
}
616
617
// Reserves TLS entries for a TLS module ID and a TLS block offset.
618
// In total it takes two GOT slots.
619
27
bool GotSection::addTlsIndex() {
620
27
  if (TlsIndexOff != uint32_t(-1))
621
18
    return false;
622
9
  TlsIndexOff = NumEntries * Config->Wordsize;
623
9
  NumEntries += 2;
624
9
  return true;
625
9
}
626
627
34
uint64_t GotSection::getGlobalDynAddr(const Symbol &B) const {
628
34
  return this->getVA() + B.GlobalDynIndex * Config->Wordsize;
629
34
}
630
631
42
uint64_t GotSection::getGlobalDynOffset(const Symbol &B) const {
632
42
  return B.GlobalDynIndex * Config->Wordsize;
633
42
}
634
635
196
void GotSection::finalizeContents() {
636
196
  Size = NumEntries * Config->Wordsize;
637
196
}
638
639
4.23k
bool GotSection::empty() const {
640
4.23k
  // We need to emit a GOT even if it's empty if there's a relocation that is
641
4.23k
  // relative to GOT(such as GOTOFFREL) or there's a symbol that points to a GOT
642
4.23k
  // (i.e. _GLOBAL_OFFSET_TABLE_) that the target defines relative to the .got.
643
4.23k
  return NumEntries == 0 && 
!HasGotOffRel3.85k
&&
644
4.23k
         
!(3.83k
ElfSym::GlobalOffsetTable3.83k
&&
!Target->GotBaseSymInGotPlt40
);
645
4.23k
}
646
647
195
void GotSection::writeTo(uint8_t *Buf) {
648
195
  // Buf points to the start of this section's buffer,
649
195
  // whereas InputSectionBase::relocateAlloc() expects its argument
650
195
  // to point to the start of the output section.
651
195
  Target->writeGotHeader(Buf);
652
195
  relocateAlloc(Buf - OutSecOff, Buf - OutSecOff + Size);
653
195
}
654
655
71
static uint64_t getMipsPageAddr(uint64_t Addr) {
656
71
  return (Addr + 0x8000) & ~0xffff;
657
71
}
658
659
14
static uint64_t getMipsPageCount(uint64_t Size) {
660
14
  return (Size + 0xfffe) / 0xffff + 1;
661
14
}
662
663
MipsGotSection::MipsGotSection()
664
    : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
665
192
                       ".got") {}
666
667
void MipsGotSection::addEntry(InputFile &File, Symbol &Sym, int64_t Addend,
668
10.1k
                              RelExpr Expr) {
669
10.1k
  FileGot &G = getGot(File);
670
10.1k
  if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
671
29
    if (const OutputSection *OS = Sym.getOutputSection())
672
25
      G.PagesMap.insert({OS, {}});
673
4
    else
674
4
      G.Local16.insert({{nullptr, getMipsPageAddr(Sym.getVA(Addend))}, 0});
675
10.0k
  } else if (Sym.isTls())
676
13
    G.Tls.insert({&Sym, 0});
677
10.0k
  else if (Sym.IsPreemptible && 
Expr == R_ABS41
)
678
4
    G.Relocs.insert({&Sym, 0});
679
10.0k
  else if (Sym.IsPreemptible)
680
37
    G.Global.insert({&Sym, 0});
681
10.0k
  else if (Expr == R_MIPS_GOT_OFF32)
682
12
    G.Local32.insert({{&Sym, Addend}, 0});
683
10.0k
  else
684
10.0k
    G.Local16.insert({{&Sym, Addend}, 0});
685
10.1k
}
686
687
12
void MipsGotSection::addDynTlsEntry(InputFile &File, Symbol &Sym) {
688
12
  getGot(File).DynTlsSymbols.insert({&Sym, 0});
689
12
}
690
691
6
void MipsGotSection::addTlsIndex(InputFile &File) {
692
6
  getGot(File).DynTlsSymbols.insert({nullptr, 0});
693
6
}
694
695
114
size_t MipsGotSection::FileGot::getEntriesNum() const {
696
114
  return getPageEntriesNum() + Local16.size() + Global.size() + Relocs.size() +
697
114
         Tls.size() + DynTlsSymbols.size() * 2;
698
114
}
699
700
218
size_t MipsGotSection::FileGot::getPageEntriesNum() const {
701
218
  size_t Num = 0;
702
218
  for (const std::pair<const OutputSection *, FileGot::PageBlock> &P : PagesMap)
703
52
    Num += P.second.Count;
704
218
  return Num;
705
218
}
706
707
59
size_t MipsGotSection::FileGot::getIndexedEntriesNum() const {
708
59
  size_t Count = getPageEntriesNum() + Local16.size() + Global.size();
709
59
  // If there are relocation-only entries in the GOT, TLS entries
710
59
  // are allocated after them. TLS entries should be addressable
711
59
  // by 16-bit index so count both reloc-only and TLS entries.
712
59
  if (!Tls.empty() || 
!DynTlsSymbols.empty()50
)
713
10
    Count += Relocs.size() + Tls.size() + DynTlsSymbols.size() * 2;
714
59
  return Count;
715
59
}
716
717
10.1k
MipsGotSection::FileGot &MipsGotSection::getGot(InputFile &F) {
718
10.1k
  if (!F.MipsGotIndex.hasValue()) {
719
58
    Gots.emplace_back();
720
58
    Gots.back().File = &F;
721
58
    F.MipsGotIndex = Gots.size() - 1;
722
58
  }
723
10.1k
  return Gots[*F.MipsGotIndex];
724
10.1k
}
725
726
uint64_t MipsGotSection::getPageEntryOffset(const InputFile *F,
727
                                            const Symbol &Sym,
728
29
                                            int64_t Addend) const {
729
29
  const FileGot &G = Gots[*F->MipsGotIndex];
730
29
  uint64_t Index = 0;
731
29
  if (const OutputSection *OutSec = Sym.getOutputSection()) {
732
25
    uint64_t SecAddr = getMipsPageAddr(OutSec->Addr);
733
25
    uint64_t SymAddr = getMipsPageAddr(Sym.getVA(Addend));
734
25
    Index = G.PagesMap.lookup(OutSec).FirstIndex + (SymAddr - SecAddr) / 0xffff;
735
25
  } else {
736
4
    Index = G.Local16.lookup({nullptr, getMipsPageAddr(Sym.getVA(Addend))});
737
4
  }
738
29
  return Index * Config->Wordsize;
739
29
}
740
741
uint64_t MipsGotSection::getSymEntryOffset(const InputFile *F, const Symbol &S,
742
10.0k
                                           int64_t Addend) const {
743
10.0k
  const FileGot &G = Gots[*F->MipsGotIndex];
744
10.0k
  Symbol *Sym = const_cast<Symbol *>(&S);
745
10.0k
  if (Sym->isTls())
746
13
    return G.Tls.lookup(Sym) * Config->Wordsize;
747
10.0k
  if (Sym->IsPreemptible)
748
37
    return G.Global.lookup(Sym) * Config->Wordsize;
749
10.0k
  return G.Local16.lookup({Sym, Addend}) * Config->Wordsize;
750
10.0k
}
751
752
6
uint64_t MipsGotSection::getTlsIndexOffset(const InputFile *F) const {
753
6
  const FileGot &G = Gots[*F->MipsGotIndex];
754
6
  return G.DynTlsSymbols.lookup(nullptr) * Config->Wordsize;
755
6
}
756
757
uint64_t MipsGotSection::getGlobalDynOffset(const InputFile *F,
758
12
                                            const Symbol &S) const {
759
12
  const FileGot &G = Gots[*F->MipsGotIndex];
760
12
  Symbol *Sym = const_cast<Symbol *>(&S);
761
12
  return G.DynTlsSymbols.lookup(Sym) * Config->Wordsize;
762
12
}
763
764
100
const Symbol *MipsGotSection::getFirstGlobalEntry() const {
765
100
  if (Gots.empty())
766
55
    return nullptr;
767
45
  const FileGot &PrimGot = Gots.front();
768
45
  if (!PrimGot.Global.empty())
769
27
    return PrimGot.Global.front().first;
770
18
  if (!PrimGot.Relocs.empty())
771
5
    return PrimGot.Relocs.front().first;
772
13
  return nullptr;
773
13
}
774
775
100
unsigned MipsGotSection::getLocalEntriesNum() const {
776
100
  if (Gots.empty())
777
55
    return HeaderEntriesNum;
778
45
  return HeaderEntriesNum + Gots.front().getPageEntriesNum() +
779
45
         Gots.front().Local16.size();
780
45
}
781
782
59
bool MipsGotSection::tryMergeGots(FileGot &Dst, FileGot &Src, bool IsPrimary) {
783
59
  FileGot Tmp = Dst;
784
59
  set_union(Tmp.PagesMap, Src.PagesMap);
785
59
  set_union(Tmp.Local16, Src.Local16);
786
59
  set_union(Tmp.Global, Src.Global);
787
59
  set_union(Tmp.Relocs, Src.Relocs);
788
59
  set_union(Tmp.Tls, Src.Tls);
789
59
  set_union(Tmp.DynTlsSymbols, Src.DynTlsSymbols);
790
59
791
59
  size_t Count = IsPrimary ? 
HeaderEntriesNum58
:
01
;
792
59
  Count += Tmp.getIndexedEntriesNum();
793
59
794
59
  if (Count * Config->Wordsize > Config->MipsGotSize)
795
4
    return false;
796
55
797
55
  std::swap(Tmp, Dst);
798
55
  return true;
799
55
}
800
801
169
void MipsGotSection::finalizeContents() { updateAllocSize(); }
802
803
363
bool MipsGotSection::updateAllocSize() {
804
363
  Size = HeaderEntriesNum * Config->Wordsize;
805
363
  for (const FileGot &G : Gots)
806
114
    Size += G.getEntriesNum() * Config->Wordsize;
807
363
  return false;
808
363
}
809
810
182
template <class ELFT> void MipsGotSection::build() {
811
182
  if (Gots.empty())
812
128
    return;
813
54
814
54
  std::vector<FileGot> MergedGots(1);
815
54
816
54
  // For each GOT move non-preemptible symbols from the `Global`
817
54
  // to `Local16` list. Preemptible symbol might become non-preemptible
818
54
  // one if, for example, it gets a related copy relocation.
819
58
  for (FileGot &Got : Gots) {
820
58
    for (auto &P: Got.Global)
821
35
      if (!P.first->IsPreemptible)
822
0
        Got.Local16.insert({{P.first, 0}, 0});
823
58
    Got.Global.remove_if([&](const std::pair<Symbol *, size_t> &P) {
824
35
      return !P.first->IsPreemptible;
825
35
    });
void lld::elf::MipsGotSection::build<llvm::object::ELFType<(llvm::support::endianness)1, false> >()::'lambda'(std::__1::pair<lld::elf::Symbol*, unsigned long> const&)::operator()(std::__1::pair<lld::elf::Symbol*, unsigned long> const&) const
Line
Count
Source
823
3
    Got.Global.remove_if([&](const std::pair<Symbol *, size_t> &P) {
824
3
      return !P.first->IsPreemptible;
825
3
    });
void lld::elf::MipsGotSection::build<llvm::object::ELFType<(llvm::support::endianness)0, false> >()::'lambda'(std::__1::pair<lld::elf::Symbol*, unsigned long> const&)::operator()(std::__1::pair<lld::elf::Symbol*, unsigned long> const&) const
Line
Count
Source
823
28
    Got.Global.remove_if([&](const std::pair<Symbol *, size_t> &P) {
824
28
      return !P.first->IsPreemptible;
825
28
    });
Unexecuted instantiation: void lld::elf::MipsGotSection::build<llvm::object::ELFType<(llvm::support::endianness)1, true> >()::'lambda'(std::__1::pair<lld::elf::Symbol*, unsigned long> const&)::operator()(std::__1::pair<lld::elf::Symbol*, unsigned long> const&) const
void lld::elf::MipsGotSection::build<llvm::object::ELFType<(llvm::support::endianness)0, true> >()::'lambda'(std::__1::pair<lld::elf::Symbol*, unsigned long> const&)::operator()(std::__1::pair<lld::elf::Symbol*, unsigned long> const&) const
Line
Count
Source
823
4
    Got.Global.remove_if([&](const std::pair<Symbol *, size_t> &P) {
824
4
      return !P.first->IsPreemptible;
825
4
    });
826
58
  }
827
54
828
54
  // For each GOT remove "reloc-only" entry if there is "global"
829
54
  // entry for the same symbol. And add local entries which indexed
830
54
  // using 32-bit value at the end of 16-bit entries.
831
58
  for (FileGot &Got : Gots) {
832
58
    Got.Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
833
4
      return Got.Global.count(P.first);
834
4
    });
void lld::elf::MipsGotSection::build<llvm::object::ELFType<(llvm::support::endianness)1, false> >()::'lambda0'(std::__1::pair<lld::elf::Symbol*, unsigned long> const&)::operator()(std::__1::pair<lld::elf::Symbol*, unsigned long> const&) const
Line
Count
Source
832
1
    Got.Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
833
1
      return Got.Global.count(P.first);
834
1
    });
void lld::elf::MipsGotSection::build<llvm::object::ELFType<(llvm::support::endianness)0, false> >()::'lambda0'(std::__1::pair<lld::elf::Symbol*, unsigned long> const&)::operator()(std::__1::pair<lld::elf::Symbol*, unsigned long> const&) const
Line
Count
Source
832
1
    Got.Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
833
1
      return Got.Global.count(P.first);
834
1
    });
Unexecuted instantiation: void lld::elf::MipsGotSection::build<llvm::object::ELFType<(llvm::support::endianness)1, true> >()::'lambda0'(std::__1::pair<lld::elf::Symbol*, unsigned long> const&)::operator()(std::__1::pair<lld::elf::Symbol*, unsigned long> const&) const
void lld::elf::MipsGotSection::build<llvm::object::ELFType<(llvm::support::endianness)0, true> >()::'lambda0'(std::__1::pair<lld::elf::Symbol*, unsigned long> const&)::operator()(std::__1::pair<lld::elf::Symbol*, unsigned long> const&) const
Line
Count
Source
832
2
    Got.Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
833
2
      return Got.Global.count(P.first);
834
2
    });
835
58
    set_union(Got.Local16, Got.Local32);
836
58
    Got.Local32.clear();
837
58
  }
838
54
839
54
  // Evaluate number of "reloc-only" entries in the resulting GOT.
840
54
  // To do that put all unique "reloc-only" and "global" entries
841
54
  // from all GOTs to the future primary GOT.
842
54
  FileGot *PrimGot = &MergedGots.front();
843
58
  for (FileGot &Got : Gots) {
844
58
    set_union(PrimGot->Relocs, Got.Global);
845
58
    set_union(PrimGot->Relocs, Got.Relocs);
846
58
    Got.Relocs.clear();
847
58
  }
848
54
849
54
  // Evaluate number of "page" entries in each GOT.
850
58
  for (FileGot &Got : Gots) {
851
58
    for (std::pair<const OutputSection *, FileGot::PageBlock> &P :
852
58
         Got.PagesMap) {
853
14
      const OutputSection *OS = P.first;
854
14
      uint64_t SecSize = 0;
855
16
      for (BaseCommand *Cmd : OS->SectionCommands) {
856
16
        if (auto *ISD = dyn_cast<InputSectionDescription>(Cmd))
857
24
          
for (InputSection *IS : ISD->Sections)15
{
858
24
            uint64_t Off = alignTo(SecSize, IS->Alignment);
859
24
            SecSize = Off + IS->getSize();
860
24
          }
861
16
      }
862
14
      P.second.Count = getMipsPageCount(SecSize);
863
14
    }
864
58
  }
865
54
866
54
  // Merge GOTs. Try to join as much as possible GOTs but do not exceed
867
54
  // maximum GOT size. At first, try to fill the primary GOT because
868
54
  // the primary GOT can be accessed in the most effective way. If it
869
54
  // is not possible, try to fill the last GOT in the list, and finally
870
54
  // create a new GOT if both attempts failed.
871
58
  for (FileGot &SrcGot : Gots) {
872
58
    InputFile *File = SrcGot.File;
873
58
    if (tryMergeGots(MergedGots.front(), SrcGot, true)) {
874
54
      File->MipsGotIndex = 0;
875
54
    } else {
876
4
      // If this is the first time we failed to merge with the primary GOT,
877
4
      // MergedGots.back() will also be the primary GOT. We must make sure not
878
4
      // to try to merge again with IsPrimary=false, as otherwise, if the
879
4
      // inputs are just right, we could allow the primary GOT to become 1 or 2
880
4
      // words too big due to ignoring the header size.
881
4
      if (MergedGots.size() == 1 ||
882
4
          
!tryMergeGots(MergedGots.back(), SrcGot, false)1
) {
883
3
        MergedGots.emplace_back();
884
3
        std::swap(MergedGots.back(), SrcGot);
885
3
      }
886
4
      File->MipsGotIndex = MergedGots.size() - 1;
887
4
    }
888
58
  }
889
54
  std::swap(Gots, MergedGots);
890
54
891
54
  // Reduce number of "reloc-only" entries in the primary GOT
892
54
  // by substracting "global" entries exist in the primary GOT.
893
54
  PrimGot = &Gots.front();
894
54
  PrimGot->Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
895
38
    return PrimGot->Global.count(P.first);
896
38
  });
void lld::elf::MipsGotSection::build<llvm::object::ELFType<(llvm::support::endianness)1, false> >()::'lambda1'(std::__1::pair<lld::elf::Symbol*, unsigned long> const&)::operator()(std::__1::pair<lld::elf::Symbol*, unsigned long> const&) const
Line
Count
Source
894
4
  PrimGot->Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
895
4
    return PrimGot->Global.count(P.first);
896
4
  });
void lld::elf::MipsGotSection::build<llvm::object::ELFType<(llvm::support::endianness)0, false> >()::'lambda1'(std::__1::pair<lld::elf::Symbol*, unsigned long> const&)::operator()(std::__1::pair<lld::elf::Symbol*, unsigned long> const&) const
Line
Count
Source
894
28
  PrimGot->Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
895
28
    return PrimGot->Global.count(P.first);
896
28
  });
Unexecuted instantiation: void lld::elf::MipsGotSection::build<llvm::object::ELFType<(llvm::support::endianness)1, true> >()::'lambda1'(std::__1::pair<lld::elf::Symbol*, unsigned long> const&)::operator()(std::__1::pair<lld::elf::Symbol*, unsigned long> const&) const
void lld::elf::MipsGotSection::build<llvm::object::ELFType<(llvm::support::endianness)0, true> >()::'lambda1'(std::__1::pair<lld::elf::Symbol*, unsigned long> const&)::operator()(std::__1::pair<lld::elf::Symbol*, unsigned long> const&) const
Line
Count
Source
894
6
  PrimGot->Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
895
6
    return PrimGot->Global.count(P.first);
896
6
  });
897
54
898
54
  // Calculate indexes for each GOT entry.
899
54
  size_t Index = HeaderEntriesNum;
900
57
  for (FileGot &Got : Gots) {
901
57
    Got.StartIndex = &Got == PrimGot ? 
054
:
Index3
;
902
57
    for (std::pair<const OutputSection *, FileGot::PageBlock> &P :
903
57
         Got.PagesMap) {
904
13
      // For each output section referenced by GOT page relocations calculate
905
13
      // and save into PagesMap an upper bound of MIPS GOT entries required
906
13
      // to store page addresses of local symbols. We assume the worst case -
907
13
      // each 64kb page of the output section has at least one GOT relocation
908
13
      // against it. And take in account the case when the section intersects
909
13
      // page boundaries.
910
13
      P.second.FirstIndex = Index;
911
13
      Index += P.second.Count;
912
13
    }
913
57
    for (auto &P: Got.Local16)
914
10.0k
      P.second = Index++;
915
57
    for (auto &P: Got.Global)
916
34
      P.second = Index++;
917
57
    for (auto &P: Got.Relocs)
918
6
      P.second = Index++;
919
57
    for (auto &P: Got.Tls)
920
12
      P.second = Index++;
921
57
    for (auto &P: Got.DynTlsSymbols) {
922
17
      P.second = Index;
923
17
      Index += 2;
924
17
    }
925
57
  }
926
54
927
54
  // Update Symbol::GotIndex field to use this
928
54
  // value later in the `sortMipsSymbols` function.
929
54
  for (auto &P : PrimGot->Global)
930
32
    P.first->GotIndex = P.second;
931
54
  for (auto &P : PrimGot->Relocs)
932
6
    P.first->GotIndex = P.second;
933
54
934
54
  // Create dynamic relocations.
935
57
  for (FileGot &Got : Gots) {
936
57
    // Create dynamic relocations for TLS entries.
937
57
    for (std::pair<Symbol *, size_t> &P : Got.Tls) {
938
12
      Symbol *S = P.first;
939
12
      uint64_t Offset = P.second * Config->Wordsize;
940
12
      if (S->IsPreemptible)
941
9
        In.RelaDyn->addReloc(Target->TlsGotRel, this, Offset, S);
942
12
    }
943
57
    for (std::pair<Symbol *, size_t> &P : Got.DynTlsSymbols) {
944
17
      Symbol *S = P.first;
945
17
      uint64_t Offset = P.second * Config->Wordsize;
946
17
      if (S == nullptr) {
947
6
        if (!Config->Pic)
948
3
          continue;
949
3
        In.RelaDyn->addReloc(Target->TlsModuleIndexRel, this, Offset, S);
950
11
      } else {
951
11
        // When building a shared library we still need a dynamic relocation
952
11
        // for the module index. Therefore only checking for
953
11
        // S->IsPreemptible is not sufficient (this happens e.g. for
954
11
        // thread-locals that have been marked as local through a linker script)
955
11
        if (!S->IsPreemptible && 
!Config->Pic4
)
956
3
          continue;
957
8
        In.RelaDyn->addReloc(Target->TlsModuleIndexRel, this, Offset, S);
958
8
        // However, we can skip writing the TLS offset reloc for non-preemptible
959
8
        // symbols since it is known even in shared libraries
960
8
        if (!S->IsPreemptible)
961
1
          continue;
962
7
        Offset += Config->Wordsize;
963
7
        In.RelaDyn->addReloc(Target->TlsOffsetRel, this, Offset, S);
964
7
      }
965
17
    }
966
57
967
57
    // Do not create dynamic relocations for non-TLS
968
57
    // entries in the primary GOT.
969
57
    if (&Got == PrimGot)
970
54
      continue;
971
3
972
3
    // Dynamic relocations for "global" entries.
973
3
    for (const std::pair<Symbol *, size_t> &P : Got.Global) {
974
2
      uint64_t Offset = P.second * Config->Wordsize;
975
2
      In.RelaDyn->addReloc(Target->RelativeRel, this, Offset, P.first);
976
2
    }
977
3
    if (!Config->Pic)
978
1
      continue;
979
2
    // Dynamic relocations for "local" entries in case of PIC.
980
2
    for (const std::pair<const OutputSection *, FileGot::PageBlock> &L :
981
2
         Got.PagesMap) {
982
1
      size_t PageCount = L.second.Count;
983
7
      for (size_t PI = 0; PI < PageCount; 
++PI6
) {
984
6
        uint64_t Offset = (L.second.FirstIndex + PI) * Config->Wordsize;
985
6
        In.RelaDyn->addReloc({Target->RelativeRel, this, Offset, L.first,
986
6
                              int64_t(PI * 0x10000)});
987
6
      }
988
1
    }
989
2
    for (const std::pair<GotEntry, size_t> &P : Got.Local16) {
990
1
      uint64_t Offset = P.second * Config->Wordsize;
991
1
      In.RelaDyn->addReloc({Target->RelativeRel, this, Offset, true,
992
1
                            P.first.first, P.first.second});
993
1
    }
994
2
  }
995
54
}
void lld::elf::MipsGotSection::build<llvm::object::ELFType<(llvm::support::endianness)1, false> >()
Line
Count
Source
810
23
template <class ELFT> void MipsGotSection::build() {
811
23
  if (Gots.empty())
812
18
    return;
813
5
814
5
  std::vector<FileGot> MergedGots(1);
815
5
816
5
  // For each GOT move non-preemptible symbols from the `Global`
817
5
  // to `Local16` list. Preemptible symbol might become non-preemptible
818
5
  // one if, for example, it gets a related copy relocation.
819
5
  for (FileGot &Got : Gots) {
820
5
    for (auto &P: Got.Global)
821
3
      if (!P.first->IsPreemptible)
822
0
        Got.Local16.insert({{P.first, 0}, 0});
823
5
    Got.Global.remove_if([&](const std::pair<Symbol *, size_t> &P) {
824
5
      return !P.first->IsPreemptible;
825
5
    });
826
5
  }
827
5
828
5
  // For each GOT remove "reloc-only" entry if there is "global"
829
5
  // entry for the same symbol. And add local entries which indexed
830
5
  // using 32-bit value at the end of 16-bit entries.
831
5
  for (FileGot &Got : Gots) {
832
5
    Got.Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
833
5
      return Got.Global.count(P.first);
834
5
    });
835
5
    set_union(Got.Local16, Got.Local32);
836
5
    Got.Local32.clear();
837
5
  }
838
5
839
5
  // Evaluate number of "reloc-only" entries in the resulting GOT.
840
5
  // To do that put all unique "reloc-only" and "global" entries
841
5
  // from all GOTs to the future primary GOT.
842
5
  FileGot *PrimGot = &MergedGots.front();
843
5
  for (FileGot &Got : Gots) {
844
5
    set_union(PrimGot->Relocs, Got.Global);
845
5
    set_union(PrimGot->Relocs, Got.Relocs);
846
5
    Got.Relocs.clear();
847
5
  }
848
5
849
5
  // Evaluate number of "page" entries in each GOT.
850
5
  for (FileGot &Got : Gots) {
851
5
    for (std::pair<const OutputSection *, FileGot::PageBlock> &P :
852
5
         Got.PagesMap) {
853
0
      const OutputSection *OS = P.first;
854
0
      uint64_t SecSize = 0;
855
0
      for (BaseCommand *Cmd : OS->SectionCommands) {
856
0
        if (auto *ISD = dyn_cast<InputSectionDescription>(Cmd))
857
0
          for (InputSection *IS : ISD->Sections) {
858
0
            uint64_t Off = alignTo(SecSize, IS->Alignment);
859
0
            SecSize = Off + IS->getSize();
860
0
          }
861
0
      }
862
0
      P.second.Count = getMipsPageCount(SecSize);
863
0
    }
864
5
  }
865
5
866
5
  // Merge GOTs. Try to join as much as possible GOTs but do not exceed
867
5
  // maximum GOT size. At first, try to fill the primary GOT because
868
5
  // the primary GOT can be accessed in the most effective way. If it
869
5
  // is not possible, try to fill the last GOT in the list, and finally
870
5
  // create a new GOT if both attempts failed.
871
5
  for (FileGot &SrcGot : Gots) {
872
5
    InputFile *File = SrcGot.File;
873
5
    if (tryMergeGots(MergedGots.front(), SrcGot, true)) {
874
5
      File->MipsGotIndex = 0;
875
5
    } else {
876
0
      // If this is the first time we failed to merge with the primary GOT,
877
0
      // MergedGots.back() will also be the primary GOT. We must make sure not
878
0
      // to try to merge again with IsPrimary=false, as otherwise, if the
879
0
      // inputs are just right, we could allow the primary GOT to become 1 or 2
880
0
      // words too big due to ignoring the header size.
881
0
      if (MergedGots.size() == 1 ||
882
0
          !tryMergeGots(MergedGots.back(), SrcGot, false)) {
883
0
        MergedGots.emplace_back();
884
0
        std::swap(MergedGots.back(), SrcGot);
885
0
      }
886
0
      File->MipsGotIndex = MergedGots.size() - 1;
887
0
    }
888
5
  }
889
5
  std::swap(Gots, MergedGots);
890
5
891
5
  // Reduce number of "reloc-only" entries in the primary GOT
892
5
  // by substracting "global" entries exist in the primary GOT.
893
5
  PrimGot = &Gots.front();
894
5
  PrimGot->Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
895
5
    return PrimGot->Global.count(P.first);
896
5
  });
897
5
898
5
  // Calculate indexes for each GOT entry.
899
5
  size_t Index = HeaderEntriesNum;
900
5
  for (FileGot &Got : Gots) {
901
5
    Got.StartIndex = &Got == PrimGot ? 0 : 
Index0
;
902
5
    for (std::pair<const OutputSection *, FileGot::PageBlock> &P :
903
5
         Got.PagesMap) {
904
0
      // For each output section referenced by GOT page relocations calculate
905
0
      // and save into PagesMap an upper bound of MIPS GOT entries required
906
0
      // to store page addresses of local symbols. We assume the worst case -
907
0
      // each 64kb page of the output section has at least one GOT relocation
908
0
      // against it. And take in account the case when the section intersects
909
0
      // page boundaries.
910
0
      P.second.FirstIndex = Index;
911
0
      Index += P.second.Count;
912
0
    }
913
5
    for (auto &P: Got.Local16)
914
2
      P.second = Index++;
915
5
    for (auto &P: Got.Global)
916
3
      P.second = Index++;
917
5
    for (auto &P: Got.Relocs)
918
1
      P.second = Index++;
919
5
    for (auto &P: Got.Tls)
920
0
      P.second = Index++;
921
5
    for (auto &P: Got.DynTlsSymbols) {
922
0
      P.second = Index;
923
0
      Index += 2;
924
0
    }
925
5
  }
926
5
927
5
  // Update Symbol::GotIndex field to use this
928
5
  // value later in the `sortMipsSymbols` function.
929
5
  for (auto &P : PrimGot->Global)
930
3
    P.first->GotIndex = P.second;
931
5
  for (auto &P : PrimGot->Relocs)
932
1
    P.first->GotIndex = P.second;
933
5
934
5
  // Create dynamic relocations.
935
5
  for (FileGot &Got : Gots) {
936
5
    // Create dynamic relocations for TLS entries.
937
5
    for (std::pair<Symbol *, size_t> &P : Got.Tls) {
938
0
      Symbol *S = P.first;
939
0
      uint64_t Offset = P.second * Config->Wordsize;
940
0
      if (S->IsPreemptible)
941
0
        In.RelaDyn->addReloc(Target->TlsGotRel, this, Offset, S);
942
0
    }
943
5
    for (std::pair<Symbol *, size_t> &P : Got.DynTlsSymbols) {
944
0
      Symbol *S = P.first;
945
0
      uint64_t Offset = P.second * Config->Wordsize;
946
0
      if (S == nullptr) {
947
0
        if (!Config->Pic)
948
0
          continue;
949
0
        In.RelaDyn->addReloc(Target->TlsModuleIndexRel, this, Offset, S);
950
0
      } else {
951
0
        // When building a shared library we still need a dynamic relocation
952
0
        // for the module index. Therefore only checking for
953
0
        // S->IsPreemptible is not sufficient (this happens e.g. for
954
0
        // thread-locals that have been marked as local through a linker script)
955
0
        if (!S->IsPreemptible && !Config->Pic)
956
0
          continue;
957
0
        In.RelaDyn->addReloc(Target->TlsModuleIndexRel, this, Offset, S);
958
0
        // However, we can skip writing the TLS offset reloc for non-preemptible
959
0
        // symbols since it is known even in shared libraries
960
0
        if (!S->IsPreemptible)
961
0
          continue;
962
0
        Offset += Config->Wordsize;
963
0
        In.RelaDyn->addReloc(Target->TlsOffsetRel, this, Offset, S);
964
0
      }
965
0
    }
966
5
967
5
    // Do not create dynamic relocations for non-TLS
968
5
    // entries in the primary GOT.
969
5
    if (&Got == PrimGot)
970
5
      continue;
971
0
972
0
    // Dynamic relocations for "global" entries.
973
0
    for (const std::pair<Symbol *, size_t> &P : Got.Global) {
974
0
      uint64_t Offset = P.second * Config->Wordsize;
975
0
      In.RelaDyn->addReloc(Target->RelativeRel, this, Offset, P.first);
976
0
    }
977
0
    if (!Config->Pic)
978
0
      continue;
979
0
    // Dynamic relocations for "local" entries in case of PIC.
980
0
    for (const std::pair<const OutputSection *, FileGot::PageBlock> &L :
981
0
         Got.PagesMap) {
982
0
      size_t PageCount = L.second.Count;
983
0
      for (size_t PI = 0; PI < PageCount; ++PI) {
984
0
        uint64_t Offset = (L.second.FirstIndex + PI) * Config->Wordsize;
985
0
        In.RelaDyn->addReloc({Target->RelativeRel, this, Offset, L.first,
986
0
                              int64_t(PI * 0x10000)});
987
0
      }
988
0
    }
989
0
    for (const std::pair<GotEntry, size_t> &P : Got.Local16) {
990
0
      uint64_t Offset = P.second * Config->Wordsize;
991
0
      In.RelaDyn->addReloc({Target->RelativeRel, this, Offset, true,
992
0
                            P.first.first, P.first.second});
993
0
    }
994
0
  }
995
5
}
void lld::elf::MipsGotSection::build<llvm::object::ELFType<(llvm::support::endianness)0, false> >()
Line
Count
Source
810
118
template <class ELFT> void MipsGotSection::build() {
811
118
  if (Gots.empty())
812
83
    return;
813
35
814
35
  std::vector<FileGot> MergedGots(1);
815
35
816
35
  // For each GOT move non-preemptible symbols from the `Global`
817
35
  // to `Local16` list. Preemptible symbol might become non-preemptible
818
35
  // one if, for example, it gets a related copy relocation.
819
37
  for (FileGot &Got : Gots) {
820
37
    for (auto &P: Got.Global)
821
28
      if (!P.first->IsPreemptible)
822
0
        Got.Local16.insert({{P.first, 0}, 0});
823
37
    Got.Global.remove_if([&](const std::pair<Symbol *, size_t> &P) {
824
37
      return !P.first->IsPreemptible;
825
37
    });
826
37
  }
827
35
828
35
  // For each GOT remove "reloc-only" entry if there is "global"
829
35
  // entry for the same symbol. And add local entries which indexed
830
35
  // using 32-bit value at the end of 16-bit entries.
831
37
  for (FileGot &Got : Gots) {
832
37
    Got.Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
833
37
      return Got.Global.count(P.first);
834
37
    });
835
37
    set_union(Got.Local16, Got.Local32);
836
37
    Got.Local32.clear();
837
37
  }
838
35
839
35
  // Evaluate number of "reloc-only" entries in the resulting GOT.
840
35
  // To do that put all unique "reloc-only" and "global" entries
841
35
  // from all GOTs to the future primary GOT.
842
35
  FileGot *PrimGot = &MergedGots.front();
843
37
  for (FileGot &Got : Gots) {
844
37
    set_union(PrimGot->Relocs, Got.Global);
845
37
    set_union(PrimGot->Relocs, Got.Relocs);
846
37
    Got.Relocs.clear();
847
37
  }
848
35
849
35
  // Evaluate number of "page" entries in each GOT.
850
37
  for (FileGot &Got : Gots) {
851
37
    for (std::pair<const OutputSection *, FileGot::PageBlock> &P :
852
37
         Got.PagesMap) {
853
10
      const OutputSection *OS = P.first;
854
10
      uint64_t SecSize = 0;
855
12
      for (BaseCommand *Cmd : OS->SectionCommands) {
856
12
        if (auto *ISD = dyn_cast<InputSectionDescription>(Cmd))
857
18
          
for (InputSection *IS : ISD->Sections)11
{
858
18
            uint64_t Off = alignTo(SecSize, IS->Alignment);
859
18
            SecSize = Off + IS->getSize();
860
18
          }
861
12
      }
862
10
      P.second.Count = getMipsPageCount(SecSize);
863
10
    }
864
37
  }
865
35
866
35
  // Merge GOTs. Try to join as much as possible GOTs but do not exceed
867
35
  // maximum GOT size. At first, try to fill the primary GOT because
868
35
  // the primary GOT can be accessed in the most effective way. If it
869
35
  // is not possible, try to fill the last GOT in the list, and finally
870
35
  // create a new GOT if both attempts failed.
871
37
  for (FileGot &SrcGot : Gots) {
872
37
    InputFile *File = SrcGot.File;
873
37
    if (tryMergeGots(MergedGots.front(), SrcGot, true)) {
874
35
      File->MipsGotIndex = 0;
875
35
    } else {
876
2
      // If this is the first time we failed to merge with the primary GOT,
877
2
      // MergedGots.back() will also be the primary GOT. We must make sure not
878
2
      // to try to merge again with IsPrimary=false, as otherwise, if the
879
2
      // inputs are just right, we could allow the primary GOT to become 1 or 2
880
2
      // words too big due to ignoring the header size.
881
2
      if (MergedGots.size() == 1 ||
882
2
          
!tryMergeGots(MergedGots.back(), SrcGot, false)1
) {
883
1
        MergedGots.emplace_back();
884
1
        std::swap(MergedGots.back(), SrcGot);
885
1
      }
886
2
      File->MipsGotIndex = MergedGots.size() - 1;
887
2
    }
888
37
  }
889
35
  std::swap(Gots, MergedGots);
890
35
891
35
  // Reduce number of "reloc-only" entries in the primary GOT
892
35
  // by substracting "global" entries exist in the primary GOT.
893
35
  PrimGot = &Gots.front();
894
35
  PrimGot->Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
895
35
    return PrimGot->Global.count(P.first);
896
35
  });
897
35
898
35
  // Calculate indexes for each GOT entry.
899
35
  size_t Index = HeaderEntriesNum;
900
36
  for (FileGot &Got : Gots) {
901
36
    Got.StartIndex = &Got == PrimGot ? 
035
:
Index1
;
902
36
    for (std::pair<const OutputSection *, FileGot::PageBlock> &P :
903
36
         Got.PagesMap) {
904
9
      // For each output section referenced by GOT page relocations calculate
905
9
      // and save into PagesMap an upper bound of MIPS GOT entries required
906
9
      // to store page addresses of local symbols. We assume the worst case -
907
9
      // each 64kb page of the output section has at least one GOT relocation
908
9
      // against it. And take in account the case when the section intersects
909
9
      // page boundaries.
910
9
      P.second.FirstIndex = Index;
911
9
      Index += P.second.Count;
912
9
    }
913
36
    for (auto &P: Got.Local16)
914
16
      P.second = Index++;
915
36
    for (auto &P: Got.Global)
916
27
      P.second = Index++;
917
36
    for (auto &P: Got.Relocs)
918
3
      P.second = Index++;
919
36
    for (auto &P: Got.Tls)
920
8
      P.second = Index++;
921
36
    for (auto &P: Got.DynTlsSymbols) {
922
10
      P.second = Index;
923
10
      Index += 2;
924
10
    }
925
36
  }
926
35
927
35
  // Update Symbol::GotIndex field to use this
928
35
  // value later in the `sortMipsSymbols` function.
929
35
  for (auto &P : PrimGot->Global)
930
25
    P.first->GotIndex = P.second;
931
35
  for (auto &P : PrimGot->Relocs)
932
3
    P.first->GotIndex = P.second;
933
35
934
35
  // Create dynamic relocations.
935
36
  for (FileGot &Got : Gots) {
936
36
    // Create dynamic relocations for TLS entries.
937
36
    for (std::pair<Symbol *, size_t> &P : Got.Tls) {
938
8
      Symbol *S = P.first;
939
8
      uint64_t Offset = P.second * Config->Wordsize;
940
8
      if (S->IsPreemptible)
941
6
        In.RelaDyn->addReloc(Target->TlsGotRel, this, Offset, S);
942
8
    }
943
36
    for (std::pair<Symbol *, size_t> &P : Got.DynTlsSymbols) {
944
10
      Symbol *S = P.first;
945
10
      uint64_t Offset = P.second * Config->Wordsize;
946
10
      if (S == nullptr) {
947
4
        if (!Config->Pic)
948
2
          continue;
949
2
        In.RelaDyn->addReloc(Target->TlsModuleIndexRel, this, Offset, S);
950
6
      } else {
951
6
        // When building a shared library we still need a dynamic relocation
952
6
        // for the module index. Therefore only checking for
953
6
        // S->IsPreemptible is not sufficient (this happens e.g. for
954
6
        // thread-locals that have been marked as local through a linker script)
955
6
        if (!S->IsPreemptible && 
!Config->Pic2
)
956
2
          continue;
957
4
        In.RelaDyn->addReloc(Target->TlsModuleIndexRel, this, Offset, S);
958
4
        // However, we can skip writing the TLS offset reloc for non-preemptible
959
4
        // symbols since it is known even in shared libraries
960
4
        if (!S->IsPreemptible)
961
0
          continue;
962
4
        Offset += Config->Wordsize;
963
4
        In.RelaDyn->addReloc(Target->TlsOffsetRel, this, Offset, S);
964
4
      }
965
10
    }
966
36
967
36
    // Do not create dynamic relocations for non-TLS
968
36
    // entries in the primary GOT.
969
36
    if (&Got == PrimGot)
970
35
      continue;
971
1
972
1
    // Dynamic relocations for "global" entries.
973
2
    
for (const std::pair<Symbol *, size_t> &P : Got.Global)1
{
974
2
      uint64_t Offset = P.second * Config->Wordsize;
975
2
      In.RelaDyn->addReloc(Target->RelativeRel, this, Offset, P.first);
976
2
    }
977
1
    if (!Config->Pic)
978
0
      continue;
979
1
    // Dynamic relocations for "local" entries in case of PIC.
980
1
    for (const std::pair<const OutputSection *, FileGot::PageBlock> &L :
981
1
         Got.PagesMap) {
982
1
      size_t PageCount = L.second.Count;
983
7
      for (size_t PI = 0; PI < PageCount; 
++PI6
) {
984
6
        uint64_t Offset = (L.second.FirstIndex + PI) * Config->Wordsize;
985
6
        In.RelaDyn->addReloc({Target->RelativeRel, this, Offset, L.first,
986
6
                              int64_t(PI * 0x10000)});
987
6
      }
988
1
    }
989
1
    for (const std::pair<GotEntry, size_t> &P : Got.Local16) {
990
0
      uint64_t Offset = P.second * Config->Wordsize;
991
0
      In.RelaDyn->addReloc({Target->RelativeRel, this, Offset, true,
992
0
                            P.first.first, P.first.second});
993
0
    }
994
1
  }
995
35
}
void lld::elf::MipsGotSection::build<llvm::object::ELFType<(llvm::support::endianness)1, true> >()
Line
Count
Source
810
3
template <class ELFT> void MipsGotSection::build() {
811
3
  if (Gots.empty())
812
3
    return;
813
0
814
0
  std::vector<FileGot> MergedGots(1);
815
0
816
0
  // For each GOT move non-preemptible symbols from the `Global`
817
0
  // to `Local16` list. Preemptible symbol might become non-preemptible
818
0
  // one if, for example, it gets a related copy relocation.
819
0
  for (FileGot &Got : Gots) {
820
0
    for (auto &P: Got.Global)
821
0
      if (!P.first->IsPreemptible)
822
0
        Got.Local16.insert({{P.first, 0}, 0});
823
0
    Got.Global.remove_if([&](const std::pair<Symbol *, size_t> &P) {
824
0
      return !P.first->IsPreemptible;
825
0
    });
826
0
  }
827
0
828
0
  // For each GOT remove "reloc-only" entry if there is "global"
829
0
  // entry for the same symbol. And add local entries which indexed
830
0
  // using 32-bit value at the end of 16-bit entries.
831
0
  for (FileGot &Got : Gots) {
832
0
    Got.Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
833
0
      return Got.Global.count(P.first);
834
0
    });
835
0
    set_union(Got.Local16, Got.Local32);
836
0
    Got.Local32.clear();
837
0
  }
838
0
839
0
  // Evaluate number of "reloc-only" entries in the resulting GOT.
840
0
  // To do that put all unique "reloc-only" and "global" entries
841
0
  // from all GOTs to the future primary GOT.
842
0
  FileGot *PrimGot = &MergedGots.front();
843
0
  for (FileGot &Got : Gots) {
844
0
    set_union(PrimGot->Relocs, Got.Global);
845
0
    set_union(PrimGot->Relocs, Got.Relocs);
846
0
    Got.Relocs.clear();
847
0
  }
848
0
849
0
  // Evaluate number of "page" entries in each GOT.
850
0
  for (FileGot &Got : Gots) {
851
0
    for (std::pair<const OutputSection *, FileGot::PageBlock> &P :
852
0
         Got.PagesMap) {
853
0
      const OutputSection *OS = P.first;
854
0
      uint64_t SecSize = 0;
855
0
      for (BaseCommand *Cmd : OS->SectionCommands) {
856
0
        if (auto *ISD = dyn_cast<InputSectionDescription>(Cmd))
857
0
          for (InputSection *IS : ISD->Sections) {
858
0
            uint64_t Off = alignTo(SecSize, IS->Alignment);
859
0
            SecSize = Off + IS->getSize();
860
0
          }
861
0
      }
862
0
      P.second.Count = getMipsPageCount(SecSize);
863
0
    }
864
0
  }
865
0
866
0
  // Merge GOTs. Try to join as much as possible GOTs but do not exceed
867
0
  // maximum GOT size. At first, try to fill the primary GOT because
868
0
  // the primary GOT can be accessed in the most effective way. If it
869
0
  // is not possible, try to fill the last GOT in the list, and finally
870
0
  // create a new GOT if both attempts failed.
871
0
  for (FileGot &SrcGot : Gots) {
872
0
    InputFile *File = SrcGot.File;
873
0
    if (tryMergeGots(MergedGots.front(), SrcGot, true)) {
874
0
      File->MipsGotIndex = 0;
875
0
    } else {
876
0
      // If this is the first time we failed to merge with the primary GOT,
877
0
      // MergedGots.back() will also be the primary GOT. We must make sure not
878
0
      // to try to merge again with IsPrimary=false, as otherwise, if the
879
0
      // inputs are just right, we could allow the primary GOT to become 1 or 2
880
0
      // words too big due to ignoring the header size.
881
0
      if (MergedGots.size() == 1 ||
882
0
          !tryMergeGots(MergedGots.back(), SrcGot, false)) {
883
0
        MergedGots.emplace_back();
884
0
        std::swap(MergedGots.back(), SrcGot);
885
0
      }
886
0
      File->MipsGotIndex = MergedGots.size() - 1;
887
0
    }
888
0
  }
889
0
  std::swap(Gots, MergedGots);
890
0
891
0
  // Reduce number of "reloc-only" entries in the primary GOT
892
0
  // by substracting "global" entries exist in the primary GOT.
893
0
  PrimGot = &Gots.front();
894
0
  PrimGot->Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
895
0
    return PrimGot->Global.count(P.first);
896
0
  });
897
0
898
0
  // Calculate indexes for each GOT entry.
899
0
  size_t Index = HeaderEntriesNum;
900
0
  for (FileGot &Got : Gots) {
901
0
    Got.StartIndex = &Got == PrimGot ? 0 : Index;
902
0
    for (std::pair<const OutputSection *, FileGot::PageBlock> &P :
903
0
         Got.PagesMap) {
904
0
      // For each output section referenced by GOT page relocations calculate
905
0
      // and save into PagesMap an upper bound of MIPS GOT entries required
906
0
      // to store page addresses of local symbols. We assume the worst case -
907
0
      // each 64kb page of the output section has at least one GOT relocation
908
0
      // against it. And take in account the case when the section intersects
909
0
      // page boundaries.
910
0
      P.second.FirstIndex = Index;
911
0
      Index += P.second.Count;
912
0
    }
913
0
    for (auto &P: Got.Local16)
914
0
      P.second = Index++;
915
0
    for (auto &P: Got.Global)
916
0
      P.second = Index++;
917
0
    for (auto &P: Got.Relocs)
918
0
      P.second = Index++;
919
0
    for (auto &P: Got.Tls)
920
0
      P.second = Index++;
921
0
    for (auto &P: Got.DynTlsSymbols) {
922
0
      P.second = Index;
923
0
      Index += 2;
924
0
    }
925
0
  }
926
0
927
0
  // Update Symbol::GotIndex field to use this
928
0
  // value later in the `sortMipsSymbols` function.
929
0
  for (auto &P : PrimGot->Global)
930
0
    P.first->GotIndex = P.second;
931
0
  for (auto &P : PrimGot->Relocs)
932
0
    P.first->GotIndex = P.second;
933
0
934
0
  // Create dynamic relocations.
935
0
  for (FileGot &Got : Gots) {
936
0
    // Create dynamic relocations for TLS entries.
937
0
    for (std::pair<Symbol *, size_t> &P : Got.Tls) {
938
0
      Symbol *S = P.first;
939
0
      uint64_t Offset = P.second * Config->Wordsize;
940
0
      if (S->IsPreemptible)
941
0
        In.RelaDyn->addReloc(Target->TlsGotRel, this, Offset, S);
942
0
    }
943
0
    for (std::pair<Symbol *, size_t> &P : Got.DynTlsSymbols) {
944
0
      Symbol *S = P.first;
945
0
      uint64_t Offset = P.second * Config->Wordsize;
946
0
      if (S == nullptr) {
947
0
        if (!Config->Pic)
948
0
          continue;
949
0
        In.RelaDyn->addReloc(Target->TlsModuleIndexRel, this, Offset, S);
950
0
      } else {
951
0
        // When building a shared library we still need a dynamic relocation
952
0
        // for the module index. Therefore only checking for
953
0
        // S->IsPreemptible is not sufficient (this happens e.g. for
954
0
        // thread-locals that have been marked as local through a linker script)
955
0
        if (!S->IsPreemptible && !Config->Pic)
956
0
          continue;
957
0
        In.RelaDyn->addReloc(Target->TlsModuleIndexRel, this, Offset, S);
958
0
        // However, we can skip writing the TLS offset reloc for non-preemptible
959
0
        // symbols since it is known even in shared libraries
960
0
        if (!S->IsPreemptible)
961
0
          continue;
962
0
        Offset += Config->Wordsize;
963
0
        In.RelaDyn->addReloc(Target->TlsOffsetRel, this, Offset, S);
964
0
      }
965
0
    }
966
0
967
0
    // Do not create dynamic relocations for non-TLS
968
0
    // entries in the primary GOT.
969
0
    if (&Got == PrimGot)
970
0
      continue;
971
0
972
0
    // Dynamic relocations for "global" entries.
973
0
    for (const std::pair<Symbol *, size_t> &P : Got.Global) {
974
0
      uint64_t Offset = P.second * Config->Wordsize;
975
0
      In.RelaDyn->addReloc(Target->RelativeRel, this, Offset, P.first);
976
0
    }
977
0
    if (!Config->Pic)
978
0
      continue;
979
0
    // Dynamic relocations for "local" entries in case of PIC.
980
0
    for (const std::pair<const OutputSection *, FileGot::PageBlock> &L :
981
0
         Got.PagesMap) {
982
0
      size_t PageCount = L.second.Count;
983
0
      for (size_t PI = 0; PI < PageCount; ++PI) {
984
0
        uint64_t Offset = (L.second.FirstIndex + PI) * Config->Wordsize;
985
0
        In.RelaDyn->addReloc({Target->RelativeRel, this, Offset, L.first,
986
0
                              int64_t(PI * 0x10000)});
987
0
      }
988
0
    }
989
0
    for (const std::pair<GotEntry, size_t> &P : Got.Local16) {
990
0
      uint64_t Offset = P.second * Config->Wordsize;
991
0
      In.RelaDyn->addReloc({Target->RelativeRel, this, Offset, true,
992
0
                            P.first.first, P.first.second});
993
0
    }
994
0
  }
995
0
}
void lld::elf::MipsGotSection::build<llvm::object::ELFType<(llvm::support::endianness)0, true> >()
Line
Count
Source
810
38
template <class ELFT> void MipsGotSection::build() {
811
38
  if (Gots.empty())
812
24
    return;
813
14
814
14
  std::vector<FileGot> MergedGots(1);
815
14
816
14
  // For each GOT move non-preemptible symbols from the `Global`
817
14
  // to `Local16` list. Preemptible symbol might become non-preemptible
818
14
  // one if, for example, it gets a related copy relocation.
819
16
  for (FileGot &Got : Gots) {
820
16
    for (auto &P: Got.Global)
821
4
      if (!P.first->IsPreemptible)
822
0
        Got.Local16.insert({{P.first, 0}, 0});
823
16
    Got.Global.remove_if([&](const std::pair<Symbol *, size_t> &P) {
824
16
      return !P.first->IsPreemptible;
825
16
    });
826
16
  }
827
14
828
14
  // For each GOT remove "reloc-only" entry if there is "global"
829
14
  // entry for the same symbol. And add local entries which indexed
830
14
  // using 32-bit value at the end of 16-bit entries.
831
16
  for (FileGot &Got : Gots) {
832
16
    Got.Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
833
16
      return Got.Global.count(P.first);
834
16
    });
835
16
    set_union(Got.Local16, Got.Local32);
836
16
    Got.Local32.clear();
837
16
  }
838
14
839
14
  // Evaluate number of "reloc-only" entries in the resulting GOT.
840
14
  // To do that put all unique "reloc-only" and "global" entries
841
14
  // from all GOTs to the future primary GOT.
842
14
  FileGot *PrimGot = &MergedGots.front();
843
16
  for (FileGot &Got : Gots) {
844
16
    set_union(PrimGot->Relocs, Got.Global);
845
16
    set_union(PrimGot->Relocs, Got.Relocs);
846
16
    Got.Relocs.clear();
847
16
  }
848
14
849
14
  // Evaluate number of "page" entries in each GOT.
850
16
  for (FileGot &Got : Gots) {
851
16
    for (std::pair<const OutputSection *, FileGot::PageBlock> &P :
852
16
         Got.PagesMap) {
853
4
      const OutputSection *OS = P.first;
854
4
      uint64_t SecSize = 0;
855
4
      for (BaseCommand *Cmd : OS->SectionCommands) {
856
4
        if (auto *ISD = dyn_cast<InputSectionDescription>(Cmd))
857
6
          
for (InputSection *IS : ISD->Sections)4
{
858
6
            uint64_t Off = alignTo(SecSize, IS->Alignment);
859
6
            SecSize = Off + IS->getSize();
860
6
          }
861
4
      }
862
4
      P.second.Count = getMipsPageCount(SecSize);
863
4
    }
864
16
  }
865
14
866
14
  // Merge GOTs. Try to join as much as possible GOTs but do not exceed
867
14
  // maximum GOT size. At first, try to fill the primary GOT because
868
14
  // the primary GOT can be accessed in the most effective way. If it
869
14
  // is not possible, try to fill the last GOT in the list, and finally
870
14
  // create a new GOT if both attempts failed.
871
16
  for (FileGot &SrcGot : Gots) {
872
16
    InputFile *File = SrcGot.File;
873
16
    if (tryMergeGots(MergedGots.front(), SrcGot, true)) {
874
14
      File->MipsGotIndex = 0;
875
14
    } else {
876
2
      // If this is the first time we failed to merge with the primary GOT,
877
2
      // MergedGots.back() will also be the primary GOT. We must make sure not
878
2
      // to try to merge again with IsPrimary=false, as otherwise, if the
879
2
      // inputs are just right, we could allow the primary GOT to become 1 or 2
880
2
      // words too big due to ignoring the header size.
881
2
      if (MergedGots.size() == 1 ||
882
2
          
!tryMergeGots(MergedGots.back(), SrcGot, false)0
) {
883
2
        MergedGots.emplace_back();
884
2
        std::swap(MergedGots.back(), SrcGot);
885
2
      }
886
2
      File->MipsGotIndex = MergedGots.size() - 1;
887
2
    }
888
16
  }
889
14
  std::swap(Gots, MergedGots);
890
14
891
14
  // Reduce number of "reloc-only" entries in the primary GOT
892
14
  // by substracting "global" entries exist in the primary GOT.
893
14
  PrimGot = &Gots.front();
894
14
  PrimGot->Relocs.remove_if([&](const std::pair<Symbol *, size_t> &P) {
895
14
    return PrimGot->Global.count(P.first);
896
14
  });
897
14
898
14
  // Calculate indexes for each GOT entry.
899
14
  size_t Index = HeaderEntriesNum;
900
16
  for (FileGot &Got : Gots) {
901
16
    Got.StartIndex = &Got == PrimGot ? 
014
:
Index2
;
902
16
    for (std::pair<const OutputSection *, FileGot::PageBlock> &P :
903
16
         Got.PagesMap) {
904
4
      // For each output section referenced by GOT page relocations calculate
905
4
      // and save into PagesMap an upper bound of MIPS GOT entries required
906
4
      // to store page addresses of local symbols. We assume the worst case -
907
4
      // each 64kb page of the output section has at least one GOT relocation
908
4
      // against it. And take in account the case when the section intersects
909
4
      // page boundaries.
910
4
      P.second.FirstIndex = Index;
911
4
      Index += P.second.Count;
912
4
    }
913
16
    for (auto &P: Got.Local16)
914
10.0k
      P.second = Index++;
915
16
    for (auto &P: Got.Global)
916
4
      P.second = Index++;
917
16
    for (auto &P: Got.Relocs)
918
2
      P.second = Index++;
919
16
    for (auto &P: Got.Tls)
920
4
      P.second = Index++;
921
16
    for (auto &P: Got.DynTlsSymbols) {
922
7
      P.second = Index;
923
7
      Index += 2;
924
7
    }
925
16
  }
926
14
927
14
  // Update Symbol::GotIndex field to use this
928
14
  // value later in the `sortMipsSymbols` function.
929
14
  for (auto &P : PrimGot->Global)
930
4
    P.first->GotIndex = P.second;
931
14
  for (auto &P : PrimGot->Relocs)
932
2
    P.first->GotIndex = P.second;
933
14
934
14
  // Create dynamic relocations.
935
16
  for (FileGot &Got : Gots) {
936
16
    // Create dynamic relocations for TLS entries.
937
16
    for (std::pair<Symbol *, size_t> &P : Got.Tls) {
938
4
      Symbol *S = P.first;
939
4
      uint64_t Offset = P.second * Config->Wordsize;
940
4
      if (S->IsPreemptible)
941
3
        In.RelaDyn->addReloc(Target->TlsGotRel, this, Offset, S);
942
4
    }
943
16
    for (std::pair<Symbol *, size_t> &P : Got.DynTlsSymbols) {
944
7
      Symbol *S = P.first;
945
7
      uint64_t Offset = P.second * Config->Wordsize;
946
7
      if (S == nullptr) {
947
2
        if (!Config->Pic)
948
1
          continue;
949
1
        In.RelaDyn->addReloc(Target->TlsModuleIndexRel, this, Offset, S);
950
5
      } else {
951
5
        // When building a shared library we still need a dynamic relocation
952
5
        // for the module index. Therefore only checking for
953
5
        // S->IsPreemptible is not sufficient (this happens e.g. for
954
5
        // thread-locals that have been marked as local through a linker script)
955
5
        if (!S->IsPreemptible && 
!Config->Pic2
)
956
1
          continue;
957
4
        In.RelaDyn->addReloc(Target->TlsModuleIndexRel, this, Offset, S);
958
4
        // However, we can skip writing the TLS offset reloc for non-preemptible
959
4
        // symbols since it is known even in shared libraries
960
4
        if (!S->IsPreemptible)
961
1
          continue;
962
3
        Offset += Config->Wordsize;
963
3
        In.RelaDyn->addReloc(Target->TlsOffsetRel, this, Offset, S);
964
3
      }
965
7
    }
966
16
967
16
    // Do not create dynamic relocations for non-TLS
968
16
    // entries in the primary GOT.
969
16
    if (&Got == PrimGot)
970
14
      continue;
971
2
972
2
    // Dynamic relocations for "global" entries.
973
2
    for (const std::pair<Symbol *, size_t> &P : Got.Global) {
974
0
      uint64_t Offset = P.second * Config->Wordsize;
975
0
      In.RelaDyn->addReloc(Target->RelativeRel, this, Offset, P.first);
976
0
    }
977
2
    if (!Config->Pic)
978
1
      continue;
979
1
    // Dynamic relocations for "local" entries in case of PIC.
980
1
    for (const std::pair<const OutputSection *, FileGot::PageBlock> &L :
981
1
         Got.PagesMap) {
982
0
      size_t PageCount = L.second.Count;
983
0
      for (size_t PI = 0; PI < PageCount; ++PI) {
984
0
        uint64_t Offset = (L.second.FirstIndex + PI) * Config->Wordsize;
985
0
        In.RelaDyn->addReloc({Target->RelativeRel, this, Offset, L.first,
986
0
                              int64_t(PI * 0x10000)});
987
0
      }
988
0
    }
989
1
    for (const std::pair<GotEntry, size_t> &P : Got.Local16) {
990
1
      uint64_t Offset = P.second * Config->Wordsize;
991
1
      In.RelaDyn->addReloc({Target->RelativeRel, this, Offset, true,
992
1
                            P.first.first, P.first.second});
993
1
    }
994
1
  }
995
14
}
996
997
364
bool MipsGotSection::empty() const {
998
364
  // We add the .got section to the result for dynamic MIPS target because
999
364
  // its address and properties are mentioned in the .dynamic section.
1000
364
  return Config->Relocatable;
1001
364
}
1002
1003
10.3k
uint64_t MipsGotSection::getGp(const InputFile *F) const {
1004
10.3k
  // For files without related GOT or files refer a primary GOT
1005
10.3k
  // returns "common" _gp value. For secondary GOTs calculate
1006
10.3k
  // individual _gp values.
1007
10.3k
  if (!F || 
!F->MipsGotIndex.hasValue()10.1k
||
*F->MipsGotIndex == 010.1k
)
1008
332
    return ElfSym::MipsGp->getVA(0);
1009
10.0k
  return getVA() + Gots[*F->MipsGotIndex].StartIndex * Config->Wordsize +
1010
10.0k
         0x7ff0;
1011
10.0k
}
1012
1013
169
void MipsGotSection::writeTo(uint8_t *Buf) {
1014
169
  // Set the MSB of the second GOT slot. This is not required by any
1015
169
  // MIPS ABI documentation, though.
1016
169
  //
1017
169
  // There is a comment in glibc saying that "The MSB of got[1] of a
1018
169
  // gnu object is set to identify gnu objects," and in GNU gold it
1019
169
  // says "the second entry will be used by some runtime loaders".
1020
169
  // But how this field is being used is unclear.
1021
169
  //
1022
169
  // We are not really willing to mimic other linkers behaviors
1023
169
  // without understanding why they do that, but because all files
1024
169
  // generated by GNU tools have this special GOT value, and because
1025
169
  // we've been doing this for years, it is probably a safe bet to
1026
169
  // keep doing this for now. We really need to revisit this to see
1027
169
  // if we had to do this.
1028
169
  writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1));
1029
169
  for (const FileGot &G : Gots) {
1030
10.1k
    auto Write = [&](size_t I, const Symbol *S, int64_t A) {
1031
10.1k
      uint64_t VA = A;
1032
10.1k
      if (S) {
1033
10.0k
        VA = S->getVA(A);
1034
10.0k
        if (S->StOther & STO_MIPS_MICROMIPS)
1035
3
          VA |= 1;
1036
10.0k
      }
1037
10.1k
      writeUint(Buf + I * Config->Wordsize, VA);
1038
10.1k
    };
1039
57
    // Write 'page address' entries to the local part of the GOT.
1040
57
    for (const std::pair<const OutputSection *, FileGot::PageBlock> &L :
1041
57
         G.PagesMap) {
1042
13
      size_t PageCount = L.second.Count;
1043
13
      uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
1044
49
      for (size_t PI = 0; PI < PageCount; 
++PI36
)
1045
36
        Write(L.second.FirstIndex + PI, nullptr, FirstPageAddr + PI * 0x10000);
1046
13
    }
1047
57
    // Local, global, TLS, reloc-only  entries.
1048
57
    // If TLS entry has a corresponding dynamic relocations, leave it
1049
57
    // initialized by zero. Write down adjusted TLS symbol's values otherwise.
1050
57
    // To calculate the adjustments use offsets for thread-local storage.
1051
57
    // https://www.linux-mips.org/wiki/NPTL
1052
57
    for (const std::pair<GotEntry, size_t> &P : G.Local16)
1053
10.0k
      Write(P.second, P.first.first, P.first.second);
1054
57
    // Write VA to the primary GOT only. For secondary GOTs that
1055
57
    // will be done by REL32 dynamic relocations.
1056
57
    if (&G == &Gots.front())
1057
54
      for (const std::pair<const Symbol *, size_t> &P : G.Global)
1058
32
        Write(P.second, P.first, 0);
1059
57
    for (const std::pair<Symbol *, size_t> &P : G.Relocs)
1060
6
      Write(P.second, P.first, 0);
1061
57
    for (const std::pair<Symbol *, size_t> &P : G.Tls)
1062
12
      Write(P.second, P.first, P.first->IsPreemptible ? 
09
:
-0x70003
);
1063
57
    for (const std::pair<Symbol *, size_t> &P : G.DynTlsSymbols) {
1064
17
      if (P.first == nullptr && 
!Config->Pic6
)
1065
3
        Write(P.second, nullptr, 1);
1066
14
      else if (P.first && 
!P.first->IsPreemptible11
) {
1067
4
        // If we are emitting PIC code with relocations we mustn't write
1068
4
        // anything to the GOT here. When using Elf_Rel relocations the value
1069
4
        // one will be treated as an addend and will cause crashes at runtime
1070
4
        if (!Config->Pic)
1071
3
          Write(P.second, nullptr, 1);
1072
4
        Write(P.second + 1, P.first, -0x8000);
1073
4
      }
1074
17
    }
1075
57
  }
1076
169
}
1077
1078
// On PowerPC the .plt section is used to hold the table of function addresses
1079
// instead of the .got.plt, and the type is SHT_NOBITS similar to a .bss
1080
// section. I don't know why we have a BSS style type for the section but it is
1081
// consitent across both 64-bit PowerPC ABIs as well as the 32-bit PowerPC ABI.
1082
GotPltSection::GotPltSection()
1083
    : SyntheticSection(SHF_ALLOC | SHF_WRITE,
1084
                       Config->EMachine == EM_PPC64 ? SHT_NOBITS : SHT_PROGBITS,
1085
                       Target->GotPltEntrySize,
1086
2.40k
                       Config->EMachine == EM_PPC64 ? ".plt" : ".got.plt") {}
1087
1088
314
void GotPltSection::addEntry(Symbol &Sym) {
1089
314
  assert(Sym.PltIndex == Entries.size());
1090
314
  Entries.push_back(&Sym);
1091
314
}
1092
1093
734
size_t GotPltSection::getSize() const {
1094
734
  return (Target->GotPltHeaderEntriesNum + Entries.size()) *
1095
734
         Target->GotPltEntrySize;
1096
734
}
1097
1098
223
void GotPltSection::writeTo(uint8_t *Buf) {
1099
223
  Target->writeGotPltHeader(Buf);
1100
223
  Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
1101
282
  for (const Symbol *B : Entries) {
1102
282
    Target->writeGotPlt(Buf, *B);
1103
282
    Buf += Config->Wordsize;
1104
282
  }
1105
223
}
1106
1107
4.59k
bool GotPltSection::empty() const {
1108
4.59k
  // We need to emit a GOT.PLT even if it's empty if there's a symbol that
1109
4.59k
  // references the _GLOBAL_OFFSET_TABLE_ and the Target defines the symbol
1110
4.59k
  // relative to the .got.plt section.
1111
4.59k
  return Entries.empty() &&
1112
4.59k
         
!(4.13k
ElfSym::GlobalOffsetTable4.13k
&&
Target->GotBaseSymInGotPlt176
);
1113
4.59k
}
1114
1115
2.40k
static StringRef getIgotPltName() {
1116
2.40k
  // On ARM the IgotPltSection is part of the GotSection.
1117
2.40k
  if (Config->EMachine == EM_ARM)
1118
148
    return ".got";
1119
2.25k
1120
2.25k
  // On PowerPC64 the GotPltSection is renamed to '.plt' so the IgotPltSection
1121
2.25k
  // needs to be named the same.
1122
2.25k
  if (Config->EMachine == EM_PPC64)
1123
142
    return ".plt";
1124
2.11k
1125
2.11k
  return ".got.plt";
1126
2.11k
}
1127
1128
// On PowerPC64 the GotPltSection type is SHT_NOBITS so we have to follow suit
1129
// with the IgotPltSection.
1130
IgotPltSection::IgotPltSection()
1131
    : SyntheticSection(SHF_ALLOC | SHF_WRITE,
1132
                       Config->EMachine == EM_PPC64 ? SHT_NOBITS : SHT_PROGBITS,
1133
2.40k
                       Target->GotPltEntrySize, getIgotPltName()) {}
1134
1135
41
void IgotPltSection::addEntry(Symbol &Sym) {
1136
41
  Sym.IsInIgot = true;
1137
41
  assert(Sym.PltIndex == Entries.size());
1138
41
  Entries.push_back(&Sym);
1139
41
}
1140
1141
87
size_t IgotPltSection::getSize() const {
1142
87
  return Entries.size() * Target->GotPltEntrySize;
1143
87
}
1144
1145
26
void IgotPltSection::writeTo(uint8_t *Buf) {
1146
39
  for (const Symbol *B : Entries) {
1147
39
    Target->writeIgotPlt(Buf, *B);
1148
39
    Buf += Config->Wordsize;
1149
39
  }
1150
26
}
1151
1152
StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
1153
    : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
1154
7.21k
      Dynamic(Dynamic) {
1155
7.21k
  // ELF string tables start with a NUL byte.
1156
7.21k
  addString("");
1157
7.21k
}
1158
1159
// Adds a string to the string table. If HashIt is true we hash and check for
1160
// duplicates. It is optional because the name of global symbols are already
1161
// uniqued and hashing them again has a big cost for a small value: uniquing
1162
// them with some other string that happens to be the same.
1163
444k
unsigned StringTableSection::addString(StringRef S, bool HashIt) {
1164
444k
  if (HashIt) {
1165
425k
    auto R = StringMap.insert(std::make_pair(S, this->Size));
1166
425k
    if (!R.second)
1167
66.0k
      return R.first->second;
1168
378k
  }
1169
378k
  unsigned Ret = this->Size;
1170
378k
  this->Size = this->Size + S.size() + 1;
1171
378k
  Strings.push_back(S);
1172
378k
  return Ret;
1173
378k
}
1174
1175
5.63k
void StringTableSection::writeTo(uint8_t *Buf) {
1176
376k
  for (StringRef S : Strings) {
1177
376k
    memcpy(Buf, S.data(), S.size());
1178
376k
    Buf[S.size()] = '\0';
1179
376k
    Buf += S.size() + 1;
1180
376k
  }
1181
5.63k
}
1182
1183
// Returns the number of version definition entries. Because the first entry
1184
// is for the version definition itself, it is the number of versioned symbols
1185
// plus one. Note that we don't support multiple versions yet.
1186
1.40k
static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
1187
1188
template <class ELFT>
1189
DynamicSection<ELFT>::DynamicSection()
1190
    : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize,
1191
2.40k
                       ".dynamic") {
1192
2.40k
  this->Entsize = ELFT::Is64Bits ? 
161.98k
:
8426
;
1193
2.40k
1194
2.40k
  // .dynamic section is not writable on MIPS and on Fuchsia OS
1195
2.40k
  // which passes -z rodynamic.
1196
2.40k
  // See "Special Section" in Chapter 4 in the following document:
1197
2.40k
  // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1198
2.40k
  if (Config->EMachine == EM_MIPS || 
Config->ZRodynamic2.21k
)
1199
195
    this->Flags = SHF_ALLOC;
1200
2.40k
1201
2.40k
  // Add strings to .dynstr early so that .dynstr's size will be
1202
2.40k
  // fixed early.
1203
2.40k
  for (StringRef S : Config->FilterList)
1204
6
    addInt(DT_FILTER, In.DynStrTab->addString(S));
1205
2.40k
  for (StringRef S : Config->AuxiliaryList)
1206
4
    addInt(DT_AUXILIARY, In.DynStrTab->addString(S));
1207
2.40k
1208
2.40k
  if (!Config->Rpath.empty())
1209
8
    addInt(Config->EnableNewDtags ? 
DT_RUNPATH7
:
DT_RPATH1
,
1210
8
           In.DynStrTab->addString(Config->Rpath));
1211
2.40k
1212
2.40k
  for (InputFile *File : SharedFiles) {
1213
351
    SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File);
1214
351
    if (F->IsNeeded)
1215
334
      addInt(DT_NEEDED, In.DynStrTab->addString(F->SoName));
1216
351
  }
1217
2.40k
  if (!Config->SoName.empty())
1218
32
    addInt(DT_SONAME, In.DynStrTab->addString(Config->SoName));
1219
2.40k
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::DynamicSection()
Line
Count
Source
1191
302
                       ".dynamic") {
1192
302
  this->Entsize = ELFT::Is64Bits ? 
160
: 8;
1193
302
1194
302
  // .dynamic section is not writable on MIPS and on Fuchsia OS
1195
302
  // which passes -z rodynamic.
1196
302
  // See "Special Section" in Chapter 4 in the following document:
1197
302
  // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1198
302
  if (Config->EMachine == EM_MIPS || 
Config->ZRodynamic279
)
1199
23
    this->Flags = SHF_ALLOC;
1200
302
1201
302
  // Add strings to .dynstr early so that .dynstr's size will be
1202
302
  // fixed early.
1203
302
  for (StringRef S : Config->FilterList)
1204
0
    addInt(DT_FILTER, In.DynStrTab->addString(S));
1205
302
  for (StringRef S : Config->AuxiliaryList)
1206
0
    addInt(DT_AUXILIARY, In.DynStrTab->addString(S));
1207
302
1208
302
  if (!Config->Rpath.empty())
1209
2
    addInt(Config->EnableNewDtags ? DT_RUNPATH : 
DT_RPATH0
,
1210
2
           In.DynStrTab->addString(Config->Rpath));
1211
302
1212
302
  for (InputFile *File : SharedFiles) {
1213
55
    SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File);
1214
55
    if (F->IsNeeded)
1215
49
      addInt(DT_NEEDED, In.DynStrTab->addString(F->SoName));
1216
55
  }
1217
302
  if (!Config->SoName.empty())
1218
6
    addInt(DT_SONAME, In.DynStrTab->addString(Config->SoName));
1219
302
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::DynamicSection()
Line
Count
Source
1191
124
                       ".dynamic") {
1192
124
  this->Entsize = ELFT::Is64Bits ? 
160
: 8;
1193
124
1194
124
  // .dynamic section is not writable on MIPS and on Fuchsia OS
1195
124
  // which passes -z rodynamic.
1196
124
  // See "Special Section" in Chapter 4 in the following document:
1197
124
  // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1198
124
  if (Config->EMachine == EM_MIPS || 
Config->ZRodynamic3
)
1199
121
    this->Flags = SHF_ALLOC;
1200
124
1201
124
  // Add strings to .dynstr early so that .dynstr's size will be
1202
124
  // fixed early.
1203
124
  for (StringRef S : Config->FilterList)
1204
0
    addInt(DT_FILTER, In.DynStrTab->addString(S));
1205
124
  for (StringRef S : Config->AuxiliaryList)
1206
0
    addInt(DT_AUXILIARY, In.DynStrTab->addString(S));
1207
124
1208
124
  if (!Config->Rpath.empty())
1209
0
    addInt(Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
1210
0
           In.DynStrTab->addString(Config->Rpath));
1211
124
1212
124
  for (InputFile *File : SharedFiles) {
1213
24
    SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File);
1214
24
    if (F->IsNeeded)
1215
24
      addInt(DT_NEEDED, In.DynStrTab->addString(F->SoName));
1216
24
  }
1217
124
  if (!Config->SoName.empty())
1218
0
    addInt(DT_SONAME, In.DynStrTab->addString(Config->SoName));
1219
124
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::DynamicSection()
Line
Count
Source
1191
1.87k
                       ".dynamic") {
1192
1.87k
  this->Entsize = ELFT::Is64Bits ? 16 : 
80
;
1193
1.87k
1194
1.87k
  // .dynamic section is not writable on MIPS and on Fuchsia OS
1195
1.87k
  // which passes -z rodynamic.
1196
1.87k
  // See "Special Section" in Chapter 4 in the following document:
1197
1.87k
  // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1198
1.87k
  if (Config->EMachine == EM_MIPS || 
Config->ZRodynamic1.86k
)
1199
6
    this->Flags = SHF_ALLOC;
1200
1.87k
1201
1.87k
  // Add strings to .dynstr early so that .dynstr's size will be
1202
1.87k
  // fixed early.
1203
1.87k
  for (StringRef S : Config->FilterList)
1204
6
    addInt(DT_FILTER, In.DynStrTab->addString(S));
1205
1.87k
  for (StringRef S : Config->AuxiliaryList)
1206
4
    addInt(DT_AUXILIARY, In.DynStrTab->addString(S));
1207
1.87k
1208
1.87k
  if (!Config->Rpath.empty())
1209
5
    addInt(Config->EnableNewDtags ? 
DT_RUNPATH4
:
DT_RPATH1
,
1210
5
           In.DynStrTab->addString(Config->Rpath));
1211
1.87k
1212
1.87k
  for (InputFile *File : SharedFiles) {
1213
255
    SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File);
1214
255
    if (F->IsNeeded)
1215
244
      addInt(DT_NEEDED, In.DynStrTab->addString(F->SoName));
1216
255
  }
1217
1.87k
  if (!Config->SoName.empty())
1218
26
    addInt(DT_SONAME, In.DynStrTab->addString(Config->SoName));
1219
1.87k
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::DynamicSection()
Line
Count
Source
1191
111
                       ".dynamic") {
1192
111
  this->Entsize = ELFT::Is64Bits ? 16 : 
80
;
1193
111
1194
111
  // .dynamic section is not writable on MIPS and on Fuchsia OS
1195
111
  // which passes -z rodynamic.
1196
111
  // See "Special Section" in Chapter 4 in the following document:
1197
111
  // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1198
111
  if (Config->EMachine == EM_MIPS || 
Config->ZRodynamic66
)
1199
45
    this->Flags = SHF_ALLOC;
1200
111
1201
111
  // Add strings to .dynstr early so that .dynstr's size will be
1202
111
  // fixed early.
1203
111
  for (StringRef S : Config->FilterList)
1204
0
    addInt(DT_FILTER, In.DynStrTab->addString(S));
1205
111
  for (StringRef S : Config->AuxiliaryList)
1206
0
    addInt(DT_AUXILIARY, In.DynStrTab->addString(S));
1207
111
1208
111
  if (!Config->Rpath.empty())
1209
1
    addInt(Config->EnableNewDtags ? DT_RUNPATH : 
DT_RPATH0
,
1210
1
           In.DynStrTab->addString(Config->Rpath));
1211
111
1212
111
  for (InputFile *File : SharedFiles) {
1213
17
    SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File);
1214
17
    if (F->IsNeeded)
1215
17
      addInt(DT_NEEDED, In.DynStrTab->addString(F->SoName));
1216
17
  }
1217
111
  if (!Config->SoName.empty())
1218
0
    addInt(DT_SONAME, In.DynStrTab->addString(Config->SoName));
1219
111
}
1220
1221
template <class ELFT>
1222
100
void DynamicSection<ELFT>::add(int32_t Tag, std::function<uint64_t()> Fn) {
1223
100
  Entries.push_back({Tag, Fn});
1224
100
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::add(int, std::__1::function<unsigned long long ()>)
Line
Count
Source
1222
8
void DynamicSection<ELFT>::add(int32_t Tag, std::function<uint64_t()> Fn) {
1223
8
  Entries.push_back({Tag, Fn});
1224
8
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::add(int, std::__1::function<unsigned long long ()>)
Line
Count
Source
1222
69
void DynamicSection<ELFT>::add(int32_t Tag, std::function<uint64_t()> Fn) {
1223
69
  Entries.push_back({Tag, Fn});
1224
69
}
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::add(int, std::__1::function<unsigned long long ()>)
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::add(int, std::__1::function<unsigned long long ()>)
Line
Count
Source
1222
23
void DynamicSection<ELFT>::add(int32_t Tag, std::function<uint64_t()> Fn) {
1223
23
  Entries.push_back({Tag, Fn});
1224
23
}
1225
1226
template <class ELFT>
1227
5.18k
void DynamicSection<ELFT>::addInt(int32_t Tag, uint64_t Val) {
1228
5.18k
  Entries.push_back({Tag, [=] 
{ return Val; }5.12k
});
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addInt(int, unsigned long long)::'lambda'()::operator()() const
Line
Count
Source
1228
687
  Entries.push_back({Tag, [=] { return Val; }});
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addInt(int, unsigned long long)::'lambda'()::operator()() const
Line
Count
Source
1228
624
  Entries.push_back({Tag, [=] { return Val; }});
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addInt(int, unsigned long long)::'lambda'()::operator()() const
Line
Count
Source
1228
3.45k
  Entries.push_back({Tag, [=] { return Val; }});
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addInt(int, unsigned long long)::'lambda'()::operator()() const
Line
Count
Source
1228
358
  Entries.push_back({Tag, [=] { return Val; }});
1229
5.18k
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addInt(int, unsigned long long)
Line
Count
Source
1227
688
void DynamicSection<ELFT>::addInt(int32_t Tag, uint64_t Val) {
1228
688
  Entries.push_back({Tag, [=] { return Val; }});
1229
688
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addInt(int, unsigned long long)
Line
Count
Source
1227
624
void DynamicSection<ELFT>::addInt(int32_t Tag, uint64_t Val) {
1228
624
  Entries.push_back({Tag, [=] { return Val; }});
1229
624
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addInt(int, unsigned long long)
Line
Count
Source
1227
3.51k
void DynamicSection<ELFT>::addInt(int32_t Tag, uint64_t Val) {
1228
3.51k
  Entries.push_back({Tag, [=] { return Val; }});
1229
3.51k
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addInt(int, unsigned long long)
Line
Count
Source
1227
358
void DynamicSection<ELFT>::addInt(int32_t Tag, uint64_t Val) {
1228
358
  Entries.push_back({Tag, [=] { return Val; }});
1229
358
}
1230
1231
template <class ELFT>
1232
5.21k
void DynamicSection<ELFT>::addInSec(int32_t Tag, InputSection *Sec) {
1233
5.21k
  Entries.push_back({Tag, [=] 
{ return Sec->getVA(0); }5.17k
});
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addInSec(int, lld::elf::InputSection*)::'lambda'()::operator()() const
Line
Count
Source
1233
681
  Entries.push_back({Tag, [=] { return Sec->getVA(0); }});
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addInSec(int, lld::elf::InputSection*)::'lambda'()::operator()() const
Line
Count
Source
1233
334
  Entries.push_back({Tag, [=] { return Sec->getVA(0); }});
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addInSec(int, lld::elf::InputSection*)::'lambda'()::operator()() const
Line
Count
Source
1233
3.87k
  Entries.push_back({Tag, [=] { return Sec->getVA(0); }});
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addInSec(int, lld::elf::InputSection*)::'lambda'()::operator()() const
Line
Count
Source
1233
279
  Entries.push_back({Tag, [=] { return Sec->getVA(0); }});
1234
5.21k
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addInSec(int, lld::elf::InputSection*)
Line
Count
Source
1232
681
void DynamicSection<ELFT>::addInSec(int32_t Tag, InputSection *Sec) {
1233
681
  Entries.push_back({Tag, [=] { return Sec->getVA(0); }});
1234
681
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addInSec(int, lld::elf::InputSection*)
Line
Count
Source
1232
334
void DynamicSection<ELFT>::addInSec(int32_t Tag, InputSection *Sec) {
1233
334
  Entries.push_back({Tag, [=] { return Sec->getVA(0); }});
1234
334
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addInSec(int, lld::elf::InputSection*)
Line
Count
Source
1232
3.92k
void DynamicSection<ELFT>::addInSec(int32_t Tag, InputSection *Sec) {
1233
3.92k
  Entries.push_back({Tag, [=] { return Sec->getVA(0); }});
1234
3.92k
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addInSec(int, lld::elf::InputSection*)
Line
Count
Source
1232
279
void DynamicSection<ELFT>::addInSec(int32_t Tag, InputSection *Sec) {
1233
279
  Entries.push_back({Tag, [=] { return Sec->getVA(0); }});
1234
279
}
1235
1236
template <class ELFT>
1237
29
void DynamicSection<ELFT>::addInSecRelative(int32_t Tag, InputSection *Sec) {
1238
29
  size_t TagOffset = Entries.size() * Entsize;
1239
29
  Entries.push_back(
1240
29
      {Tag, [=] { return Sec->getVA(0) - (getVA() + TagOffset); }});
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addInSecRelative(int, lld::elf::InputSection*)::'lambda'()::operator()() const
Line
Count
Source
1240
2
      {Tag, [=] { return Sec->getVA(0) - (getVA() + TagOffset); }});
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addInSecRelative(int, lld::elf::InputSection*)::'lambda'()::operator()() const
Line
Count
Source
1240
21
      {Tag, [=] { return Sec->getVA(0) - (getVA() + TagOffset); }});
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addInSecRelative(int, lld::elf::InputSection*)::'lambda'()::operator()() const
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addInSecRelative(int, lld::elf::InputSection*)::'lambda'()::operator()() const
Line
Count
Source
1240
6
      {Tag, [=] { return Sec->getVA(0) - (getVA() + TagOffset); }});
1241
29
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addInSecRelative(int, lld::elf::InputSection*)
Line
Count
Source
1237
2
void DynamicSection<ELFT>::addInSecRelative(int32_t Tag, InputSection *Sec) {
1238
2
  size_t TagOffset = Entries.size() * Entsize;
1239
2
  Entries.push_back(
1240
2
      {Tag, [=] { return Sec->getVA(0) - (getVA() + TagOffset); }});
1241
2
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addInSecRelative(int, lld::elf::InputSection*)
Line
Count
Source
1237
21
void DynamicSection<ELFT>::addInSecRelative(int32_t Tag, InputSection *Sec) {
1238
21
  size_t TagOffset = Entries.size() * Entsize;
1239
21
  Entries.push_back(
1240
21
      {Tag, [=] { return Sec->getVA(0) - (getVA() + TagOffset); }});
1241
21
}
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addInSecRelative(int, lld::elf::InputSection*)
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addInSecRelative(int, lld::elf::InputSection*)
Line
Count
Source
1237
6
void DynamicSection<ELFT>::addInSecRelative(int32_t Tag, InputSection *Sec) {
1238
6
  size_t TagOffset = Entries.size() * Entsize;
1239
6
  Entries.push_back(
1240
6
      {Tag, [=] { return Sec->getVA(0) - (getVA() + TagOffset); }});
1241
6
}
1242
1243
template <class ELFT>
1244
8
void DynamicSection<ELFT>::addOutSec(int32_t Tag, OutputSection *Sec) {
1245
8
  Entries.push_back({Tag, [=] { return Sec->Addr; }});
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addOutSec(int, lld::elf::OutputSection*)::'lambda'()::operator()() const
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addOutSec(int, lld::elf::OutputSection*)::'lambda'()::operator()() const
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addOutSec(int, lld::elf::OutputSection*)::'lambda'()::operator()() const
Line
Count
Source
1245
8
  Entries.push_back({Tag, [=] { return Sec->Addr; }});
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addOutSec(int, lld::elf::OutputSection*)::'lambda'()::operator()() const
1246
8
}
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addOutSec(int, lld::elf::OutputSection*)
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addOutSec(int, lld::elf::OutputSection*)
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addOutSec(int, lld::elf::OutputSection*)
Line
Count
Source
1244
8
void DynamicSection<ELFT>::addOutSec(int32_t Tag, OutputSection *Sec) {
1245
8
  Entries.push_back({Tag, [=] { return Sec->Addr; }});
1246
8
}
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addOutSec(int, lld::elf::OutputSection*)
1247
1248
template <class ELFT>
1249
240
void DynamicSection<ELFT>::addSize(int32_t Tag, OutputSection *Sec) {
1250
240
  Entries.push_back({Tag, [=] 
{ return Sec->Size; }237
});
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addSize(int, lld::elf::OutputSection*)::'lambda'()::operator()() const
Line
Count
Source
1250
50
  Entries.push_back({Tag, [=] { return Sec->Size; }});
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addSize(int, lld::elf::OutputSection*)::'lambda'()::operator()() const
Line
Count
Source
1250
8
  Entries.push_back({Tag, [=] { return Sec->Size; }});
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addSize(int, lld::elf::OutputSection*)::'lambda'()::operator()() const
Line
Count
Source
1250
159
  Entries.push_back({Tag, [=] { return Sec->Size; }});
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addSize(int, lld::elf::OutputSection*)::'lambda'()::operator()() const
Line
Count
Source
1250
20
  Entries.push_back({Tag, [=] { return Sec->Size; }});
1251
240
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addSize(int, lld::elf::OutputSection*)
Line
Count
Source
1249
50
void DynamicSection<ELFT>::addSize(int32_t Tag, OutputSection *Sec) {
1250
50
  Entries.push_back({Tag, [=] { return Sec->Size; }});
1251
50
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addSize(int, lld::elf::OutputSection*)
Line
Count
Source
1249
8
void DynamicSection<ELFT>::addSize(int32_t Tag, OutputSection *Sec) {
1250
8
  Entries.push_back({Tag, [=] { return Sec->Size; }});
1251
8
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addSize(int, lld::elf::OutputSection*)
Line
Count
Source
1249
162
void DynamicSection<ELFT>::addSize(int32_t Tag, OutputSection *Sec) {
1250
162
  Entries.push_back({Tag, [=] { return Sec->Size; }});
1251
162
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addSize(int, lld::elf::OutputSection*)
Line
Count
Source
1249
20
void DynamicSection<ELFT>::addSize(int32_t Tag, OutputSection *Sec) {
1250
20
  Entries.push_back({Tag, [=] { return Sec->Size; }});
1251
20
}
1252
1253
template <class ELFT>
1254
8
void DynamicSection<ELFT>::addSym(int32_t Tag, Symbol *Sym) {
1255
8
  Entries.push_back({Tag, [=] { return Sym->getVA(); }});
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addSym(int, lld::elf::Symbol*)::'lambda'()::operator()() const
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addSym(int, lld::elf::Symbol*)::'lambda'()::operator()() const
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addSym(int, lld::elf::Symbol*)::'lambda'()::operator()() const
Line
Count
Source
1255
8
  Entries.push_back({Tag, [=] { return Sym->getVA(); }});
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addSym(int, lld::elf::Symbol*)::'lambda'()::operator()() const
1256
8
}
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addSym(int, lld::elf::Symbol*)
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addSym(int, lld::elf::Symbol*)
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addSym(int, lld::elf::Symbol*)
Line
Count
Source
1254
8
void DynamicSection<ELFT>::addSym(int32_t Tag, Symbol *Sym) {
1255
8
  Entries.push_back({Tag, [=] { return Sym->getVA(); }});
1256
8
}
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addSym(int, lld::elf::Symbol*)
1257
1258
// A Linker script may assign the RELA relocation sections to the same
1259
// output section. When this occurs we cannot just use the OutputSection
1260
// Size. Moreover the [DT_JMPREL, DT_JMPREL + DT_PLTRELSZ) is permitted to
1261
// overlap with the [DT_RELA, DT_RELA + DT_RELASZ).
1262
232
static uint64_t addPltRelSz() {
1263
232
  size_t Size = In.RelaPlt->getSize();
1264
232
  if (In.RelaIplt->getParent() == In.RelaPlt->getParent() &&
1265
232
      
In.RelaIplt->Name == In.RelaPlt->Name213
)
1266
212
    Size += In.RelaIplt->getSize();
1267
232
  return Size;
1268
232
}
1269
1270
// Add remaining entries to complete .dynamic contents.
1271
1.12k
template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1272
1.12k
  // Set DT_FLAGS and DT_FLAGS_1.
1273
1.12k
  uint32_t DtFlags = 0;
1274
1.12k
  uint32_t DtFlags1 = 0;
1275
1.12k
  if (Config->Bsymbolic)
1276
8
    DtFlags |= DF_SYMBOLIC;
1277
1.12k
  if (Config->ZGlobal)
1278
1
    DtFlags1 |= DF_1_GLOBAL;
1279
1.12k
  if (Config->ZInitfirst)
1280
1
    DtFlags1 |= DF_1_INITFIRST;
1281
1.12k
  if (Config->ZInterpose)
1282
1
    DtFlags1 |= DF_1_INTERPOSE;
1283
1.12k
  if (Config->ZNodefaultlib)
1284
1
    DtFlags1 |= DF_1_NODEFLIB;
1285
1.12k
  if (Config->ZNodelete)
1286
1
    DtFlags1 |= DF_1_NODELETE;
1287
1.12k
  if (Config->ZNodlopen)
1288
1
    DtFlags1 |= DF_1_NOOPEN;
1289
1.12k
  if (Config->ZNow) {
1290
4
    DtFlags |= DF_BIND_NOW;
1291
4
    DtFlags1 |= DF_1_NOW;
1292
4
  }
1293
1.12k
  if (Config->ZOrigin) {
1294
1
    DtFlags |= DF_ORIGIN;
1295
1
    DtFlags1 |= DF_1_ORIGIN;
1296
1
  }
1297
1.12k
  if (!Config->ZText)
1298
9
    DtFlags |= DF_TEXTREL;
1299
1.12k
1300
1.12k
  if (DtFlags)
1301
20
    addInt(DT_FLAGS, DtFlags);
1302
1.12k
  if (DtFlags1)
1303
4
    addInt(DT_FLAGS_1, DtFlags1);
1304
1.12k
1305
1.12k
  // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1306
1.12k
  // need it for each process, so we don't write it for DSOs. The loader writes
1307
1.12k
  // the pointer into this entry.
1308
1.12k
  //
1309
1.12k
  // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1310
1.12k
  // systems (currently only Fuchsia OS) provide other means to give the
1311
1.12k
  // debugger this information. Such systems may choose make .dynamic read-only.
1312
1.12k
  // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1313
1.12k
  if (!Config->Shared && 
!Config->Relocatable318
&&
!Config->ZRodynamic316
)
1314
315
    addInt(DT_DEBUG, 0);
1315
1.12k
1316
1.12k
  if (OutputSection *Sec = In.DynStrTab->getParent())
1317
1.12k
    this->Link = Sec->SectionIndex;
1318
1.12k
1319
1.12k
  if (!In.RelaDyn->empty()) {
1320
229
    addInSec(In.RelaDyn->DynamicTag, In.RelaDyn);
1321
229
    addSize(In.RelaDyn->SizeDynamicTag, In.RelaDyn->getParent());
1322
229
1323
229
    bool IsRela = Config->IsRela;
1324
229
    addInt(IsRela ? 
DT_RELAENT167
:
DT_RELENT62
,
1325
229
           IsRela ? 
sizeof(Elf_Rela)167
:
sizeof(Elf_Rel)62
);
1326
229
1327
229
    // MIPS dynamic loader does not support RELCOUNT tag.
1328
229
    // The problem is in the tight relation between dynamic
1329
229
    // relocations and GOT. So do not emit this tag on MIPS.
1330
229
    if (Config->EMachine != EM_MIPS) {
1331
213
      size_t NumRelativeRels = In.RelaDyn->getRelativeRelocCount();
1332
213
      if (Config->ZCombreloc && 
NumRelativeRels212
)
1333
43
        addInt(IsRela ? 
DT_RELACOUNT30
:
DT_RELCOUNT13
, NumRelativeRels);
1334
213
    }
1335
229
  }
1336
1.12k
  if (In.RelrDyn && 
!In.RelrDyn->Relocs.empty()4
) {
1337
3
    addInSec(Config->UseAndroidRelrTags ? 
DT_ANDROID_RELR0
: DT_RELR,
1338
3
             In.RelrDyn);
1339
3
    addSize(Config->UseAndroidRelrTags ? 
DT_ANDROID_RELRSZ0
: DT_RELRSZ,
1340
3
            In.RelrDyn->getParent());
1341
3
    addInt(Config->UseAndroidRelrTags ? 
DT_ANDROID_RELRENT0
: DT_RELRENT,
1342
3
           sizeof(Elf_Relr));
1343
3
  }
1344
1.12k
  // .rel[a].plt section usually consists of two parts, containing plt and
1345
1.12k
  // iplt relocations. It is possible to have only iplt relocations in the
1346
1.12k
  // output. In that case RelaPlt is empty and have zero offset, the same offset
1347
1.12k
  // as RelaIplt have. And we still want to emit proper dynamic tags for that
1348
1.12k
  // case, so here we always use RelaPlt as marker for the begining of
1349
1.12k
  // .rel[a].plt section.
1350
1.12k
  if (In.RelaPlt->getParent()->Live) {
1351
233
    addInSec(DT_JMPREL, In.RelaPlt);
1352
233
    Entries.push_back({DT_PLTRELSZ, addPltRelSz});
1353
233
    switch (Config->EMachine) {
1354
233
    case EM_MIPS:
1355
15
      addInSec(DT_MIPS_PLTGOT, In.GotPlt);
1356
15
      break;
1357
233
    case EM_SPARCV9:
1358
0
      addInSec(DT_PLTGOT, In.Plt);
1359
0
      break;
1360
233
    default:
1361
218
      addInSec(DT_PLTGOT, In.GotPlt);
1362
218
      break;
1363
233
    }
1364
233
    addInt(DT_PLTREL, Config->IsRela ? 
DT_RELA185
:
DT_REL48
);
1365
233
  }
1366
1.12k
1367
1.12k
  addInSec(DT_SYMTAB, In.DynSymTab);
1368
1.12k
  addInt(DT_SYMENT, sizeof(Elf_Sym));
1369
1.12k
  addInSec(DT_STRTAB, In.DynStrTab);
1370
1.12k
  addInt(DT_STRSZ, In.DynStrTab->getSize());
1371
1.12k
  if (!Config->ZText)
1372
9
    addInt(DT_TEXTREL, 0);
1373
1.12k
  if (In.GnuHashTab)
1374
896
    addInSec(DT_GNU_HASH, In.GnuHashTab);
1375
1.12k
  if (In.HashTab)
1376
1.11k
    addInSec(DT_HASH, In.HashTab);
1377
1.12k
1378
1.12k
  if (Out::PreinitArray) {
1379
3
    addOutSec(DT_PREINIT_ARRAY, Out::PreinitArray);
1380
3
    addSize(DT_PREINIT_ARRAYSZ, Out::PreinitArray);
1381
3
  }
1382
1.12k
  if (Out::InitArray) {
1383
3
    addOutSec(DT_INIT_ARRAY, Out::InitArray);
1384
3
    addSize(DT_INIT_ARRAYSZ, Out::InitArray);
1385
3
  }
1386
1.12k
  if (Out::FiniArray) {
1387
2
    addOutSec(DT_FINI_ARRAY, Out::FiniArray);
1388
2
    addSize(DT_FINI_ARRAYSZ, Out::FiniArray);
1389
2
  }
1390
1.12k
1391
1.12k
  if (Symbol *B = Symtab->find(Config->Init))
1392
6
    if (B->isDefined())
1393
4
      addSym(DT_INIT, B);
1394
1.12k
  if (Symbol *B = Symtab->find(Config->Fini))
1395
6
    if (B->isDefined())
1396
4
      addSym(DT_FINI, B);
1397
1.12k
1398
1.12k
  bool HasVerNeed = InX<ELFT>::VerNeed->getNeedNum() != 0;
1399
1.12k
  if (HasVerNeed || 
In.VerDef1.12k
)
1400
59
    addInSec(DT_VERSYM, InX<ELFT>::VerSym);
1401
1.12k
  if (In.VerDef) {
1402
52
    addInSec(DT_VERDEF, In.VerDef);
1403
52
    addInt(DT_VERDEFNUM, getVerDefNum());
1404
52
  }
1405
1.12k
  if (HasVerNeed) {
1406
8
    addInSec(DT_VERNEED, InX<ELFT>::VerNeed);
1407
8
    addInt(DT_VERNEEDNUM, InX<ELFT>::VerNeed->getNeedNum());
1408
8
  }
1409
1.12k
1410
1.12k
  if (Config->EMachine == EM_MIPS) {
1411
100
    addInt(DT_MIPS_RLD_VERSION, 1);
1412
100
    addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1413
100
    addInt(DT_MIPS_BASE_ADDRESS, Target->getImageBase());
1414
100
    addInt(DT_MIPS_SYMTABNO, In.DynSymTab->getNumSymbols());
1415
100
1416
100
    add(DT_MIPS_LOCAL_GOTNO, [] { return In.MipsGot->getLocalEntriesNum(); });
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::finalizeContents()::'lambda'()::operator()() const
Line
Count
Source
1416
8
    add(DT_MIPS_LOCAL_GOTNO, [] { return In.MipsGot->getLocalEntriesNum(); });
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::finalizeContents()::'lambda'()::operator()() const
Line
Count
Source
1416
69
    add(DT_MIPS_LOCAL_GOTNO, [] { return In.MipsGot->getLocalEntriesNum(); });
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::finalizeContents()::'lambda'()::operator()() const
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::finalizeContents()::'lambda'()::operator()() const
Line
Count
Source
1416
23
    add(DT_MIPS_LOCAL_GOTNO, [] { return In.MipsGot->getLocalEntriesNum(); });
1417
100
1418
100
    if (const Symbol *B = In.MipsGot->getFirstGlobalEntry())
1419
32
      addInt(DT_MIPS_GOTSYM, B->DynsymIndex);
1420
68
    else
1421
68
      addInt(DT_MIPS_GOTSYM, In.DynSymTab->getNumSymbols());
1422
100
    addInSec(DT_PLTGOT, In.MipsGot);
1423
100
    if (In.MipsRldMap) {
1424
29
      if (!Config->Pie)
1425
26
        addInSec(DT_MIPS_RLD_MAP, In.MipsRldMap);
1426
29
      // Store the offset to the .rld_map section
1427
29
      // relative to the address of the tag.
1428
29
      addInSecRelative(DT_MIPS_RLD_MAP_REL, In.MipsRldMap);
1429
29
    }
1430
100
  }
1431
1.12k
1432
1.12k
  // Glink dynamic tag is required by the V2 abi if the plt section isn't empty.
1433
1.12k
  if (Config->EMachine == EM_PPC64 && 
!In.Plt->empty()75
) {
1434
28
    // The Glink tag points to 32 bytes before the first lazy symbol resolution
1435
28
    // stub, which starts directly after the header.
1436
28
    Entries.push_back({DT_PPC64_GLINK, [=] {
1437
28
                         unsigned Offset = Target->PltHeaderSize - 32;
1438
28
                         return In.Plt->getVA(0) + Offset;
1439
28
                       }});
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::finalizeContents()::'lambda0'()::operator()() const
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::finalizeContents()::'lambda0'()::operator()() const
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::finalizeContents()::'lambda0'()::operator()() const
Line
Count
Source
1436
15
    Entries.push_back({DT_PPC64_GLINK, [=] {
1437
15
                         unsigned Offset = Target->PltHeaderSize - 32;
1438
15
                         return In.Plt->getVA(0) + Offset;
1439
15
                       }});
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::finalizeContents()::'lambda0'()::operator()() const
Line
Count
Source
1436
13
    Entries.push_back({DT_PPC64_GLINK, [=] {
1437
13
                         unsigned Offset = Target->PltHeaderSize - 32;
1438
13
                         return In.Plt->getVA(0) + Offset;
1439
13
                       }});
1440
28
  }
1441
1.12k
1442
1.12k
  addInt(DT_NULL, 0);
1443
1.12k
1444
1.12k
  getParent()->Link = this->Link;
1445
1.12k
  this->Size = Entries.size() * this->Entsize;
1446
1.12k
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::finalizeContents()
Line
Count
Source
1271
148
template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1272
148
  // Set DT_FLAGS and DT_FLAGS_1.
1273
148
  uint32_t DtFlags = 0;
1274
148
  uint32_t DtFlags1 = 0;
1275
148
  if (Config->Bsymbolic)
1276
2
    DtFlags |= DF_SYMBOLIC;
1277
148
  if (Config->ZGlobal)
1278
0
    DtFlags1 |= DF_1_GLOBAL;
1279
148
  if (Config->ZInitfirst)
1280
0
    DtFlags1 |= DF_1_INITFIRST;
1281
148
  if (Config->ZInterpose)
1282
0
    DtFlags1 |= DF_1_INTERPOSE;
1283
148
  if (Config->ZNodefaultlib)
1284
0
    DtFlags1 |= DF_1_NODEFLIB;
1285
148
  if (Config->ZNodelete)
1286
0
    DtFlags1 |= DF_1_NODELETE;
1287
148
  if (Config->ZNodlopen)
1288
0
    DtFlags1 |= DF_1_NOOPEN;
1289
148
  if (Config->ZNow) {
1290
0
    DtFlags |= DF_BIND_NOW;
1291
0
    DtFlags1 |= DF_1_NOW;
1292
0
  }
1293
148
  if (Config->ZOrigin) {
1294
0
    DtFlags |= DF_ORIGIN;
1295
0
    DtFlags1 |= DF_1_ORIGIN;
1296
0
  }
1297
148
  if (!Config->ZText)
1298
0
    DtFlags |= DF_TEXTREL;
1299
148
1300
148
  if (DtFlags)
1301
2
    addInt(DT_FLAGS, DtFlags);
1302
148
  if (DtFlags1)
1303
0
    addInt(DT_FLAGS_1, DtFlags1);
1304
148
1305
148
  // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1306
148
  // need it for each process, so we don't write it for DSOs. The loader writes
1307
148
  // the pointer into this entry.
1308
148
  //
1309
148
  // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1310
148
  // systems (currently only Fuchsia OS) provide other means to give the
1311
148
  // debugger this information. Such systems may choose make .dynamic read-only.
1312
148
  // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1313
148
  if (!Config->Shared && 
!Config->Relocatable45
&&
!Config->ZRodynamic45
)
1314
45
    addInt(DT_DEBUG, 0);
1315
148
1316
148
  if (OutputSection *Sec = In.DynStrTab->getParent())
1317
148
    this->Link = Sec->SectionIndex;
1318
148
1319
148
  if (!In.RelaDyn->empty()) {
1320
48
    addInSec(In.RelaDyn->DynamicTag, In.RelaDyn);
1321
48
    addSize(In.RelaDyn->SizeDynamicTag, In.RelaDyn->getParent());
1322
48
1323
48
    bool IsRela = Config->IsRela;
1324
48
    addInt(IsRela ? 
DT_RELAENT1
:
DT_RELENT47
,
1325
48
           IsRela ? 
sizeof(Elf_Rela)1
:
sizeof(Elf_Rel)47
);
1326
48
1327
48
    // MIPS dynamic loader does not support RELCOUNT tag.
1328
48
    // The problem is in the tight relation between dynamic
1329
48
    // relocations and GOT. So do not emit this tag on MIPS.
1330
48
    if (Config->EMachine != EM_MIPS) {
1331
47
      size_t NumRelativeRels = In.RelaDyn->getRelativeRelocCount();
1332
47
      if (Config->ZCombreloc && NumRelativeRels)
1333
13
        addInt(IsRela ? 
DT_RELACOUNT0
: DT_RELCOUNT, NumRelativeRels);
1334
47
    }
1335
48
  }
1336
148
  if (In.RelrDyn && 
!In.RelrDyn->Relocs.empty()2
) {
1337
2
    addInSec(Config->UseAndroidRelrTags ? 
DT_ANDROID_RELR0
: DT_RELR,
1338
2
             In.RelrDyn);
1339
2
    addSize(Config->UseAndroidRelrTags ? 
DT_ANDROID_RELRSZ0
: DT_RELRSZ,
1340
2
            In.RelrDyn->getParent());
1341
2
    addInt(Config->UseAndroidRelrTags ? 
DT_ANDROID_RELRENT0
: DT_RELRENT,
1342
2
           sizeof(Elf_Relr));
1343
2
  }
1344
148
  // .rel[a].plt section usually consists of two parts, containing plt and
1345
148
  // iplt relocations. It is possible to have only iplt relocations in the
1346
148
  // output. In that case RelaPlt is empty and have zero offset, the same offset
1347
148
  // as RelaIplt have. And we still want to emit proper dynamic tags for that
1348
148
  // case, so here we always use RelaPlt as marker for the begining of
1349
148
  // .rel[a].plt section.
1350
148
  if (In.RelaPlt->getParent()->Live) {
1351
37
    addInSec(DT_JMPREL, In.RelaPlt);
1352
37
    Entries.push_back({DT_PLTRELSZ, addPltRelSz});
1353
37
    switch (Config->EMachine) {
1354
37
    case EM_MIPS:
1355
2
      addInSec(DT_MIPS_PLTGOT, In.GotPlt);
1356
2
      break;
1357
37
    case EM_SPARCV9:
1358
0
      addInSec(DT_PLTGOT, In.Plt);
1359
0
      break;
1360
37
    default:
1361
35
      addInSec(DT_PLTGOT, In.GotPlt);
1362
35
      break;
1363
37
    }
1364
37
    addInt(DT_PLTREL, Config->IsRela ? 
DT_RELA2
:
DT_REL35
);
1365
37
  }
1366
148
1367
148
  addInSec(DT_SYMTAB, In.DynSymTab);
1368
148
  addInt(DT_SYMENT, sizeof(Elf_Sym));
1369
148
  addInSec(DT_STRTAB, In.DynStrTab);
1370
148
  addInt(DT_STRSZ, In.DynStrTab->getSize());
1371
148
  if (!Config->ZText)
1372
0
    addInt(DT_TEXTREL, 0);
1373
148
  if (In.GnuHashTab)
1374
105
    addInSec(DT_GNU_HASH, In.GnuHashTab);
1375
148
  if (In.HashTab)
1376
146
    addInSec(DT_HASH, In.HashTab);
1377
148
1378
148
  if (Out::PreinitArray) {
1379
0
    addOutSec(DT_PREINIT_ARRAY, Out::PreinitArray);
1380
0
    addSize(DT_PREINIT_ARRAYSZ, Out::PreinitArray);
1381
0
  }
1382
148
  if (Out::InitArray) {
1383
0
    addOutSec(DT_INIT_ARRAY, Out::InitArray);
1384
0
    addSize(DT_INIT_ARRAYSZ, Out::InitArray);
1385
0
  }
1386
148
  if (Out::FiniArray) {
1387
0
    addOutSec(DT_FINI_ARRAY, Out::FiniArray);
1388
0
    addSize(DT_FINI_ARRAYSZ, Out::FiniArray);
1389
0
  }
1390
148
1391
148
  if (Symbol *B = Symtab->find(Config->Init))
1392
0
    if (B->isDefined())
1393
0
      addSym(DT_INIT, B);
1394
148
  if (Symbol *B = Symtab->find(Config->Fini))
1395
0
    if (B->isDefined())
1396
0
      addSym(DT_FINI, B);
1397
148
1398
148
  bool HasVerNeed = InX<ELFT>::VerNeed->getNeedNum() != 0;
1399
148
  if (HasVerNeed || In.VerDef)
1400
0
    addInSec(DT_VERSYM, InX<ELFT>::VerSym);
1401
148
  if (In.VerDef) {
1402
0
    addInSec(DT_VERDEF, In.VerDef);
1403
0
    addInt(DT_VERDEFNUM, getVerDefNum());
1404
0
  }
1405
148
  if (HasVerNeed) {
1406
0
    addInSec(DT_VERNEED, InX<ELFT>::VerNeed);
1407
0
    addInt(DT_VERNEEDNUM, InX<ELFT>::VerNeed->getNeedNum());
1408
0
  }
1409
148
1410
148
  if (Config->EMachine == EM_MIPS) {
1411
8
    addInt(DT_MIPS_RLD_VERSION, 1);
1412
8
    addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1413
8
    addInt(DT_MIPS_BASE_ADDRESS, Target->getImageBase());
1414
8
    addInt(DT_MIPS_SYMTABNO, In.DynSymTab->getNumSymbols());
1415
8
1416
8
    add(DT_MIPS_LOCAL_GOTNO, [] { return In.MipsGot->getLocalEntriesNum(); });
1417
8
1418
8
    if (const Symbol *B = In.MipsGot->getFirstGlobalEntry())
1419
3
      addInt(DT_MIPS_GOTSYM, B->DynsymIndex);
1420
5
    else
1421
5
      addInt(DT_MIPS_GOTSYM, In.DynSymTab->getNumSymbols());
1422
8
    addInSec(DT_PLTGOT, In.MipsGot);
1423
8
    if (In.MipsRldMap) {
1424
2
      if (!Config->Pie)
1425
2
        addInSec(DT_MIPS_RLD_MAP, In.MipsRldMap);
1426
2
      // Store the offset to the .rld_map section
1427
2
      // relative to the address of the tag.
1428
2
      addInSecRelative(DT_MIPS_RLD_MAP_REL, In.MipsRldMap);
1429
2
    }
1430
8
  }
1431
148
1432
148
  // Glink dynamic tag is required by the V2 abi if the plt section isn't empty.
1433
148
  if (Config->EMachine == EM_PPC64 && 
!In.Plt->empty()0
) {
1434
0
    // The Glink tag points to 32 bytes before the first lazy symbol resolution
1435
0
    // stub, which starts directly after the header.
1436
0
    Entries.push_back({DT_PPC64_GLINK, [=] {
1437
0
                         unsigned Offset = Target->PltHeaderSize - 32;
1438
0
                         return In.Plt->getVA(0) + Offset;
1439
0
                       }});
1440
0
  }
1441
148
1442
148
  addInt(DT_NULL, 0);
1443
148
1444
148
  getParent()->Link = this->Link;
1445
148
  this->Size = Entries.size() * this->Entsize;
1446
148
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::finalizeContents()
Line
Count
Source
1271
71
template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1272
71
  // Set DT_FLAGS and DT_FLAGS_1.
1273
71
  uint32_t DtFlags = 0;
1274
71
  uint32_t DtFlags1 = 0;
1275
71
  if (Config->Bsymbolic)
1276
1
    DtFlags |= DF_SYMBOLIC;
1277
71
  if (Config->ZGlobal)
1278
0
    DtFlags1 |= DF_1_GLOBAL;
1279
71
  if (Config->ZInitfirst)
1280
0
    DtFlags1 |= DF_1_INITFIRST;
1281
71
  if (Config->ZInterpose)
1282
0
    DtFlags1 |= DF_1_INTERPOSE;
1283
71
  if (Config->ZNodefaultlib)
1284
0
    DtFlags1 |= DF_1_NODEFLIB;
1285
71
  if (Config->ZNodelete)
1286
0
    DtFlags1 |= DF_1_NODELETE;
1287
71
  if (Config->ZNodlopen)
1288
0
    DtFlags1 |= DF_1_NOOPEN;
1289
71
  if (Config->ZNow) {
1290
0
    DtFlags |= DF_BIND_NOW;
1291
0
    DtFlags1 |= DF_1_NOW;
1292
0
  }
1293
71
  if (Config->ZOrigin) {
1294
0
    DtFlags |= DF_ORIGIN;
1295
0
    DtFlags1 |= DF_1_ORIGIN;
1296
0
  }
1297
71
  if (!Config->ZText)
1298
0
    DtFlags |= DF_TEXTREL;
1299
71
1300
71
  if (DtFlags)
1301
1
    addInt(DT_FLAGS, DtFlags);
1302
71
  if (DtFlags1)
1303
0
    addInt(DT_FLAGS_1, DtFlags1);
1304
71
1305
71
  // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1306
71
  // need it for each process, so we don't write it for DSOs. The loader writes
1307
71
  // the pointer into this entry.
1308
71
  //
1309
71
  // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1310
71
  // systems (currently only Fuchsia OS) provide other means to give the
1311
71
  // debugger this information. Such systems may choose make .dynamic read-only.
1312
71
  // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1313
71
  if (!Config->Shared && 
!Config->Relocatable21
&&
!Config->ZRodynamic21
)
1314
21
    addInt(DT_DEBUG, 0);
1315
71
1316
71
  if (OutputSection *Sec = In.DynStrTab->getParent())
1317
71
    this->Link = Sec->SectionIndex;
1318
71
1319
71
  if (!In.RelaDyn->empty()) {
1320
8
    addInSec(In.RelaDyn->DynamicTag, In.RelaDyn);
1321
8
    addSize(In.RelaDyn->SizeDynamicTag, In.RelaDyn->getParent());
1322
8
1323
8
    bool IsRela = Config->IsRela;
1324
8
    addInt(IsRela ? 
DT_RELAENT1
:
DT_RELENT7
,
1325
8
           IsRela ? 
sizeof(Elf_Rela)1
:
sizeof(Elf_Rel)7
);
1326
8
1327
8
    // MIPS dynamic loader does not support RELCOUNT tag.
1328
8
    // The problem is in the tight relation between dynamic
1329
8
    // relocations and GOT. So do not emit this tag on MIPS.
1330
8
    if (Config->EMachine != EM_MIPS) {
1331
1
      size_t NumRelativeRels = In.RelaDyn->getRelativeRelocCount();
1332
1
      if (Config->ZCombreloc && NumRelativeRels)
1333
0
        addInt(IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels);
1334
1
    }
1335
8
  }
1336
71
  if (In.RelrDyn && 
!In.RelrDyn->Relocs.empty()0
) {
1337
0
    addInSec(Config->UseAndroidRelrTags ? DT_ANDROID_RELR : DT_RELR,
1338
0
             In.RelrDyn);
1339
0
    addSize(Config->UseAndroidRelrTags ? DT_ANDROID_RELRSZ : DT_RELRSZ,
1340
0
            In.RelrDyn->getParent());
1341
0
    addInt(Config->UseAndroidRelrTags ? DT_ANDROID_RELRENT : DT_RELRENT,
1342
0
           sizeof(Elf_Relr));
1343
0
  }
1344
71
  // .rel[a].plt section usually consists of two parts, containing plt and
1345
71
  // iplt relocations. It is possible to have only iplt relocations in the
1346
71
  // output. In that case RelaPlt is empty and have zero offset, the same offset
1347
71
  // as RelaIplt have. And we still want to emit proper dynamic tags for that
1348
71
  // case, so here we always use RelaPlt as marker for the begining of
1349
71
  // .rel[a].plt section.
1350
71
  if (In.RelaPlt->getParent()->Live) {
1351
11
    addInSec(DT_JMPREL, In.RelaPlt);
1352
11
    Entries.push_back({DT_PLTRELSZ, addPltRelSz});
1353
11
    switch (Config->EMachine) {
1354
11
    case EM_MIPS:
1355
11
      addInSec(DT_MIPS_PLTGOT, In.GotPlt);
1356
11
      break;
1357
11
    case EM_SPARCV9:
1358
0
      addInSec(DT_PLTGOT, In.Plt);
1359
0
      break;
1360
11
    default:
1361
0
      addInSec(DT_PLTGOT, In.GotPlt);
1362
0
      break;
1363
11
    }
1364
11
    addInt(DT_PLTREL, Config->IsRela ? 
DT_RELA0
: DT_REL);
1365
11
  }
1366
71
1367
71
  addInSec(DT_SYMTAB, In.DynSymTab);
1368
71
  addInt(DT_SYMENT, sizeof(Elf_Sym));
1369
71
  addInSec(DT_STRTAB, In.DynStrTab);
1370
71
  addInt(DT_STRSZ, In.DynStrTab->getSize());
1371
71
  if (!Config->ZText)
1372
0
    addInt(DT_TEXTREL, 0);
1373
71
  if (In.GnuHashTab)
1374
1
    addInSec(DT_GNU_HASH, In.GnuHashTab);
1375
71
  if (In.HashTab)
1376
71
    addInSec(DT_HASH, In.HashTab);
1377
71
1378
71
  if (Out::PreinitArray) {
1379
0
    addOutSec(DT_PREINIT_ARRAY, Out::PreinitArray);
1380
0
    addSize(DT_PREINIT_ARRAYSZ, Out::PreinitArray);
1381
0
  }
1382
71
  if (Out::InitArray) {
1383
0
    addOutSec(DT_INIT_ARRAY, Out::InitArray);
1384
0
    addSize(DT_INIT_ARRAYSZ, Out::InitArray);
1385
0
  }
1386
71
  if (Out::FiniArray) {
1387
0
    addOutSec(DT_FINI_ARRAY, Out::FiniArray);
1388
0
    addSize(DT_FINI_ARRAYSZ, Out::FiniArray);
1389
0
  }
1390
71
1391
71
  if (Symbol *B = Symtab->find(Config->Init))
1392
0
    if (B->isDefined())
1393
0
      addSym(DT_INIT, B);
1394
71
  if (Symbol *B = Symtab->find(Config->Fini))
1395
0
    if (B->isDefined())
1396
0
      addSym(DT_FINI, B);
1397
71
1398
71
  bool HasVerNeed = InX<ELFT>::VerNeed->getNeedNum() != 0;
1399
71
  if (HasVerNeed || 
In.VerDef70
)
1400
1
    addInSec(DT_VERSYM, InX<ELFT>::VerSym);
1401
71
  if (In.VerDef) {
1402
0
    addInSec(DT_VERDEF, In.VerDef);
1403
0
    addInt(DT_VERDEFNUM, getVerDefNum());
1404
0
  }
1405
71
  if (HasVerNeed) {
1406
1
    addInSec(DT_VERNEED, InX<ELFT>::VerNeed);
1407
1
    addInt(DT_VERNEEDNUM, InX<ELFT>::VerNeed->getNeedNum());
1408
1
  }
1409
71
1410
71
  if (Config->EMachine == EM_MIPS) {
1411
69
    addInt(DT_MIPS_RLD_VERSION, 1);
1412
69
    addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1413
69
    addInt(DT_MIPS_BASE_ADDRESS, Target->getImageBase());
1414
69
    addInt(DT_MIPS_SYMTABNO, In.DynSymTab->getNumSymbols());
1415
69
1416
69
    add(DT_MIPS_LOCAL_GOTNO, [] { return In.MipsGot->getLocalEntriesNum(); });
1417
69
1418
69
    if (const Symbol *B = In.MipsGot->getFirstGlobalEntry())
1419
23
      addInt(DT_MIPS_GOTSYM, B->DynsymIndex);
1420
46
    else
1421
46
      addInt(DT_MIPS_GOTSYM, In.DynSymTab->getNumSymbols());
1422
69
    addInSec(DT_PLTGOT, In.MipsGot);
1423
69
    if (In.MipsRldMap) {
1424
21
      if (!Config->Pie)
1425
19
        addInSec(DT_MIPS_RLD_MAP, In.MipsRldMap);
1426
21
      // Store the offset to the .rld_map section
1427
21
      // relative to the address of the tag.
1428
21
      addInSecRelative(DT_MIPS_RLD_MAP_REL, In.MipsRldMap);
1429
21
    }
1430
69
  }
1431
71
1432
71
  // Glink dynamic tag is required by the V2 abi if the plt section isn't empty.
1433
71
  if (Config->EMachine == EM_PPC64 && 
!In.Plt->empty()0
) {
1434
0
    // The Glink tag points to 32 bytes before the first lazy symbol resolution
1435
0
    // stub, which starts directly after the header.
1436
0
    Entries.push_back({DT_PPC64_GLINK, [=] {
1437
0
                         unsigned Offset = Target->PltHeaderSize - 32;
1438
0
                         return In.Plt->getVA(0) + Offset;
1439
0
                       }});
1440
0
  }
1441
71
1442
71
  addInt(DT_NULL, 0);
1443
71
1444
71
  getParent()->Link = this->Link;
1445
71
  this->Size = Entries.size() * this->Entsize;
1446
71
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::finalizeContents()
Line
Count
Source
1271
853
template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1272
853
  // Set DT_FLAGS and DT_FLAGS_1.
1273
853
  uint32_t DtFlags = 0;
1274
853
  uint32_t DtFlags1 = 0;
1275
853
  if (Config->Bsymbolic)
1276
4
    DtFlags |= DF_SYMBOLIC;
1277
853
  if (Config->ZGlobal)
1278
1
    DtFlags1 |= DF_1_GLOBAL;
1279
853
  if (Config->ZInitfirst)
1280
1
    DtFlags1 |= DF_1_INITFIRST;
1281
853
  if (Config->ZInterpose)
1282
1
    DtFlags1 |= DF_1_INTERPOSE;
1283
853
  if (Config->ZNodefaultlib)
1284
1
    DtFlags1 |= DF_1_NODEFLIB;
1285
853
  if (Config->ZNodelete)
1286
1
    DtFlags1 |= DF_1_NODELETE;
1287
853
  if (Config->ZNodlopen)
1288
1
    DtFlags1 |= DF_1_NOOPEN;
1289
853
  if (Config->ZNow) {
1290
4
    DtFlags |= DF_BIND_NOW;
1291
4
    DtFlags1 |= DF_1_NOW;
1292
4
  }
1293
853
  if (Config->ZOrigin) {
1294
1
    DtFlags |= DF_ORIGIN;
1295
1
    DtFlags1 |= DF_1_ORIGIN;
1296
1
  }
1297
853
  if (!Config->ZText)
1298
7
    DtFlags |= DF_TEXTREL;
1299
853
1300
853
  if (DtFlags)
1301
14
    addInt(DT_FLAGS, DtFlags);
1302
853
  if (DtFlags1)
1303
4
    addInt(DT_FLAGS_1, DtFlags1);
1304
853
1305
853
  // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1306
853
  // need it for each process, so we don't write it for DSOs. The loader writes
1307
853
  // the pointer into this entry.
1308
853
  //
1309
853
  // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1310
853
  // systems (currently only Fuchsia OS) provide other means to give the
1311
853
  // debugger this information. Such systems may choose make .dynamic read-only.
1312
853
  // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1313
853
  if (!Config->Shared && 
!Config->Relocatable236
&&
!Config->ZRodynamic234
)
1314
233
    addInt(DT_DEBUG, 0);
1315
853
1316
853
  if (OutputSection *Sec = In.DynStrTab->getParent())
1317
852
    this->Link = Sec->SectionIndex;
1318
853
1319
853
  if (!In.RelaDyn->empty()) {
1320
153
    addInSec(In.RelaDyn->DynamicTag, In.RelaDyn);
1321
153
    addSize(In.RelaDyn->SizeDynamicTag, In.RelaDyn->getParent());
1322
153
1323
153
    bool IsRela = Config->IsRela;
1324
153
    addInt(IsRela ? DT_RELAENT : 
DT_RELENT0
,
1325
153
           IsRela ? sizeof(Elf_Rela) : 
sizeof(Elf_Rel)0
);
1326
153
1327
153
    // MIPS dynamic loader does not support RELCOUNT tag.
1328
153
    // The problem is in the tight relation between dynamic
1329
153
    // relocations and GOT. So do not emit this tag on MIPS.
1330
153
    if (Config->EMachine != EM_MIPS) {
1331
153
      size_t NumRelativeRels = In.RelaDyn->getRelativeRelocCount();
1332
153
      if (Config->ZCombreloc && 
NumRelativeRels152
)
1333
29
        addInt(IsRela ? DT_RELACOUNT : 
DT_RELCOUNT0
, NumRelativeRels);
1334
153
    }
1335
153
  }
1336
853
  if (In.RelrDyn && 
!In.RelrDyn->Relocs.empty()2
) {
1337
1
    addInSec(Config->UseAndroidRelrTags ? 
DT_ANDROID_RELR0
: DT_RELR,
1338
1
             In.RelrDyn);
1339
1
    addSize(Config->UseAndroidRelrTags ? 
DT_ANDROID_RELRSZ0
: DT_RELRSZ,
1340
1
            In.RelrDyn->getParent());
1341
1
    addInt(Config->UseAndroidRelrTags ? 
DT_ANDROID_RELRENT0
: DT_RELRENT,
1342
1
           sizeof(Elf_Relr));
1343
1
  }
1344
853
  // .rel[a].plt section usually consists of two parts, containing plt and
1345
853
  // iplt relocations. It is possible to have only iplt relocations in the
1346
853
  // output. In that case RelaPlt is empty and have zero offset, the same offset
1347
853
  // as RelaIplt have. And we still want to emit proper dynamic tags for that
1348
853
  // case, so here we always use RelaPlt as marker for the begining of
1349
853
  // .rel[a].plt section.
1350
853
  if (In.RelaPlt->getParent()->Live) {
1351
170
    addInSec(DT_JMPREL, In.RelaPlt);
1352
170
    Entries.push_back({DT_PLTRELSZ, addPltRelSz});
1353
170
    switch (Config->EMachine) {
1354
170
    case EM_MIPS:
1355
0
      addInSec(DT_MIPS_PLTGOT, In.GotPlt);
1356
0
      break;
1357
170
    case EM_SPARCV9:
1358
0
      addInSec(DT_PLTGOT, In.Plt);
1359
0
      break;
1360
170
    default:
1361
170
      addInSec(DT_PLTGOT, In.GotPlt);
1362
170
      break;
1363
170
    }
1364
170
    addInt(DT_PLTREL, Config->IsRela ? DT_RELA : 
DT_REL0
);
1365
170
  }
1366
853
1367
853
  addInSec(DT_SYMTAB, In.DynSymTab);
1368
853
  addInt(DT_SYMENT, sizeof(Elf_Sym));
1369
853
  addInSec(DT_STRTAB, In.DynStrTab);
1370
853
  addInt(DT_STRSZ, In.DynStrTab->getSize());
1371
853
  if (!Config->ZText)
1372
7
    addInt(DT_TEXTREL, 0);
1373
853
  if (In.GnuHashTab)
1374
757
    addInSec(DT_GNU_HASH, In.GnuHashTab);
1375
853
  if (In.HashTab)
1376
846
    addInSec(DT_HASH, In.HashTab);
1377
853
1378
853
  if (Out::PreinitArray) {
1379
3
    addOutSec(DT_PREINIT_ARRAY, Out::PreinitArray);
1380
3
    addSize(DT_PREINIT_ARRAYSZ, Out::PreinitArray);
1381
3
  }
1382
853
  if (Out::InitArray) {
1383
3
    addOutSec(DT_INIT_ARRAY, Out::InitArray);
1384
3
    addSize(DT_INIT_ARRAYSZ, Out::InitArray);
1385
3
  }
1386
853
  if (Out::FiniArray) {
1387
2
    addOutSec(DT_FINI_ARRAY, Out::FiniArray);
1388
2
    addSize(DT_FINI_ARRAYSZ, Out::FiniArray);
1389
2
  }
1390
853
1391
853
  if (Symbol *B = Symtab->find(Config->Init))
1392
6
    if (B->isDefined())
1393
4
      addSym(DT_INIT, B);
1394
853
  if (Symbol *B = Symtab->find(Config->Fini))
1395
6
    if (B->isDefined())
1396
4
      addSym(DT_FINI, B);
1397
853
1398
853
  bool HasVerNeed = InX<ELFT>::VerNeed->getNeedNum() != 0;
1399
853
  if (HasVerNeed || 
In.VerDef846
)
1400
58
    addInSec(DT_VERSYM, InX<ELFT>::VerSym);
1401
853
  if (In.VerDef) {
1402
52
    addInSec(DT_VERDEF, In.VerDef);
1403
52
    addInt(DT_VERDEFNUM, getVerDefNum());
1404
52
  }
1405
853
  if (HasVerNeed) {
1406
7
    addInSec(DT_VERNEED, InX<ELFT>::VerNeed);
1407
7
    addInt(DT_VERNEEDNUM, InX<ELFT>::VerNeed->getNeedNum());
1408
7
  }
1409
853
1410
853
  if (Config->EMachine == EM_MIPS) {
1411
0
    addInt(DT_MIPS_RLD_VERSION, 1);
1412
0
    addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1413
0
    addInt(DT_MIPS_BASE_ADDRESS, Target->getImageBase());
1414
0
    addInt(DT_MIPS_SYMTABNO, In.DynSymTab->getNumSymbols());
1415
0
1416
0
    add(DT_MIPS_LOCAL_GOTNO, [] { return In.MipsGot->getLocalEntriesNum(); });
1417
0
1418
0
    if (const Symbol *B = In.MipsGot->getFirstGlobalEntry())
1419
0
      addInt(DT_MIPS_GOTSYM, B->DynsymIndex);
1420
0
    else
1421
0
      addInt(DT_MIPS_GOTSYM, In.DynSymTab->getNumSymbols());
1422
0
    addInSec(DT_PLTGOT, In.MipsGot);
1423
0
    if (In.MipsRldMap) {
1424
0
      if (!Config->Pie)
1425
0
        addInSec(DT_MIPS_RLD_MAP, In.MipsRldMap);
1426
0
      // Store the offset to the .rld_map section
1427
0
      // relative to the address of the tag.
1428
0
      addInSecRelative(DT_MIPS_RLD_MAP_REL, In.MipsRldMap);
1429
0
    }
1430
0
  }
1431
853
1432
853
  // Glink dynamic tag is required by the V2 abi if the plt section isn't empty.
1433
853
  if (Config->EMachine == EM_PPC64 && 
!In.Plt->empty()42
) {
1434
15
    // The Glink tag points to 32 bytes before the first lazy symbol resolution
1435
15
    // stub, which starts directly after the header.
1436
15
    Entries.push_back({DT_PPC64_GLINK, [=] {
1437
15
                         unsigned Offset = Target->PltHeaderSize - 32;
1438
15
                         return In.Plt->getVA(0) + Offset;
1439
15
                       }});
1440
15
  }
1441
853
1442
853
  addInt(DT_NULL, 0);
1443
853
1444
853
  getParent()->Link = this->Link;
1445
853
  this->Size = Entries.size() * this->Entsize;
1446
853
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::finalizeContents()
Line
Count
Source
1271
56
template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1272
56
  // Set DT_FLAGS and DT_FLAGS_1.
1273
56
  uint32_t DtFlags = 0;
1274
56
  uint32_t DtFlags1 = 0;
1275
56
  if (Config->Bsymbolic)
1276
1
    DtFlags |= DF_SYMBOLIC;
1277
56
  if (Config->ZGlobal)
1278
0
    DtFlags1 |= DF_1_GLOBAL;
1279
56
  if (Config->ZInitfirst)
1280
0
    DtFlags1 |= DF_1_INITFIRST;
1281
56
  if (Config->ZInterpose)
1282
0
    DtFlags1 |= DF_1_INTERPOSE;
1283
56
  if (Config->ZNodefaultlib)
1284
0
    DtFlags1 |= DF_1_NODEFLIB;
1285
56
  if (Config->ZNodelete)
1286
0
    DtFlags1 |= DF_1_NODELETE;
1287
56
  if (Config->ZNodlopen)
1288
0
    DtFlags1 |= DF_1_NOOPEN;
1289
56
  if (Config->ZNow) {
1290
0
    DtFlags |= DF_BIND_NOW;
1291
0
    DtFlags1 |= DF_1_NOW;
1292
0
  }
1293
56
  if (Config->ZOrigin) {
1294
0
    DtFlags |= DF_ORIGIN;
1295
0
    DtFlags1 |= DF_1_ORIGIN;
1296
0
  }
1297
56
  if (!Config->ZText)
1298
2
    DtFlags |= DF_TEXTREL;
1299
56
1300
56
  if (DtFlags)
1301
3
    addInt(DT_FLAGS, DtFlags);
1302
56
  if (DtFlags1)
1303
0
    addInt(DT_FLAGS_1, DtFlags1);
1304
56
1305
56
  // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1306
56
  // need it for each process, so we don't write it for DSOs. The loader writes
1307
56
  // the pointer into this entry.
1308
56
  //
1309
56
  // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1310
56
  // systems (currently only Fuchsia OS) provide other means to give the
1311
56
  // debugger this information. Such systems may choose make .dynamic read-only.
1312
56
  // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1313
56
  if (!Config->Shared && 
!Config->Relocatable16
&&
!Config->ZRodynamic16
)
1314
16
    addInt(DT_DEBUG, 0);
1315
56
1316
56
  if (OutputSection *Sec = In.DynStrTab->getParent())
1317
56
    this->Link = Sec->SectionIndex;
1318
56
1319
56
  if (!In.RelaDyn->empty()) {
1320
20
    addInSec(In.RelaDyn->DynamicTag, In.RelaDyn);
1321
20
    addSize(In.RelaDyn->SizeDynamicTag, In.RelaDyn->getParent());
1322
20
1323
20
    bool IsRela = Config->IsRela;
1324
20
    addInt(IsRela ? 
DT_RELAENT12
:
DT_RELENT8
,
1325
20
           IsRela ? 
sizeof(Elf_Rela)12
:
sizeof(Elf_Rel)8
);
1326
20
1327
20
    // MIPS dynamic loader does not support RELCOUNT tag.
1328
20
    // The problem is in the tight relation between dynamic
1329
20
    // relocations and GOT. So do not emit this tag on MIPS.
1330
20
    if (Config->EMachine != EM_MIPS) {
1331
12
      size_t NumRelativeRels = In.RelaDyn->getRelativeRelocCount();
1332
12
      if (Config->ZCombreloc && NumRelativeRels)
1333
1
        addInt(IsRela ? DT_RELACOUNT : 
DT_RELCOUNT0
, NumRelativeRels);
1334
12
    }
1335
20
  }
1336
56
  if (In.RelrDyn && 
!In.RelrDyn->Relocs.empty()0
) {
1337
0
    addInSec(Config->UseAndroidRelrTags ? DT_ANDROID_RELR : DT_RELR,
1338
0
             In.RelrDyn);
1339
0
    addSize(Config->UseAndroidRelrTags ? DT_ANDROID_RELRSZ : DT_RELRSZ,
1340
0
            In.RelrDyn->getParent());
1341
0
    addInt(Config->UseAndroidRelrTags ? DT_ANDROID_RELRENT : DT_RELRENT,
1342
0
           sizeof(Elf_Relr));
1343
0
  }
1344
56
  // .rel[a].plt section usually consists of two parts, containing plt and
1345
56
  // iplt relocations. It is possible to have only iplt relocations in the
1346
56
  // output. In that case RelaPlt is empty and have zero offset, the same offset
1347
56
  // as RelaIplt have. And we still want to emit proper dynamic tags for that
1348
56
  // case, so here we always use RelaPlt as marker for the begining of
1349
56
  // .rel[a].plt section.
1350
56
  if (In.RelaPlt->getParent()->Live) {
1351
15
    addInSec(DT_JMPREL, In.RelaPlt);
1352
15
    Entries.push_back({DT_PLTRELSZ, addPltRelSz});
1353
15
    switch (Config->EMachine) {
1354
15
    case EM_MIPS:
1355
2
      addInSec(DT_MIPS_PLTGOT, In.GotPlt);
1356
2
      break;
1357
15
    case EM_SPARCV9:
1358
0
      addInSec(DT_PLTGOT, In.Plt);
1359
0
      break;
1360
15
    default:
1361
13
      addInSec(DT_PLTGOT, In.GotPlt);
1362
13
      break;
1363
15
    }
1364
15
    addInt(DT_PLTREL, Config->IsRela ? 
DT_RELA13
:
DT_REL2
);
1365
15
  }
1366
56
1367
56
  addInSec(DT_SYMTAB, In.DynSymTab);
1368
56
  addInt(DT_SYMENT, sizeof(Elf_Sym));
1369
56
  addInSec(DT_STRTAB, In.DynStrTab);
1370
56
  addInt(DT_STRSZ, In.DynStrTab->getSize());
1371
56
  if (!Config->ZText)
1372
2
    addInt(DT_TEXTREL, 0);
1373
56
  if (In.GnuHashTab)
1374
33
    addInSec(DT_GNU_HASH, In.GnuHashTab);
1375
56
  if (In.HashTab)
1376
56
    addInSec(DT_HASH, In.HashTab);
1377
56
1378
56
  if (Out::PreinitArray) {
1379
0
    addOutSec(DT_PREINIT_ARRAY, Out::PreinitArray);
1380
0
    addSize(DT_PREINIT_ARRAYSZ, Out::PreinitArray);
1381
0
  }
1382
56
  if (Out::InitArray) {
1383
0
    addOutSec(DT_INIT_ARRAY, Out::InitArray);
1384
0
    addSize(DT_INIT_ARRAYSZ, Out::InitArray);
1385
0
  }
1386
56
  if (Out::FiniArray) {
1387
0
    addOutSec(DT_FINI_ARRAY, Out::FiniArray);
1388
0
    addSize(DT_FINI_ARRAYSZ, Out::FiniArray);
1389
0
  }
1390
56
1391
56
  if (Symbol *B = Symtab->find(Config->Init))
1392
0
    if (B->isDefined())
1393
0
      addSym(DT_INIT, B);
1394
56
  if (Symbol *B = Symtab->find(Config->Fini))
1395
0
    if (B->isDefined())
1396
0
      addSym(DT_FINI, B);
1397
56
1398
56
  bool HasVerNeed = InX<ELFT>::VerNeed->getNeedNum() != 0;
1399
56
  if (HasVerNeed || In.VerDef)
1400
0
    addInSec(DT_VERSYM, InX<ELFT>::VerSym);
1401
56
  if (In.VerDef) {
1402
0
    addInSec(DT_VERDEF, In.VerDef);
1403
0
    addInt(DT_VERDEFNUM, getVerDefNum());
1404
0
  }
1405
56
  if (HasVerNeed) {
1406
0
    addInSec(DT_VERNEED, InX<ELFT>::VerNeed);
1407
0
    addInt(DT_VERNEEDNUM, InX<ELFT>::VerNeed->getNeedNum());
1408
0
  }
1409
56
1410
56
  if (Config->EMachine == EM_MIPS) {
1411
23
    addInt(DT_MIPS_RLD_VERSION, 1);
1412
23
    addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1413
23
    addInt(DT_MIPS_BASE_ADDRESS, Target->getImageBase());
1414
23
    addInt(DT_MIPS_SYMTABNO, In.DynSymTab->getNumSymbols());
1415
23
1416
23
    add(DT_MIPS_LOCAL_GOTNO, [] { return In.MipsGot->getLocalEntriesNum(); });
1417
23
1418
23
    if (const Symbol *B = In.MipsGot->getFirstGlobalEntry())
1419
6
      addInt(DT_MIPS_GOTSYM, B->DynsymIndex);
1420
17
    else
1421
17
      addInt(DT_MIPS_GOTSYM, In.DynSymTab->getNumSymbols());
1422
23
    addInSec(DT_PLTGOT, In.MipsGot);
1423
23
    if (In.MipsRldMap) {
1424
6
      if (!Config->Pie)
1425
5
        addInSec(DT_MIPS_RLD_MAP, In.MipsRldMap);
1426
6
      // Store the offset to the .rld_map section
1427
6
      // relative to the address of the tag.
1428
6
      addInSecRelative(DT_MIPS_RLD_MAP_REL, In.MipsRldMap);
1429
6
    }
1430
23
  }
1431
56
1432
56
  // Glink dynamic tag is required by the V2 abi if the plt section isn't empty.
1433
56
  if (Config->EMachine == EM_PPC64 && 
!In.Plt->empty()33
) {
1434
13
    // The Glink tag points to 32 bytes before the first lazy symbol resolution
1435
13
    // stub, which starts directly after the header.
1436
13
    Entries.push_back({DT_PPC64_GLINK, [=] {
1437
13
                         unsigned Offset = Target->PltHeaderSize - 32;
1438
13
                         return In.Plt->getVA(0) + Offset;
1439
13
                       }});
1440
13
  }
1441
56
1442
56
  addInt(DT_NULL, 0);
1443
56
1444
56
  getParent()->Link = this->Link;
1445
56
  this->Size = Entries.size() * this->Entsize;
1446
56
}
1447
1448
1.11k
template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1449
1.11k
  auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1450
1.11k
1451
10.9k
  for (std::pair<int32_t, std::function<uint64_t()>> &KV : Entries) {
1452
10.9k
    P->d_tag = KV.first;
1453
10.9k
    P->d_un.d_val = KV.second();
1454
10.9k
    ++P;
1455
10.9k
  }
1456
1.11k
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::writeTo(unsigned char*)
Line
Count
Source
1448
148
template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1449
148
  auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1450
148
1451
1.46k
  for (std::pair<int32_t, std::function<uint64_t()>> &KV : Entries) {
1452
1.46k
    P->d_tag = KV.first;
1453
1.46k
    P->d_un.d_val = KV.second();
1454
1.46k
    ++P;
1455
1.46k
  }
1456
148
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::writeTo(unsigned char*)
Line
Count
Source
1448
71
template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1449
71
  auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1450
71
1451
1.06k
  for (std::pair<int32_t, std::function<uint64_t()>> &KV : Entries) {
1452
1.06k
    P->d_tag = KV.first;
1453
1.06k
    P->d_un.d_val = KV.second();
1454
1.06k
    ++P;
1455
1.06k
  }
1456
71
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::writeTo(unsigned char*)
Line
Count
Source
1448
844
template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1449
844
  auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1450
844
1451
7.69k
  for (std::pair<int32_t, std::function<uint64_t()>> &KV : Entries) {
1452
7.69k
    P->d_tag = KV.first;
1453
7.69k
    P->d_un.d_val = KV.second();
1454
7.69k
    ++P;
1455
7.69k
  }
1456
844
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::writeTo(unsigned char*)
Line
Count
Source
1448
56
template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1449
56
  auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1450
56
1451
714
  for (std::pair<int32_t, std::function<uint64_t()>> &KV : Entries) {
1452
714
    P->d_tag = KV.first;
1453
714
    P->d_un.d_val = KV.second();
1454
714
    ++P;
1455
714
  }
1456
56
}
1457
1458
976
uint64_t DynamicReloc::getOffset() const {
1459
976
  return InputSec->getVA(OffsetInSec);
1460
976
}
1461
1462
647
int64_t DynamicReloc::computeAddend() const {
1463
647
  if (UseSymVA)
1464
169
    return Sym->getVA(Addend);
1465
478
  if (!OutputSec)
1466
478
    return Addend;
1467
0
  // See the comment in the DynamicReloc ctor.
1468
0
  return getMipsPageAddr(OutputSec->Addr) + Addend;
1469
0
}
1470
1471
1.64k
uint32_t DynamicReloc::getSymIndex() const {
1472
1.64k
  if (Sym && 
!UseSymVA1.58k
)
1473
1.13k
    return Sym->DynsymIndex;
1474
510
  return 0;
1475
510
}
1476
1477
RelocationBaseSection::RelocationBaseSection(StringRef Name, uint32_t Type,
1478
                                             int32_t DynamicTag,
1479
                                             int32_t SizeDynamicTag)
1480
    : SyntheticSection(SHF_ALLOC, Type, Config->Wordsize, Name),
1481
7.22k
      DynamicTag(DynamicTag), SizeDynamicTag(SizeDynamicTag) {}
1482
1483
void RelocationBaseSection::addReloc(RelType DynType, InputSectionBase *IS,
1484
136
                                     uint64_t OffsetInSec, Symbol *Sym) {
1485
136
  addReloc({DynType, IS, OffsetInSec, false, Sym, 0});
1486
136
}
1487
1488
void RelocationBaseSection::addReloc(RelType DynType,
1489
                                     InputSectionBase *InputSec,
1490
                                     uint64_t OffsetInSec, Symbol *Sym,
1491
                                     int64_t Addend, RelExpr Expr,
1492
426
                                     RelType Type) {
1493
426
  // Write the addends to the relocated address if required. We skip
1494
426
  // it if the written value would be zero.
1495
426
  if (Config->WriteAddends && 
(144
Expr != R_ADDEND144
||
Addend != 063
))
1496
95
    InputSec->Relocations.push_back({Expr, Type, OffsetInSec, Addend, Sym});
1497
426
  addReloc({DynType, InputSec, OffsetInSec, Expr != R_ADDEND, Sym, Addend});
1498
426
}
1499
1500
930
void RelocationBaseSection::addReloc(const DynamicReloc &Reloc) {
1501
930
  if (Reloc.Type == Target->RelativeRel)
1502
191
    ++NumRelativeRelocs;
1503
930
  Relocs.push_back(Reloc);
1504
930
}
1505
1506
486
void RelocationBaseSection::finalizeContents() {
1507
486
  // When linking glibc statically, .rel{,a}.plt contains R_*_IRELATIVE
1508
486
  // relocations due to IFUNC (e.g. strcpy). sh_link will be set to 0 in that
1509
486
  // case.
1510
486
  InputSection *SymTab = Config->Relocatable ? 
In.SymTab0
: In.DynSymTab;
1511
486
  if (SymTab && 
SymTab->getParent()470
)
1512
470
    getParent()->Link = SymTab->getParent()->SectionIndex;
1513
16
  else
1514
16
    getParent()->Link = 0;
1515
486
1516
486
  if (In.RelaIplt == this || 
In.RelaPlt == this458
)
1517
257
    getParent()->Info = In.GotPlt->getParent()->SectionIndex;
1518
486
}
1519
1520
RelrBaseSection::RelrBaseSection()
1521
    : SyntheticSection(SHF_ALLOC,
1522
                       Config->UseAndroidRelrTags ? SHT_ANDROID_RELR : SHT_RELR,
1523
4
                       Config->Wordsize, ".relr.dyn") {}
1524
1525
template <class ELFT>
1526
static void encodeDynamicReloc(typename ELFT::Rela *P,
1527
976
                               const DynamicReloc &Rel) {
1528
976
  if (Config->IsRela)
1529
647
    P->r_addend = Rel.computeAddend();
1530
976
  P->r_offset = Rel.getOffset();
1531
976
  P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
1532
976
}
SyntheticSections.cpp:void encodeDynamicReloc<llvm::object::ELFType<(llvm::support::endianness)1, false> >(llvm::object::ELFType<(llvm::support::endianness)1, false>::Rela*, lld::elf::DynamicReloc const&)
Line
Count
Source
1527
269
                               const DynamicReloc &Rel) {
1528
269
  if (Config->IsRela)
1529
3
    P->r_addend = Rel.computeAddend();
1530
269
  P->r_offset = Rel.getOffset();
1531
269
  P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
1532
269
}
SyntheticSections.cpp:void encodeDynamicReloc<llvm::object::ELFType<(llvm::support::endianness)0, false> >(llvm::object::ELFType<(llvm::support::endianness)0, false>::Rela*, lld::elf::DynamicReloc const&)
Line
Count
Source
1527
45
                               const DynamicReloc &Rel) {
1528
45
  if (Config->IsRela)
1529
1
    P->r_addend = Rel.computeAddend();
1530
45
  P->r_offset = Rel.getOffset();
1531
45
  P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
1532
45
}
SyntheticSections.cpp:void encodeDynamicReloc<llvm::object::ELFType<(llvm::support::endianness)1, true> >(llvm::object::ELFType<(llvm::support::endianness)1, true>::Rela*, lld::elf::DynamicReloc const&)
Line
Count
Source
1527
602
                               const DynamicReloc &Rel) {
1528
602
  if (Config->IsRela)
1529
602
    P->r_addend = Rel.computeAddend();
1530
602
  P->r_offset = Rel.getOffset();
1531
602
  P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
1532
602
}
SyntheticSections.cpp:void encodeDynamicReloc<llvm::object::ELFType<(llvm::support::endianness)0, true> >(llvm::object::ELFType<(llvm::support::endianness)0, true>::Rela*, lld::elf::DynamicReloc const&)
Line
Count
Source
1527
60
                               const DynamicReloc &Rel) {
1528
60
  if (Config->IsRela)
1529
41
    P->r_addend = Rel.computeAddend();
1530
60
  P->r_offset = Rel.getOffset();
1531
60
  P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
1532
60
}
1533
1534
template <class ELFT>
1535
RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
1536
    : RelocationBaseSection(Name, Config->IsRela ? SHT_RELA : SHT_REL,
1537
                            Config->IsRela ? DT_RELA : DT_REL,
1538
                            Config->IsRela ? DT_RELASZ : DT_RELSZ),
1539
7.21k
      Sort(Sort) {
1540
7.21k
  this->Entsize = Config->IsRela ? 
sizeof(Elf_Rela)5.82k
:
sizeof(Elf_Rel)1.38k
;
1541
7.21k
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::RelocationSection(llvm::StringRef, bool)
Line
Count
Source
1539
905
      Sort(Sort) {
1540
905
  this->Entsize = Config->IsRela ? 
sizeof(Elf_Rela)27
:
sizeof(Elf_Rel)878
;
1541
905
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::RelocationSection(llvm::StringRef, bool)
Line
Count
Source
1539
372
      Sort(Sort) {
1540
372
  this->Entsize = Config->IsRela ? 
sizeof(Elf_Rela)9
:
sizeof(Elf_Rel)363
;
1541
372
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::RelocationSection(llvm::StringRef, bool)
Line
Count
Source
1539
5.60k
      Sort(Sort) {
1540
5.60k
  this->Entsize = Config->IsRela ? 
sizeof(Elf_Rela)5.59k
:
sizeof(Elf_Rel)9
;
1541
5.60k
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::RelocationSection(llvm::StringRef, bool)
Line
Count
Source
1539
333
      Sort(Sort) {
1540
333
  this->Entsize = Config->IsRela ? 
sizeof(Elf_Rela)195
:
sizeof(Elf_Rel)138
;
1541
333
}
1542
1543
489
static bool compRelocations(const DynamicReloc &A, const DynamicReloc &B) {
1544
489
  bool AIsRel = A.Type == Target->RelativeRel;
1545
489
  bool BIsRel = B.Type == Target->RelativeRel;
1546
489
  if (AIsRel != BIsRel)
1547
156
    return AIsRel;
1548
333
  return A.getSymIndex() < B.getSymIndex();
1549
333
}
1550
1551
477
template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1552
477
  if (Sort)
1553
220
    std::stable_sort(Relocs.begin(), Relocs.end(), compRelocations);
1554
477
1555
856
  for (const DynamicReloc &Rel : Relocs) {
1556
856
    encodeDynamicReloc<ELFT>(reinterpret_cast<Elf_Rela *>(Buf), Rel);
1557
856
    Buf += Config->IsRela ? 
sizeof(Elf_Rela)581
:
sizeof(Elf_Rel)275
;
1558
856
  }
1559
477
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::writeTo(unsigned char*)
Line
Count
Source
1551
91
template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1552
91
  if (Sort)
1553
47
    std::stable_sort(Relocs.begin(), Relocs.end(), compRelocations);
1554
91
1555
215
  for (const DynamicReloc &Rel : Relocs) {
1556
215
    encodeDynamicReloc<ELFT>(reinterpret_cast<Elf_Rela *>(Buf), Rel);
1557
215
    Buf += Config->IsRela ? 
sizeof(Elf_Rela)3
:
sizeof(Elf_Rel)212
;
1558
215
  }
1559
91
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::writeTo(unsigned char*)
Line
Count
Source
1551
19
template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1552
19
  if (Sort)
1553
8
    std::stable_sort(Relocs.begin(), Relocs.end(), compRelocations);
1554
19
1555
45
  for (const DynamicReloc &Rel : Relocs) {
1556
45
    encodeDynamicReloc<ELFT>(reinterpret_cast<Elf_Rela *>(Buf), Rel);
1557
45
    Buf += Config->IsRela ? 
sizeof(Elf_Rela)1
:
sizeof(Elf_Rel)44
;
1558
45
  }
1559
19
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::writeTo(unsigned char*)
Line
Count
Source
1551
331
template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1552
331
  if (Sort)
1553
145
    std::stable_sort(Relocs.begin(), Relocs.end(), compRelocations);
1554
331
1555
536
  for (const DynamicReloc &Rel : Relocs) {
1556
536
    encodeDynamicReloc<ELFT>(reinterpret_cast<Elf_Rela *>(Buf), Rel);
1557
536
    Buf += Config->IsRela ? sizeof(Elf_Rela) : 
sizeof(Elf_Rel)0
;
1558
536
  }
1559
331
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::writeTo(unsigned char*)
Line
Count
Source
1551
36
template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1552
36
  if (Sort)
1553
20
    std::stable_sort(Relocs.begin(), Relocs.end(), compRelocations);
1554
36
1555
60
  for (const DynamicReloc &Rel : Relocs) {
1556
60
    encodeDynamicReloc<ELFT>(reinterpret_cast<Elf_Rela *>(Buf), Rel);
1557
60
    Buf += Config->IsRela ? 
sizeof(Elf_Rela)41
:
sizeof(Elf_Rel)19
;
1558
60
  }
1559
36
}
1560
1561
355
template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1562
355
  return this->Entsize * Relocs.size();
1563
355
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::getRelocOffset()
Line
Count
Source
1561
83
template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1562
83
  return this->Entsize * Relocs.size();
1563
83
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::getRelocOffset()
Line
Count
Source
1561
13
template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1562
13
  return this->Entsize * Relocs.size();
1563
13
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::getRelocOffset()
Line
Count
Source
1561
242
template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1562
242
  return this->Entsize * Relocs.size();
1563
242
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::getRelocOffset()
Line
Count
Source
1561
17
template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1562
17
  return this->Entsize * Relocs.size();
1563
17
}
1564
1565
template <class ELFT>
1566
AndroidPackedRelocationSection<ELFT>::AndroidPackedRelocationSection(
1567
    StringRef Name)
1568
    : RelocationBaseSection(
1569
          Name, Config->IsRela ? SHT_ANDROID_RELA : SHT_ANDROID_REL,
1570
          Config->IsRela ? DT_ANDROID_RELA : DT_ANDROID_REL,
1571
5
          Config->IsRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ) {
1572
5
  this->Entsize = 1;
1573
5
}
lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::AndroidPackedRelocationSection(llvm::StringRef)
Line
Count
Source
1571
1
          Config->IsRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ) {
1572
1
  this->Entsize = 1;
1573
1
}
Unexecuted instantiation: lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::AndroidPackedRelocationSection(llvm::StringRef)
lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::AndroidPackedRelocationSection(llvm::StringRef)
Line
Count
Source
1571
4
          Config->IsRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ) {
1572
4
  this->Entsize = 1;
1573
4
}
Unexecuted instantiation: lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::AndroidPackedRelocationSection(llvm::StringRef)
1574
1575
template <class ELFT>
1576
10
bool AndroidPackedRelocationSection<ELFT>::updateAllocSize() {
1577
10
  // This function computes the contents of an Android-format packed relocation
1578
10
  // section.
1579
10
  //
1580
10
  // This format compresses relocations by using relocation groups to factor out
1581
10
  // fields that are common between relocations and storing deltas from previous
1582
10
  // relocations in SLEB128 format (which has a short representation for small
1583
10
  // numbers). A good example of a relocation type with common fields is
1584
10
  // R_*_RELATIVE, which is normally used to represent function pointers in
1585
10
  // vtables. In the REL format, each relative relocation has the same r_info
1586
10
  // field, and is only different from other relative relocations in terms of
1587
10
  // the r_offset field. By sorting relocations by offset, grouping them by
1588
10
  // r_info and representing each relocation with only the delta from the
1589
10
  // previous offset, each 8-byte relocation can be compressed to as little as 1
1590
10
  // byte (or less with run-length encoding). This relocation packer was able to
1591
10
  // reduce the size of the relocation section in an Android Chromium DSO from
1592
10
  // 2,911,184 bytes to 174,693 bytes, or 6% of the original size.
1593
10
  //
1594
10
  // A relocation section consists of a header containing the literal bytes
1595
10
  // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two
1596
10
  // elements are the total number of relocations in the section and an initial
1597
10
  // r_offset value. The remaining elements define a sequence of relocation
1598
10
  // groups. Each relocation group starts with a header consisting of the
1599
10
  // following elements:
1600
10
  //
1601
10
  // - the number of relocations in the relocation group
1602
10
  // - flags for the relocation group
1603
10
  // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta
1604
10
  //   for each relocation in the group.
1605
10
  // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info
1606
10
  //   field for each relocation in the group.
1607
10
  // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and
1608
10
  //   RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for
1609
10
  //   each relocation in the group.
1610
10
  //
1611
10
  // Following the relocation group header are descriptions of each of the
1612
10
  // relocations in the group. They consist of the following elements:
1613
10
  //
1614
10
  // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset
1615
10
  //   delta for this relocation.
1616
10
  // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info
1617
10
  //   field for this relocation.
1618
10
  // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and
1619
10
  //   RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for
1620
10
  //   this relocation.
1621
10
1622
10
  size_t OldSize = RelocData.size();
1623
10
1624
10
  RelocData = {'A', 'P', 'S', '2'};
1625
10
  raw_svector_ostream OS(RelocData);
1626
250
  auto Add = [&](int64_t V) { encodeSLEB128(V, OS); };
lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::updateAllocSize()::'lambda'(long long)::operator()(long long) const
Line
Count
Source
1626
70
  auto Add = [&](int64_t V) { encodeSLEB128(V, OS); };
Unexecuted instantiation: lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::updateAllocSize()::'lambda'(long long)::operator()(long long) const
lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::updateAllocSize()::'lambda'(long long)::operator()(long long) const
Line
Count
Source
1626
180
  auto Add = [&](int64_t V) { encodeSLEB128(V, OS); };
Unexecuted instantiation: lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::updateAllocSize()::'lambda'(long long)::operator()(long long) const
1627
10
1628
10
  // The format header includes the number of relocations and the initial
1629
10
  // offset (we set this to zero because the first relocation group will
1630
10
  // perform the initial adjustment).
1631
10
  Add(Relocs.size());
1632
10
  Add(0);
1633
10
1634
10
  std::vector<Elf_Rela> Relatives, NonRelatives;
1635
10
1636
120
  for (const DynamicReloc &Rel : Relocs) {
1637
120
    Elf_Rela R;
1638
120
    encodeDynamicReloc<ELFT>(&R, Rel);
1639
120
1640
120
    if (R.getType(Config->IsMips64EL) == Target->RelativeRel)
1641
106
      Relatives.push_back(R);
1642
14
    else
1643
14
      NonRelatives.push_back(R);
1644
120
  }
1645
10
1646
100
  llvm::sort(Relatives, [](const Elf_Rel &A, const Elf_Rel &B) {
1647
100
    return A.r_offset < B.r_offset;
1648
100
  });
lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::updateAllocSize()::'lambda'(llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, false> const&, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, false> const&)::operator()(llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, false> const&, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, false> const&) const
Line
Count
Source
1646
48
  llvm::sort(Relatives, [](const Elf_Rel &A, const Elf_Rel &B) {
1647
48
    return A.r_offset < B.r_offset;
1648
48
  });
Unexecuted instantiation: lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::updateAllocSize()::'lambda'(llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, false> const&, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, false> const&)::operator()(llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, false> const&, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, false> const&) const
lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::updateAllocSize()::'lambda'(llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, false> const&, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, false> const&)::operator()(llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, false> const&, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, false> const&) const
Line
Count
Source
1646
52
  llvm::sort(Relatives, [](const Elf_Rel &A, const Elf_Rel &B) {
1647
52
    return A.r_offset < B.r_offset;
1648
52
  });
Unexecuted instantiation: lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::updateAllocSize()::'lambda'(llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, false> const&, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, false> const&)::operator()(llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, false> const&, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, false> const&) const
1649
10
1650
10
  // Try to find groups of relative relocations which are spaced one word
1651
10
  // apart from one another. These generally correspond to vtable entries. The
1652
10
  // format allows these groups to be encoded using a sort of run-length
1653
10
  // encoding, but each group will cost 7 bytes in addition to the offset from
1654
10
  // the previous group, so it is only profitable to do this for groups of
1655
10
  // size 8 or larger.
1656
10
  std::vector<Elf_Rela> UngroupedRelatives;
1657
10
  std::vector<std::vector<Elf_Rela>> RelativeGroups;
1658
32
  for (auto I = Relatives.begin(), E = Relatives.end(); I != E;) {
1659
22
    std::vector<Elf_Rela> Group;
1660
106
    do {
1661
106
      Group.push_back(*I++);
1662
106
    } while (I != E && 
(I - 1)->r_offset + Config->Wordsize == I->r_offset100
);
1663
22
1664
22
    if (Group.size() < 8)
1665
14
      UngroupedRelatives.insert(UngroupedRelatives.end(), Group.begin(),
1666
14
                                Group.end());
1667
8
    else
1668
8
      RelativeGroups.emplace_back(std::move(Group));
1669
22
  }
1670
10
1671
10
  unsigned HasAddendIfRela =
1672
10
      Config->IsRela ? 
RELOCATION_GROUP_HAS_ADDEND_FLAG8
:
02
;
1673
10
1674
10
  uint64_t Offset = 0;
1675
10
  uint64_t Addend = 0;
1676
10
1677
10
  // Emit the run-length encoding for the groups of adjacent relative
1678
10
  // relocations. Each group is represented using two groups in the packed
1679
10
  // format. The first is used to set the current offset to the start of the
1680
10
  // group (and also encodes the first relocation), and the second encodes the
1681
10
  // remaining relocations.
1682
10
  for (std::vector<Elf_Rela> &G : RelativeGroups) {
1683
8
    // The first relocation in the group.
1684
8
    Add(1);
1685
8
    Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1686
8
        RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1687
8
    Add(G[0].r_offset - Offset);
1688
8
    Add(Target->RelativeRel);
1689
8
    if (Config->IsRela) {
1690
4
      Add(G[0].r_addend - Addend);
1691
4
      Addend = G[0].r_addend;
1692
4
    }
1693
8
1694
8
    // The remaining relocations.
1695
8
    Add(G.size() - 1);
1696
8
    Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1697
8
        RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1698
8
    Add(Config->Wordsize);
1699
8
    Add(Target->RelativeRel);
1700
8
    if (Config->IsRela) {
1701
34
      for (auto I = G.begin() + 1, E = G.end(); I != E; 
++I30
) {
1702
30
        Add(I->r_addend - Addend);
1703
30
        Addend = I->r_addend;
1704
30
      }
1705
4
    }
1706
8
1707
8
    Offset = G.back().r_offset;
1708
8
  }
1709
10
1710
10
  // Now the ungrouped relatives.
1711
10
  if (!UngroupedRelatives.empty()) {
1712
6
    Add(UngroupedRelatives.size());
1713
6
    Add(RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1714
6
    Add(Target->RelativeRel);
1715
38
    for (Elf_Rela &R : UngroupedRelatives) {
1716
38
      Add(R.r_offset - Offset);
1717
38
      Offset = R.r_offset;
1718
38
      if (Config->IsRela) {
1719
22
        Add(R.r_addend - Addend);
1720
22
        Addend = R.r_addend;
1721
22
      }
1722
38
    }
1723
6
  }
1724
10
1725
10
  // Finally the non-relative relocations.
1726
10
  llvm::sort(NonRelatives, [](const Elf_Rela &A, const Elf_Rela &B) {
1727
6
    return A.r_offset < B.r_offset;
1728
6
  });
lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::updateAllocSize()::'lambda'(llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, true> const&, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, true> const&)::operator()(llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, true> const&, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, true> const&) const
Line
Count
Source
1726
2
  llvm::sort(NonRelatives, [](const Elf_Rela &A, const Elf_Rela &B) {
1727
2
    return A.r_offset < B.r_offset;
1728
2
  });
Unexecuted instantiation: lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::updateAllocSize()::'lambda'(llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, true> const&, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, true> const&)::operator()(llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, true> const&, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, true> const&) const
lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::updateAllocSize()::'lambda'(llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, true> const&, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, true> const&)::operator()(llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, true> const&, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, true> const&) const
Line
Count
Source
1726
4
  llvm::sort(NonRelatives, [](const Elf_Rela &A, const Elf_Rela &B) {
1727
4
    return A.r_offset < B.r_offset;
1728
4
  });
Unexecuted instantiation: lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::updateAllocSize()::'lambda'(llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, true> const&, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, true> const&)::operator()(llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, true> const&, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, true> const&) const
1729
10
  if (!NonRelatives.empty()) {
1730
8
    Add(NonRelatives.size());
1731
8
    Add(HasAddendIfRela);
1732
14
    for (Elf_Rela &R : NonRelatives) {
1733
14
      Add(R.r_offset - Offset);
1734
14
      Offset = R.r_offset;
1735
14
      Add(R.r_info);
1736
14
      if (Config->IsRela) {
1737
10
        Add(R.r_addend - Addend);
1738
10
        Addend = R.r_addend;
1739
10
      }
1740
14
    }
1741
8
  }
1742
10
1743
10
  // Don't allow the section to shrink; otherwise the size of the section can
1744
10
  // oscillate infinitely.
1745
10
  if (RelocData.size() < OldSize)
1746
1
    RelocData.append(OldSize - RelocData.size(), 0);
1747
10
1748
10
  // Returns whether the section size changed. We need to keep recomputing both
1749
10
  // section layout and the contents of this section until the size converges
1750
10
  // because changing this section's size can affect section layout, which in
1751
10
  // turn can affect the sizes of the LEB-encoded integers stored in this
1752
10
  // section.
1753
10
  return RelocData.size() != OldSize;
1754
10
}
lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::updateAllocSize()
Line
Count
Source
1576
2
bool AndroidPackedRelocationSection<ELFT>::updateAllocSize() {
1577
2
  // This function computes the contents of an Android-format packed relocation
1578
2
  // section.
1579
2
  //
1580
2
  // This format compresses relocations by using relocation groups to factor out
1581
2
  // fields that are common between relocations and storing deltas from previous
1582
2
  // relocations in SLEB128 format (which has a short representation for small
1583
2
  // numbers). A good example of a relocation type with common fields is
1584
2
  // R_*_RELATIVE, which is normally used to represent function pointers in
1585
2
  // vtables. In the REL format, each relative relocation has the same r_info
1586
2
  // field, and is only different from other relative relocations in terms of
1587
2
  // the r_offset field. By sorting relocations by offset, grouping them by
1588
2
  // r_info and representing each relocation with only the delta from the
1589
2
  // previous offset, each 8-byte relocation can be compressed to as little as 1
1590
2
  // byte (or less with run-length encoding). This relocation packer was able to
1591
2
  // reduce the size of the relocation section in an Android Chromium DSO from
1592
2
  // 2,911,184 bytes to 174,693 bytes, or 6% of the original size.
1593
2
  //
1594
2
  // A relocation section consists of a header containing the literal bytes
1595
2
  // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two
1596
2
  // elements are the total number of relocations in the section and an initial
1597
2
  // r_offset value. The remaining elements define a sequence of relocation
1598
2
  // groups. Each relocation group starts with a header consisting of the
1599
2
  // following elements:
1600
2
  //
1601
2
  // - the number of relocations in the relocation group
1602
2
  // - flags for the relocation group
1603
2
  // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta
1604
2
  //   for each relocation in the group.
1605
2
  // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info
1606
2
  //   field for each relocation in the group.
1607
2
  // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and
1608
2
  //   RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for
1609
2
  //   each relocation in the group.
1610
2
  //
1611
2
  // Following the relocation group header are descriptions of each of the
1612
2
  // relocations in the group. They consist of the following elements:
1613
2
  //
1614
2
  // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset
1615
2
  //   delta for this relocation.
1616
2
  // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info
1617
2
  //   field for this relocation.
1618
2
  // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and
1619
2
  //   RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for
1620
2
  //   this relocation.
1621
2
1622
2
  size_t OldSize = RelocData.size();
1623
2
1624
2
  RelocData = {'A', 'P', 'S', '2'};
1625
2
  raw_svector_ostream OS(RelocData);
1626
2
  auto Add = [&](int64_t V) { encodeSLEB128(V, OS); };
1627
2
1628
2
  // The format header includes the number of relocations and the initial
1629
2
  // offset (we set this to zero because the first relocation group will
1630
2
  // perform the initial adjustment).
1631
2
  Add(Relocs.size());
1632
2
  Add(0);
1633
2
1634
2
  std::vector<Elf_Rela> Relatives, NonRelatives;
1635
2
1636
54
  for (const DynamicReloc &Rel : Relocs) {
1637
54
    Elf_Rela R;
1638
54
    encodeDynamicReloc<ELFT>(&R, Rel);
1639
54
1640
54
    if (R.getType(Config->IsMips64EL) == Target->RelativeRel)
1641
50
      Relatives.push_back(R);
1642
4
    else
1643
4
      NonRelatives.push_back(R);
1644
54
  }
1645
2
1646
2
  llvm::sort(Relatives, [](const Elf_Rel &A, const Elf_Rel &B) {
1647
2
    return A.r_offset < B.r_offset;
1648
2
  });
1649
2
1650
2
  // Try to find groups of relative relocations which are spaced one word
1651
2
  // apart from one another. These generally correspond to vtable entries. The
1652
2
  // format allows these groups to be encoded using a sort of run-length
1653
2
  // encoding, but each group will cost 7 bytes in addition to the offset from
1654
2
  // the previous group, so it is only profitable to do this for groups of
1655
2
  // size 8 or larger.
1656
2
  std::vector<Elf_Rela> UngroupedRelatives;
1657
2
  std::vector<std::vector<Elf_Rela>> RelativeGroups;
1658
10
  for (auto I = Relatives.begin(), E = Relatives.end(); I != E;) {
1659
8
    std::vector<Elf_Rela> Group;
1660
50
    do {
1661
50
      Group.push_back(*I++);
1662
50
    } while (I != E && 
(I - 1)->r_offset + Config->Wordsize == I->r_offset48
);
1663
8
1664
8
    if (Group.size() < 8)
1665
4
      UngroupedRelatives.insert(UngroupedRelatives.end(), Group.begin(),
1666
4
                                Group.end());
1667
4
    else
1668
4
      RelativeGroups.emplace_back(std::move(Group));
1669
8
  }
1670
2
1671
2
  unsigned HasAddendIfRela =
1672
2
      Config->IsRela ? 
RELOCATION_GROUP_HAS_ADDEND_FLAG0
: 0;
1673
2
1674
2
  uint64_t Offset = 0;
1675
2
  uint64_t Addend = 0;
1676
2
1677
2
  // Emit the run-length encoding for the groups of adjacent relative
1678
2
  // relocations. Each group is represented using two groups in the packed
1679
2
  // format. The first is used to set the current offset to the start of the
1680
2
  // group (and also encodes the first relocation), and the second encodes the
1681
2
  // remaining relocations.
1682
4
  for (std::vector<Elf_Rela> &G : RelativeGroups) {
1683
4
    // The first relocation in the group.
1684
4
    Add(1);
1685
4
    Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1686
4
        RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1687
4
    Add(G[0].r_offset - Offset);
1688
4
    Add(Target->RelativeRel);
1689
4
    if (Config->IsRela) {
1690
0
      Add(G[0].r_addend - Addend);
1691
0
      Addend = G[0].r_addend;
1692
0
    }
1693
4
1694
4
    // The remaining relocations.
1695
4
    Add(G.size() - 1);
1696
4
    Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1697
4
        RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1698
4
    Add(Config->Wordsize);
1699
4
    Add(Target->RelativeRel);
1700
4
    if (Config->IsRela) {
1701
0
      for (auto I = G.begin() + 1, E = G.end(); I != E; ++I) {
1702
0
        Add(I->r_addend - Addend);
1703
0
        Addend = I->r_addend;
1704
0
      }
1705
0
    }
1706
4
1707
4
    Offset = G.back().r_offset;
1708
4
  }
1709
2
1710
2
  // Now the ungrouped relatives.
1711
2
  if (!UngroupedRelatives.empty()) {
1712
2
    Add(UngroupedRelatives.size());
1713
2
    Add(RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1714
2
    Add(Target->RelativeRel);
1715
16
    for (Elf_Rela &R : UngroupedRelatives) {
1716
16
      Add(R.r_offset - Offset);
1717
16
      Offset = R.r_offset;
1718
16
      if (Config->IsRela) {
1719
0
        Add(R.r_addend - Addend);
1720
0
        Addend = R.r_addend;
1721
0
      }
1722
16
    }
1723
2
  }
1724
2
1725
2
  // Finally the non-relative relocations.
1726
2
  llvm::sort(NonRelatives, [](const Elf_Rela &A, const Elf_Rela &B) {
1727
2
    return A.r_offset < B.r_offset;
1728
2
  });
1729
2
  if (!NonRelatives.empty()) {
1730
2
    Add(NonRelatives.size());
1731
2
    Add(HasAddendIfRela);
1732
4
    for (Elf_Rela &R : NonRelatives) {
1733
4
      Add(R.r_offset - Offset);
1734
4
      Offset = R.r_offset;
1735
4
      Add(R.r_info);
1736
4
      if (Config->IsRela) {
1737
0
        Add(R.r_addend - Addend);
1738
0
        Addend = R.r_addend;
1739
0
      }
1740
4
    }
1741
2
  }
1742
2
1743
2
  // Don't allow the section to shrink; otherwise the size of the section can
1744
2
  // oscillate infinitely.
1745
2
  if (RelocData.size() < OldSize)
1746
0
    RelocData.append(OldSize - RelocData.size(), 0);
1747
2
1748
2
  // Returns whether the section size changed. We need to keep recomputing both
1749
2
  // section layout and the contents of this section until the size converges
1750
2
  // because changing this section's size can affect section layout, which in
1751
2
  // turn can affect the sizes of the LEB-encoded integers stored in this
1752
2
  // section.
1753
2
  return RelocData.size() != OldSize;
1754
2
}
Unexecuted instantiation: lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::updateAllocSize()
lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::updateAllocSize()
Line
Count
Source
1576
8
bool AndroidPackedRelocationSection<ELFT>::updateAllocSize() {
1577
8
  // This function computes the contents of an Android-format packed relocation
1578
8
  // section.
1579
8
  //
1580
8
  // This format compresses relocations by using relocation groups to factor out
1581
8
  // fields that are common between relocations and storing deltas from previous
1582
8
  // relocations in SLEB128 format (which has a short representation for small
1583
8
  // numbers). A good example of a relocation type with common fields is
1584
8
  // R_*_RELATIVE, which is normally used to represent function pointers in
1585
8
  // vtables. In the REL format, each relative relocation has the same r_info
1586
8
  // field, and is only different from other relative relocations in terms of
1587
8
  // the r_offset field. By sorting relocations by offset, grouping them by