Coverage Report

Created: 2018-01-17 21:32

/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 "Strings.h"
24
#include "SymbolTable.h"
25
#include "Symbols.h"
26
#include "Target.h"
27
#include "Writer.h"
28
#include "lld/Common/ErrorHandler.h"
29
#include "lld/Common/Memory.h"
30
#include "lld/Common/Threads.h"
31
#include "lld/Common/Version.h"
32
#include "llvm/BinaryFormat/Dwarf.h"
33
#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
34
#include "llvm/Object/Decompressor.h"
35
#include "llvm/Object/ELFObjectFile.h"
36
#include "llvm/Support/Endian.h"
37
#include "llvm/Support/LEB128.h"
38
#include "llvm/Support/MD5.h"
39
#include "llvm/Support/RandomNumberGenerator.h"
40
#include "llvm/Support/SHA1.h"
41
#include "llvm/Support/xxhash.h"
42
#include <cstdlib>
43
#include <thread>
44
45
using namespace llvm;
46
using namespace llvm::dwarf;
47
using namespace llvm::ELF;
48
using namespace llvm::object;
49
using namespace llvm::support;
50
using namespace llvm::support::endian;
51
52
using namespace lld;
53
using namespace lld::elf;
54
55
constexpr size_t MergeNoTailSection::NumShards;
56
57
3.92k
static void write32(void *Buf, uint32_t Val) {
58
3.92k
  endian::write32(Buf, Val, Config->Endianness);
59
3.92k
}
60
61
11.1k
uint64_t SyntheticSection::getVA() const {
62
11.1k
  if (OutputSection *Sec = getParent())
63
11.1k
    return Sec->Addr + OutSecOff;
64
0
  return 0;
65
0
}
66
67
// Returns an LLD version string.
68
907
static ArrayRef<uint8_t> getVersion() {
69
907
  // Check LLD_VERSION first for ease of testing.
70
907
  // You can get consitent output by using the environment variable.
71
907
  // This is only for testing.
72
907
  StringRef S = getenv("LLD_VERSION");
73
907
  if (S.empty())
74
0
    S = Saver.save(Twine("Linker: ") + getLLDVersion());
75
907
76
907
  // +1 to include the terminating '\0'.
77
907
  return {(const uint8_t *)S.data(), S.size() + 1};
78
907
}
79
80
// Creates a .comment section containing LLD version info.
81
// With this feature, you can identify LLD-generated binaries easily
82
// by "readelf --string-dump .comment <file>".
83
// The returned object is a mergeable string section.
84
907
MergeInputSection *elf::createCommentSection() {
85
907
  return make<MergeInputSection>(SHF_MERGE | SHF_STRINGS, SHT_PROGBITS, 1,
86
907
                                 getVersion(), ".comment");
87
907
}
88
89
// .MIPS.abiflags section.
90
template <class ELFT>
91
MipsAbiFlagsSection<ELFT>::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags)
92
    : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"),
93
73
      Flags(Flags) {
94
73
  this->Entsize = sizeof(Elf_Mips_ABIFlags);
95
73
}
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
93
4
      Flags(Flags) {
94
4
  this->Entsize = sizeof(Elf_Mips_ABIFlags);
95
4
}
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
93
50
      Flags(Flags) {
94
50
  this->Entsize = sizeof(Elf_Mips_ABIFlags);
95
50
}
Unexecuted instantiation: 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> >)
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
93
19
      Flags(Flags) {
94
19
  this->Entsize = sizeof(Elf_Mips_ABIFlags);
95
19
}
96
97
70
template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
98
70
  memcpy(Buf, &Flags, sizeof(Flags));
99
70
}
lld::elf::MipsAbiFlagsSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::writeTo(unsigned char*)
Line
Count
Source
97
4
template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
98
4
  memcpy(Buf, &Flags, sizeof(Flags));
99
4
}
lld::elf::MipsAbiFlagsSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::writeTo(unsigned char*)
Line
Count
Source
97
48
template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
98
48
  memcpy(Buf, &Flags, sizeof(Flags));
99
48
}
Unexecuted instantiation: lld::elf::MipsAbiFlagsSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::writeTo(unsigned char*)
lld::elf::MipsAbiFlagsSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::writeTo(unsigned char*)
Line
Count
Source
97
18
template <class ELFT> void MipsAbiFlagsSection<ELFT>::writeTo(uint8_t *Buf) {
98
18
  memcpy(Buf, &Flags, sizeof(Flags));
99
18
}
100
101
template <class ELFT>
102
74
MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
103
74
  Elf_Mips_ABIFlags Flags = {};
104
74
  bool Create = false;
105
74
106
756
  for (InputSectionBase *Sec : InputSections) {
107
756
    if (Sec->Type != SHT_MIPS_ABIFLAGS)
108
658
      continue;
109
98
    Sec->Live = false;
110
98
    Create = true;
111
98
112
98
    std::string Filename = toString(Sec->File);
113
98
    const size_t Size = Sec->Data.size();
114
98
    // Older version of BFD (such as the default FreeBSD linker) concatenate
115
98
    // .MIPS.abiflags instead of merging. To allow for this case (or potential
116
98
    // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
117
98
    if (Size < sizeof(Elf_Mips_ABIFlags)) {
118
0
      error(Filename + ": invalid size of .MIPS.abiflags section: got " +
119
0
            Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
120
0
      return nullptr;
121
0
    }
122
98
    auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
123
98
    if (S->version != 0) {
124
0
      error(Filename + ": unexpected .MIPS.abiflags version " +
125
0
            Twine(S->version));
126
0
      return nullptr;
127
0
    }
128
98
129
98
    // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
130
98
    // select the highest number of ISA/Rev/Ext.
131
98
    Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
132
98
    Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
133
98
    Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
134
98
    Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
135
98
    Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
136
98
    Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
137
98
    Flags.ases |= S->ases;
138
98
    Flags.flags1 |= S->flags1;
139
98
    Flags.flags2 |= S->flags2;
140
98
    Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
141
98
  };
142
74
143
74
  if (Create)
144
73
    return make<MipsAbiFlagsSection<ELFT>>(Flags);
145
1
  return nullptr;
146
1
}
lld::elf::MipsAbiFlagsSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::create()
Line
Count
Source
102
4
MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
103
4
  Elf_Mips_ABIFlags Flags = {};
104
4
  bool Create = false;
105
4
106
38
  for (InputSectionBase *Sec : InputSections) {
107
38
    if (Sec->Type != SHT_MIPS_ABIFLAGS)
108
33
      continue;
109
5
    Sec->Live = false;
110
5
    Create = true;
111
5
112
5
    std::string Filename = toString(Sec->File);
113
5
    const size_t Size = Sec->Data.size();
114
5
    // Older version of BFD (such as the default FreeBSD linker) concatenate
115
5
    // .MIPS.abiflags instead of merging. To allow for this case (or potential
116
5
    // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
117
5
    if (Size < sizeof(Elf_Mips_ABIFlags)) {
118
0
      error(Filename + ": invalid size of .MIPS.abiflags section: got " +
119
0
            Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
120
0
      return nullptr;
121
0
    }
122
5
    auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
123
5
    if (S->version != 0) {
124
0
      error(Filename + ": unexpected .MIPS.abiflags version " +
125
0
            Twine(S->version));
126
0
      return nullptr;
127
0
    }
128
5
129
5
    // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
130
5
    // select the highest number of ISA/Rev/Ext.
131
5
    Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
132
5
    Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
133
5
    Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
134
5
    Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
135
5
    Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
136
5
    Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
137
5
    Flags.ases |= S->ases;
138
5
    Flags.flags1 |= S->flags1;
139
5
    Flags.flags2 |= S->flags2;
140
5
    Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
141
5
  };
142
4
143
4
  if (Create)
144
4
    return make<MipsAbiFlagsSection<ELFT>>(Flags);
145
0
  return nullptr;
146
0
}
lld::elf::MipsAbiFlagsSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::create()
Line
Count
Source
102
51
MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
103
51
  Elf_Mips_ABIFlags Flags = {};
104
51
  bool Create = false;
105
51
106
535
  for (InputSectionBase *Sec : InputSections) {
107
535
    if (Sec->Type != SHT_MIPS_ABIFLAGS)
108
465
      continue;
109
70
    Sec->Live = false;
110
70
    Create = true;
111
70
112
70
    std::string Filename = toString(Sec->File);
113
70
    const size_t Size = Sec->Data.size();
114
70
    // Older version of BFD (such as the default FreeBSD linker) concatenate
115
70
    // .MIPS.abiflags instead of merging. To allow for this case (or potential
116
70
    // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
117
70
    if (Size < sizeof(Elf_Mips_ABIFlags)) {
118
0
      error(Filename + ": invalid size of .MIPS.abiflags section: got " +
119
0
            Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
120
0
      return nullptr;
121
0
    }
122
70
    auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
123
70
    if (S->version != 0) {
124
0
      error(Filename + ": unexpected .MIPS.abiflags version " +
125
0
            Twine(S->version));
126
0
      return nullptr;
127
0
    }
128
70
129
70
    // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
130
70
    // select the highest number of ISA/Rev/Ext.
131
70
    Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
132
70
    Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
133
70
    Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
134
70
    Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
135
70
    Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
136
70
    Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
137
70
    Flags.ases |= S->ases;
138
70
    Flags.flags1 |= S->flags1;
139
70
    Flags.flags2 |= S->flags2;
140
70
    Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
141
70
  };
142
51
143
51
  if (Create)
144
50
    return make<MipsAbiFlagsSection<ELFT>>(Flags);
145
1
  return nullptr;
146
1
}
Unexecuted instantiation: lld::elf::MipsAbiFlagsSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::create()
lld::elf::MipsAbiFlagsSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::create()
Line
Count
Source
102
19
MipsAbiFlagsSection<ELFT> *MipsAbiFlagsSection<ELFT>::create() {
103
19
  Elf_Mips_ABIFlags Flags = {};
104
19
  bool Create = false;
105
19
106
183
  for (InputSectionBase *Sec : InputSections) {
107
183
    if (Sec->Type != SHT_MIPS_ABIFLAGS)
108
160
      continue;
109
23
    Sec->Live = false;
110
23
    Create = true;
111
23
112
23
    std::string Filename = toString(Sec->File);
113
23
    const size_t Size = Sec->Data.size();
114
23
    // Older version of BFD (such as the default FreeBSD linker) concatenate
115
23
    // .MIPS.abiflags instead of merging. To allow for this case (or potential
116
23
    // zero padding) we ignore everything after the first Elf_Mips_ABIFlags
117
23
    if (Size < sizeof(Elf_Mips_ABIFlags)) {
118
0
      error(Filename + ": invalid size of .MIPS.abiflags section: got " +
119
0
            Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags)));
120
0
      return nullptr;
121
0
    }
122
23
    auto *S = reinterpret_cast<const Elf_Mips_ABIFlags *>(Sec->Data.data());
123
23
    if (S->version != 0) {
124
0
      error(Filename + ": unexpected .MIPS.abiflags version " +
125
0
            Twine(S->version));
126
0
      return nullptr;
127
0
    }
128
23
129
23
    // LLD checks ISA compatibility in calcMipsEFlags(). Here we just
130
23
    // select the highest number of ISA/Rev/Ext.
131
23
    Flags.isa_level = std::max(Flags.isa_level, S->isa_level);
132
23
    Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev);
133
23
    Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext);
134
23
    Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size);
135
23
    Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size);
136
23
    Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size);
137
23
    Flags.ases |= S->ases;
138
23
    Flags.flags1 |= S->flags1;
139
23
    Flags.flags2 |= S->flags2;
140
23
    Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename);
141
23
  };
142
19
143
19
  if (Create)
144
19
    return make<MipsAbiFlagsSection<ELFT>>(Flags);
145
0
  return nullptr;
146
0
}
147
148
// .MIPS.options section.
149
template <class ELFT>
150
MipsOptionsSection<ELFT>::MipsOptionsSection(Elf_Mips_RegInfo Reginfo)
151
    : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"),
152
19
      Reginfo(Reginfo) {
153
19
  this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
154
19
}
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> >)
Unexecuted instantiation: 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> >)
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
152
19
      Reginfo(Reginfo) {
153
19
  this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
154
19
}
155
156
18
template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
157
18
  auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
158
18
  Options->kind = ODK_REGINFO;
159
18
  Options->size = getSize();
160
18
161
18
  if (!Config->Relocatable)
162
18
    Reginfo.ri_gp_value = InX::MipsGot->getGp();
163
18
  memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
164
18
}
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*)
Unexecuted instantiation: lld::elf::MipsOptionsSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::writeTo(unsigned char*)
lld::elf::MipsOptionsSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::writeTo(unsigned char*)
Line
Count
Source
156
18
template <class ELFT> void MipsOptionsSection<ELFT>::writeTo(uint8_t *Buf) {
157
18
  auto *Options = reinterpret_cast<Elf_Mips_Options *>(Buf);
158
18
  Options->kind = ODK_REGINFO;
159
18
  Options->size = getSize();
160
18
161
18
  if (!Config->Relocatable)
162
18
    Reginfo.ri_gp_value = InX::MipsGot->getGp();
163
18
  memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo));
164
18
}
165
166
template <class ELFT>
167
74
MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
168
74
  // N64 ABI only.
169
74
  if (!ELFT::Is64Bits)
170
55
    return nullptr;
171
19
172
19
  std::vector<InputSectionBase *> Sections;
173
19
  for (InputSectionBase *Sec : InputSections)
174
202
    if (Sec->Type == SHT_MIPS_OPTIONS)
175
23
      Sections.push_back(Sec);
176
19
177
19
  if (Sections.empty())
178
0
    return nullptr;
179
19
180
19
  Elf_Mips_RegInfo Reginfo = {};
181
23
  for (InputSectionBase *Sec : Sections) {
182
23
    Sec->Live = false;
183
23
184
23
    std::string Filename = toString(Sec->File);
185
23
    ArrayRef<uint8_t> D = Sec->Data;
186
23
187
23
    while (!D.empty()) {
188
23
      if (D.size() < sizeof(Elf_Mips_Options)) {
189
0
        error(Filename + ": invalid size of .MIPS.options section");
190
0
        break;
191
0
      }
192
23
193
23
      auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
194
23
      if (Opt->kind == ODK_REGINFO) {
195
23
        if (Config->Relocatable && 
Opt->getRegInfo().ri_gp_value0
)
196
0
          error(Filename + ": unsupported non-zero ri_gp_value");
197
23
        Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
198
23
        Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
199
23
        break;
200
23
      }
201
0
202
0
      if (!Opt->size)
203
0
        fatal(Filename + ": zero option descriptor size");
204
0
      D = D.slice(Opt->size);
205
0
    }
206
23
  };
207
19
208
19
  return make<MipsOptionsSection<ELFT>>(Reginfo);
209
19
}
lld::elf::MipsOptionsSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::create()
Line
Count
Source
167
4
MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
168
4
  // N64 ABI only.
169
4
  if (!ELFT::Is64Bits)
170
4
    return nullptr;
171
0
172
0
  std::vector<InputSectionBase *> Sections;
173
0
  for (InputSectionBase *Sec : InputSections)
174
0
    if (Sec->Type == SHT_MIPS_OPTIONS)
175
0
      Sections.push_back(Sec);
176
0
177
0
  if (Sections.empty())
178
0
    return nullptr;
179
0
180
0
  Elf_Mips_RegInfo Reginfo = {};
181
0
  for (InputSectionBase *Sec : Sections) {
182
0
    Sec->Live = false;
183
0
184
0
    std::string Filename = toString(Sec->File);
185
0
    ArrayRef<uint8_t> D = Sec->Data;
186
0
187
0
    while (!D.empty()) {
188
0
      if (D.size() < sizeof(Elf_Mips_Options)) {
189
0
        error(Filename + ": invalid size of .MIPS.options section");
190
0
        break;
191
0
      }
192
0
193
0
      auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
194
0
      if (Opt->kind == ODK_REGINFO) {
195
0
        if (Config->Relocatable && Opt->getRegInfo().ri_gp_value)
196
0
          error(Filename + ": unsupported non-zero ri_gp_value");
197
0
        Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
198
0
        Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
199
0
        break;
200
0
      }
201
0
202
0
      if (!Opt->size)
203
0
        fatal(Filename + ": zero option descriptor size");
204
0
      D = D.slice(Opt->size);
205
0
    }
206
0
  };
207
0
208
0
  return make<MipsOptionsSection<ELFT>>(Reginfo);
209
0
}
lld::elf::MipsOptionsSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::create()
Line
Count
Source
167
51
MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
168
51
  // N64 ABI only.
169
51
  if (!ELFT::Is64Bits)
170
51
    return nullptr;
171
0
172
0
  std::vector<InputSectionBase *> Sections;
173
0
  for (InputSectionBase *Sec : InputSections)
174
0
    if (Sec->Type == SHT_MIPS_OPTIONS)
175
0
      Sections.push_back(Sec);
176
0
177
0
  if (Sections.empty())
178
0
    return nullptr;
179
0
180
0
  Elf_Mips_RegInfo Reginfo = {};
181
0
  for (InputSectionBase *Sec : Sections) {
182
0
    Sec->Live = false;
183
0
184
0
    std::string Filename = toString(Sec->File);
185
0
    ArrayRef<uint8_t> D = Sec->Data;
186
0
187
0
    while (!D.empty()) {
188
0
      if (D.size() < sizeof(Elf_Mips_Options)) {
189
0
        error(Filename + ": invalid size of .MIPS.options section");
190
0
        break;
191
0
      }
192
0
193
0
      auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
194
0
      if (Opt->kind == ODK_REGINFO) {
195
0
        if (Config->Relocatable && Opt->getRegInfo().ri_gp_value)
196
0
          error(Filename + ": unsupported non-zero ri_gp_value");
197
0
        Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
198
0
        Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
199
0
        break;
200
0
      }
201
0
202
0
      if (!Opt->size)
203
0
        fatal(Filename + ": zero option descriptor size");
204
0
      D = D.slice(Opt->size);
205
0
    }
206
0
  };
207
0
208
0
  return make<MipsOptionsSection<ELFT>>(Reginfo);
209
0
}
Unexecuted instantiation: lld::elf::MipsOptionsSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::create()
lld::elf::MipsOptionsSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::create()
Line
Count
Source
167
19
MipsOptionsSection<ELFT> *MipsOptionsSection<ELFT>::create() {
168
19
  // N64 ABI only.
169
19
  if (!ELFT::Is64Bits)
170
0
    return nullptr;
171
19
172
19
  std::vector<InputSectionBase *> Sections;
173
19
  for (InputSectionBase *Sec : InputSections)
174
202
    if (Sec->Type == SHT_MIPS_OPTIONS)
175
23
      Sections.push_back(Sec);
176
19
177
19
  if (Sections.empty())
178
0
    return nullptr;
179
19
180
19
  Elf_Mips_RegInfo Reginfo = {};
181
23
  for (InputSectionBase *Sec : Sections) {
182
23
    Sec->Live = false;
183
23
184
23
    std::string Filename = toString(Sec->File);
185
23
    ArrayRef<uint8_t> D = Sec->Data;
186
23
187
23
    while (!D.empty()) {
188
23
      if (D.size() < sizeof(Elf_Mips_Options)) {
189
0
        error(Filename + ": invalid size of .MIPS.options section");
190
0
        break;
191
0
      }
192
23
193
23
      auto *Opt = reinterpret_cast<const Elf_Mips_Options *>(D.data());
194
23
      if (Opt->kind == ODK_REGINFO) {
195
23
        if (Config->Relocatable && 
Opt->getRegInfo().ri_gp_value0
)
196
0
          error(Filename + ": unsupported non-zero ri_gp_value");
197
23
        Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask;
198
23
        Sec->getFile<ELFT>()->MipsGp0 = Opt->getRegInfo().ri_gp_value;
199
23
        break;
200
23
      }
201
0
202
0
      if (!Opt->size)
203
0
        fatal(Filename + ": zero option descriptor size");
204
0
      D = D.slice(Opt->size);
205
0
    }
206
23
  };
207
19
208
19
  return make<MipsOptionsSection<ELFT>>(Reginfo);
209
19
}
210
211
// MIPS .reginfo section.
212
template <class ELFT>
213
MipsReginfoSection<ELFT>::MipsReginfoSection(Elf_Mips_RegInfo Reginfo)
214
    : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"),
215
54
      Reginfo(Reginfo) {
216
54
  this->Entsize = sizeof(Elf_Mips_RegInfo);
217
54
}
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
215
4
      Reginfo(Reginfo) {
216
4
  this->Entsize = sizeof(Elf_Mips_RegInfo);
217
4
}
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
215
50
      Reginfo(Reginfo) {
216
50
  this->Entsize = sizeof(Elf_Mips_RegInfo);
217
50
}
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> >)
218
219
52
template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
220
52
  if (!Config->Relocatable)
221
48
    Reginfo.ri_gp_value = InX::MipsGot->getGp();
222
52
  memcpy(Buf, &Reginfo, sizeof(Reginfo));
223
52
}
lld::elf::MipsReginfoSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::writeTo(unsigned char*)
Line
Count
Source
219
4
template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
220
4
  if (!Config->Relocatable)
221
4
    Reginfo.ri_gp_value = InX::MipsGot->getGp();
222
4
  memcpy(Buf, &Reginfo, sizeof(Reginfo));
223
4
}
lld::elf::MipsReginfoSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::writeTo(unsigned char*)
Line
Count
Source
219
48
template <class ELFT> void MipsReginfoSection<ELFT>::writeTo(uint8_t *Buf) {
220
48
  if (!Config->Relocatable)
221
44
    Reginfo.ri_gp_value = InX::MipsGot->getGp();
222
48
  memcpy(Buf, &Reginfo, sizeof(Reginfo));
223
48
}
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*)
224
225
template <class ELFT>
226
74
MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
227
74
  // Section should be alive for O32 and N32 ABIs only.
228
74
  if (ELFT::Is64Bits)
229
19
    return nullptr;
230
55
231
55
  std::vector<InputSectionBase *> Sections;
232
55
  for (InputSectionBase *Sec : InputSections)
233
627
    if (Sec->Type == SHT_MIPS_REGINFO)
234
75
      Sections.push_back(Sec);
235
55
236
55
  if (Sections.empty())
237
1
    return nullptr;
238
54
239
54
  Elf_Mips_RegInfo Reginfo = {};
240
75
  for (InputSectionBase *Sec : Sections) {
241
75
    Sec->Live = false;
242
75
243
75
    if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
244
0
      error(toString(Sec->File) + ": invalid size of .reginfo section");
245
0
      return nullptr;
246
0
    }
247
75
    auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
248
75
    if (Config->Relocatable && 
R->ri_gp_value8
)
249
1
      error(toString(Sec->File) + ": unsupported non-zero ri_gp_value");
250
75
251
75
    Reginfo.ri_gprmask |= R->ri_gprmask;
252
75
    Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
253
75
  };
254
54
255
54
  return make<MipsReginfoSection<ELFT>>(Reginfo);
256
54
}
lld::elf::MipsReginfoSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::create()
Line
Count
Source
226
4
MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
227
4
  // Section should be alive for O32 and N32 ABIs only.
228
4
  if (ELFT::Is64Bits)
229
0
    return nullptr;
230
4
231
4
  std::vector<InputSectionBase *> Sections;
232
4
  for (InputSectionBase *Sec : InputSections)
233
42
    if (Sec->Type == SHT_MIPS_REGINFO)
234
5
      Sections.push_back(Sec);
235
4
236
4
  if (Sections.empty())
237
0
    return nullptr;
238
4
239
4
  Elf_Mips_RegInfo Reginfo = {};
240
5
  for (InputSectionBase *Sec : Sections) {
241
5
    Sec->Live = false;
242
5
243
5
    if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
244
0
      error(toString(Sec->File) + ": invalid size of .reginfo section");
245
0
      return nullptr;
246
0
    }
247
5
    auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
248
5
    if (Config->Relocatable && 
R->ri_gp_value0
)
249
0
      error(toString(Sec->File) + ": unsupported non-zero ri_gp_value");
250
5
251
5
    Reginfo.ri_gprmask |= R->ri_gprmask;
252
5
    Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
253
5
  };
254
4
255
4
  return make<MipsReginfoSection<ELFT>>(Reginfo);
256
4
}
lld::elf::MipsReginfoSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::create()
Line
Count
Source
226
51
MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
227
51
  // Section should be alive for O32 and N32 ABIs only.
228
51
  if (ELFT::Is64Bits)
229
0
    return nullptr;
230
51
231
51
  std::vector<InputSectionBase *> Sections;
232
51
  for (InputSectionBase *Sec : InputSections)
233
585
    if (Sec->Type == SHT_MIPS_REGINFO)
234
70
      Sections.push_back(Sec);
235
51
236
51
  if (Sections.empty())
237
1
    return nullptr;
238
50
239
50
  Elf_Mips_RegInfo Reginfo = {};
240
70
  for (InputSectionBase *Sec : Sections) {
241
70
    Sec->Live = false;
242
70
243
70
    if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
244
0
      error(toString(Sec->File) + ": invalid size of .reginfo section");
245
0
      return nullptr;
246
0
    }
247
70
    auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
248
70
    if (Config->Relocatable && 
R->ri_gp_value8
)
249
1
      error(toString(Sec->File) + ": unsupported non-zero ri_gp_value");
250
70
251
70
    Reginfo.ri_gprmask |= R->ri_gprmask;
252
70
    Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
253
70
  };
254
50
255
50
  return make<MipsReginfoSection<ELFT>>(Reginfo);
256
50
}
Unexecuted instantiation: lld::elf::MipsReginfoSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::create()
lld::elf::MipsReginfoSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::create()
Line
Count
Source
226
19
MipsReginfoSection<ELFT> *MipsReginfoSection<ELFT>::create() {
227
19
  // Section should be alive for O32 and N32 ABIs only.
228
19
  if (ELFT::Is64Bits)
229
19
    return nullptr;
230
0
231
0
  std::vector<InputSectionBase *> Sections;
232
0
  for (InputSectionBase *Sec : InputSections)
233
0
    if (Sec->Type == SHT_MIPS_REGINFO)
234
0
      Sections.push_back(Sec);
235
0
236
0
  if (Sections.empty())
237
0
    return nullptr;
238
0
239
0
  Elf_Mips_RegInfo Reginfo = {};
240
0
  for (InputSectionBase *Sec : Sections) {
241
0
    Sec->Live = false;
242
0
243
0
    if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) {
244
0
      error(toString(Sec->File) + ": invalid size of .reginfo section");
245
0
      return nullptr;
246
0
    }
247
0
    auto *R = reinterpret_cast<const Elf_Mips_RegInfo *>(Sec->Data.data());
248
0
    if (Config->Relocatable && R->ri_gp_value)
249
0
      error(toString(Sec->File) + ": unsupported non-zero ri_gp_value");
250
0
251
0
    Reginfo.ri_gprmask |= R->ri_gprmask;
252
0
    Sec->getFile<ELFT>()->MipsGp0 = R->ri_gp_value;
253
0
  };
254
0
255
0
  return make<MipsReginfoSection<ELFT>>(Reginfo);
256
0
}
257
258
4
InputSection *elf::createInterpSection() {
259
4
  // StringSaver guarantees that the returned string ends with '\0'.
260
4
  StringRef S = Saver.save(Config->DynamicLinker);
261
4
  ArrayRef<uint8_t> Contents = {(const uint8_t *)S.data(), S.size() + 1};
262
4
263
4
  auto *Sec = make<InputSection>(nullptr, SHF_ALLOC, SHT_PROGBITS, 1, Contents,
264
4
                                 ".interp");
265
4
  Sec->Live = true;
266
4
  return Sec;
267
4
}
268
269
Symbol *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
270
236
                               uint64_t Size, InputSectionBase &Section) {
271
236
  auto *S = make<Defined>(Section.File, Name, STB_LOCAL, STV_DEFAULT, Type,
272
236
                          Value, Size, &Section);
273
236
  if (InX::SymTab)
274
236
    InX::SymTab->addSymbol(S);
275
236
  return S;
276
236
}
277
278
6
static size_t getHashSize() {
279
6
  switch (Config->BuildId) {
280
6
  case BuildIdKind::Fast:
281
2
    return 8;
282
6
  case BuildIdKind::Md5:
283
1
  case BuildIdKind::Uuid:
284
1
    return 16;
285
3
  case BuildIdKind::Sha1:
286
3
    return 20;
287
1
  case BuildIdKind::Hexstring:
288
0
    return Config->BuildIdVector.size();
289
1
  default:
290
0
    llvm_unreachable("unknown BuildIdKind");
291
0
  }
292
0
}
293
294
BuildIdSection::BuildIdSection()
295
    : SyntheticSection(SHF_ALLOC, SHT_NOTE, 4, ".note.gnu.build-id"),
296
6
      HashSize(getHashSize()) {}
297
298
6
void BuildIdSection::writeTo(uint8_t *Buf) {
299
6
  write32(Buf, 4);                      // Name size
300
6
  write32(Buf + 4, HashSize);           // Content size
301
6
  write32(Buf + 8, NT_GNU_BUILD_ID);    // Type
302
6
  memcpy(Buf + 12, "GNU", 4);           // Name string
303
6
  HashBuf = Buf + 16;
304
6
}
305
306
// Split one uint8 array into small pieces of uint8 arrays.
307
static std::vector<ArrayRef<uint8_t>> split(ArrayRef<uint8_t> Arr,
308
6
                                            size_t ChunkSize) {
309
6
  std::vector<ArrayRef<uint8_t>> Ret;
310
6
  while (Arr.size() > ChunkSize) {
311
0
    Ret.push_back(Arr.take_front(ChunkSize));
312
0
    Arr = Arr.drop_front(ChunkSize);
313
0
  }
314
6
  if (!Arr.empty())
315
6
    Ret.push_back(Arr);
316
6
  return Ret;
317
6
}
318
319
// Computes a hash value of Data using a given hash function.
320
// In order to utilize multiple cores, we first split data into 1MB
321
// chunks, compute a hash for each chunk, and then compute a hash value
322
// of the hash values.
323
void BuildIdSection::computeHash(
324
    llvm::ArrayRef<uint8_t> Data,
325
6
    std::function<void(uint8_t *Dest, ArrayRef<uint8_t> Arr)> HashFn) {
326
6
  std::vector<ArrayRef<uint8_t>> Chunks = split(Data, 1024 * 1024);
327
6
  std::vector<uint8_t> Hashes(Chunks.size() * HashSize);
328
6
329
6
  // Compute hash values.
330
6
  parallelForEachN(0, Chunks.size(), [&](size_t I) {
331
6
    HashFn(Hashes.data() + I * HashSize, Chunks[I]);
332
6
  });
333
6
334
6
  // Write to the final output buffer.
335
6
  HashFn(HashBuf, Hashes);
336
6
}
337
338
BssSection::BssSection(StringRef Name, uint64_t Size, uint32_t Alignment)
339
1.95k
    : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, Alignment, Name) {
340
1.95k
  this->Bss = true;
341
1.95k
  if (OutputSection *Sec = getParent())
342
0
    Sec->Alignment = std::max(Sec->Alignment, Alignment);
343
1.95k
  this->Size = Size;
344
1.95k
}
345
346
6
void BuildIdSection::writeBuildId(ArrayRef<uint8_t> Buf) {
347
6
  switch (Config->BuildId) {
348
6
  case BuildIdKind::Fast:
349
4
    computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
350
4
      write64le(Dest, xxHash64(toStringRef(Arr)));
351
4
    });
352
2
    break;
353
6
  case BuildIdKind::Md5:
354
2
    computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
355
2
      memcpy(Dest, MD5::hash(Arr).data(), 16);
356
2
    });
357
1
    break;
358
6
  case BuildIdKind::Sha1:
359
6
    computeHash(Buf, [](uint8_t *Dest, ArrayRef<uint8_t> Arr) {
360
6
      memcpy(Dest, SHA1::hash(Arr).data(), 20);
361
6
    });
362
3
    break;
363
6
  case BuildIdKind::Uuid:
364
0
    if (auto EC = getRandomBytes(HashBuf, HashSize))
365
0
      error("entropy source failure: " + EC.message());
366
0
    break;
367
6
  case BuildIdKind::Hexstring:
368
0
    memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size());
369
0
    break;
370
6
  default:
371
0
    llvm_unreachable("unknown BuildIdKind");
372
6
  }
373
6
}
374
375
EhFrameSection::EhFrameSection()
376
907
    : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {}
377
378
// Search for an existing CIE record or create a new one.
379
// CIE records from input object files are uniquified by their contents
380
// and where their relocations point to.
381
template <class ELFT, class RelTy>
382
50
CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) {
383
50
  auto *Sec = cast<EhInputSection>(Cie.Sec);
384
50
  if (read32(Cie.data().data() + 4, Config->Endianness) != 0)
385
0
    fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
386
50
387
50
  Symbol *Personality = nullptr;
388
50
  unsigned FirstRelI = Cie.FirstRelocation;
389
50
  if (FirstRelI != (unsigned)-1)
390
3
    Personality =
391
3
        &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
392
50
393
50
  // Search for an existing CIE by CIE contents/relocation target pair.
394
50
  CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
395
50
396
50
  // If not found, create a new one.
397
50
  if (!Rec) {
398
43
    Rec = make<CieRecord>();
399
43
    Rec->Cie = &Cie;
400
43
    CieRecords.push_back(Rec);
401
43
  }
402
50
  return Rec;
403
50
}
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
382
2
CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) {
383
2
  auto *Sec = cast<EhInputSection>(Cie.Sec);
384
2
  if (read32(Cie.data().data() + 4, Config->Endianness) != 0)
385
0
    fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
386
2
387
2
  Symbol *Personality = nullptr;
388
2
  unsigned FirstRelI = Cie.FirstRelocation;
389
2
  if (FirstRelI != (unsigned)-1)
390
0
    Personality =
391
0
        &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
392
2
393
2
  // Search for an existing CIE by CIE contents/relocation target pair.
394
2
  CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
395
2
396
2
  // If not found, create a new one.
397
2
  if (!Rec) {
398
1
    Rec = make<CieRecord>();
399
1
    Rec->Cie = &Cie;
400
1
    CieRecords.push_back(Rec);
401
1
  }
402
2
  return Rec;
403
2
}
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
382
1
CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) {
383
1
  auto *Sec = cast<EhInputSection>(Cie.Sec);
384
1
  if (read32(Cie.data().data() + 4, Config->Endianness) != 0)
385
0
    fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
386
1
387
1
  Symbol *Personality = nullptr;
388
1
  unsigned FirstRelI = Cie.FirstRelocation;
389
1
  if (FirstRelI != (unsigned)-1)
390
0
    Personality =
391
0
        &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
392
1
393
1
  // Search for an existing CIE by CIE contents/relocation target pair.
394
1
  CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
395
1
396
1
  // If not found, create a new one.
397
1
  if (!Rec) {
398
1
    Rec = make<CieRecord>();
399
1
    Rec->Cie = &Cie;
400
1
    CieRecords.push_back(Rec);
401
1
  }
402
1
  return Rec;
403
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
382
44
CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) {
383
44
  auto *Sec = cast<EhInputSection>(Cie.Sec);
384
44
  if (read32(Cie.data().data() + 4, Config->Endianness) != 0)
385
0
    fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
386
44
387
44
  Symbol *Personality = nullptr;
388
44
  unsigned FirstRelI = Cie.FirstRelocation;
389
44
  if (FirstRelI != (unsigned)-1)
390
3
    Personality =
391
3
        &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
392
44
393
44
  // Search for an existing CIE by CIE contents/relocation target pair.
394
44
  CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
395
44
396
44
  // If not found, create a new one.
397
44
  if (!Rec) {
398
38
    Rec = make<CieRecord>();
399
38
    Rec->Cie = &Cie;
400
38
    CieRecords.push_back(Rec);
401
38
  }
402
44
  return Rec;
403
44
}
Unexecuted instantiation: 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> >)
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
382
2
CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) {
383
2
  auto *Sec = cast<EhInputSection>(Cie.Sec);
384
2
  if (read32(Cie.data().data() + 4, Config->Endianness) != 0)
385
0
    fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
386
2
387
2
  Symbol *Personality = nullptr;
388
2
  unsigned FirstRelI = Cie.FirstRelocation;
389
2
  if (FirstRelI != (unsigned)-1)
390
0
    Personality =
391
0
        &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
392
2
393
2
  // Search for an existing CIE by CIE contents/relocation target pair.
394
2
  CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
395
2
396
2
  // If not found, create a new one.
397
2
  if (!Rec) {
398
2
    Rec = make<CieRecord>();
399
2
    Rec->Cie = &Cie;
400
2
    CieRecords.push_back(Rec);
401
2
  }
402
2
  return Rec;
403
2
}
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
382
1
CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef<RelTy> Rels) {
383
1
  auto *Sec = cast<EhInputSection>(Cie.Sec);
384
1
  if (read32(Cie.data().data() + 4, Config->Endianness) != 0)
385
0
    fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
386
1
387
1
  Symbol *Personality = nullptr;
388
1
  unsigned FirstRelI = Cie.FirstRelocation;
389
1
  if (FirstRelI != (unsigned)-1)
390
0
    Personality =
391
0
        &Sec->template getFile<ELFT>()->getRelocTargetSym(Rels[FirstRelI]);
392
1
393
1
  // Search for an existing CIE by CIE contents/relocation target pair.
394
1
  CieRecord *&Rec = CieMap[{Cie.data(), Personality}];
395
1
396
1
  // If not found, create a new one.
397
1
  if (!Rec) {
398
1
    Rec = make<CieRecord>();
399
1
    Rec->Cie = &Cie;
400
1
    CieRecords.push_back(Rec);
401
1
  }
402
1
  return Rec;
403
1
}
404
405
// There is one FDE per function. Returns true if a given FDE
406
// points to a live function.
407
template <class ELFT, class RelTy>
408
69
bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef<RelTy> Rels) {
409
69
  auto *Sec = cast<EhInputSection>(Fde.Sec);
410
69
  unsigned FirstRelI = Fde.FirstRelocation;
411
69
412
69
  // An FDE should point to some function because FDEs are to describe
413
69
  // functions. That's however not always the case due to an issue of
414
69
  // ld.gold with -r. ld.gold may discard only functions and leave their
415
69
  // corresponding FDEs, which results in creating bad .eh_frame sections.
416
69
  // To deal with that, we ignore such FDEs.
417
69
  if (FirstRelI == (unsigned)-1)
418
0
    return false;
419
69
420
69
  const RelTy &Rel = Rels[FirstRelI];
421
69
  Symbol &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
422
69
423
69
  // FDEs for garbage-collected or merged-by-ICF sections are dead.
424
69
  if (auto *D = dyn_cast<Defined>(&B))
425
68
    if (SectionBase *Sec = D->Section)
426
68
      return Sec->Live;
427
1
  return false;
428
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
408
2
bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef<RelTy> Rels) {
409
2
  auto *Sec = cast<EhInputSection>(Fde.Sec);
410
2
  unsigned FirstRelI = Fde.FirstRelocation;
411
2
412
2
  // An FDE should point to some function because FDEs are to describe
413
2
  // functions. That's however not always the case due to an issue of
414
2
  // ld.gold with -r. ld.gold may discard only functions and leave their
415
2
  // corresponding FDEs, which results in creating bad .eh_frame sections.
416
2
  // To deal with that, we ignore such FDEs.
417
2
  if (FirstRelI == (unsigned)-1)
418
0
    return false;
419
2
420
2
  const RelTy &Rel = Rels[FirstRelI];
421
2
  Symbol &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
422
2
423
2
  // FDEs for garbage-collected or merged-by-ICF sections are dead.
424
2
  if (auto *D = dyn_cast<Defined>(&B))
425
2
    if (SectionBase *Sec = D->Section)
426
2
      return Sec->Live;
427
0
  return false;
428
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
408
1
bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef<RelTy> Rels) {
409
1
  auto *Sec = cast<EhInputSection>(Fde.Sec);
410
1
  unsigned FirstRelI = Fde.FirstRelocation;
411
1
412
1
  // An FDE should point to some function because FDEs are to describe
413
1
  // functions. That's however not always the case due to an issue of
414
1
  // ld.gold with -r. ld.gold may discard only functions and leave their
415
1
  // corresponding FDEs, which results in creating bad .eh_frame sections.
416
1
  // To deal with that, we ignore such FDEs.
417
1
  if (FirstRelI == (unsigned)-1)
418
0
    return false;
419
1
420
1
  const RelTy &Rel = Rels[FirstRelI];
421
1
  Symbol &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
422
1
423
1
  // FDEs for garbage-collected or merged-by-ICF sections are dead.
424
1
  if (auto *D = dyn_cast<Defined>(&B))
425
1
    if (SectionBase *Sec = D->Section)
426
1
      return Sec->Live;
427
0
  return false;
428
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
408
64
bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef<RelTy> Rels) {
409
64
  auto *Sec = cast<EhInputSection>(Fde.Sec);
410
64
  unsigned FirstRelI = Fde.FirstRelocation;
411
64
412
64
  // An FDE should point to some function because FDEs are to describe
413
64
  // functions. That's however not always the case due to an issue of
414
64
  // ld.gold with -r. ld.gold may discard only functions and leave their
415
64
  // corresponding FDEs, which results in creating bad .eh_frame sections.
416
64
  // To deal with that, we ignore such FDEs.
417
64
  if (FirstRelI == (unsigned)-1)
418
0
    return false;
419
64
420
64
  const RelTy &Rel = Rels[FirstRelI];
421
64
  Symbol &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
422
64
423
64
  // FDEs for garbage-collected or merged-by-ICF sections are dead.
424
64
  if (auto *D = dyn_cast<Defined>(&B))
425
63
    if (SectionBase *Sec = D->Section)
426
63
      return Sec->Live;
427
1
  return false;
428
1
}
Unexecuted instantiation: 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> >)
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
408
2
bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef<RelTy> Rels) {
409
2
  auto *Sec = cast<EhInputSection>(Fde.Sec);
410
2
  unsigned FirstRelI = Fde.FirstRelocation;
411
2
412
2
  // An FDE should point to some function because FDEs are to describe
413
2
  // functions. That's however not always the case due to an issue of
414
2
  // ld.gold with -r. ld.gold may discard only functions and leave their
415
2
  // corresponding FDEs, which results in creating bad .eh_frame sections.
416
2
  // To deal with that, we ignore such FDEs.
417
2
  if (FirstRelI == (unsigned)-1)
418
0
    return false;
419
2
420
2
  const RelTy &Rel = Rels[FirstRelI];
421
2
  Symbol &B = Sec->template getFile<ELFT>()->getRelocTargetSym(Rel);
422
2
423
2
  // FDEs for garbage-collected or merged-by-ICF sections are dead.
424
2
  if (auto *D = dyn_cast<Defined>(&B))
425
2
    if (SectionBase *Sec = D->Section)
426
2
      return Sec->Live;
427
0
  return false;
428
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> >)
429
430
// .eh_frame is a sequence of CIE or FDE records. In general, there
431
// is one CIE record per input object file which is followed by
432
// a list of FDEs. This function searches an existing CIE or create a new
433
// one and associates FDEs to the CIE.
434
template <class ELFT, class RelTy>
435
51
void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
436
51
  DenseMap<size_t, CieRecord *> OffsetToCie;
437
121
  for (EhSectionPiece &Piece : Sec->Pieces) {
438
121
    // The empty record is the end marker.
439
121
    if (Piece.Size == 4)
440
2
      return;
441
119
442
119
    size_t Offset = Piece.InputOff;
443
119
    uint32_t ID = read32(Piece.data().data() + 4, Config->Endianness);
444
119
    if (ID == 0) {
445
50
      OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
446
50
      continue;
447
50
    }
448
69
449
69
    uint32_t CieOffset = Offset + 4 - ID;
450
69
    CieRecord *Rec = OffsetToCie[CieOffset];
451
69
    if (!Rec)
452
0
      fatal(toString(Sec) + ": invalid CIE reference");
453
69
454
69
    if (!isFdeLive<ELFT>(Piece, Rels))
455
6
      continue;
456
63
    Rec->Fdes.push_back(&Piece);
457
63
    NumFdes++;
458
63
  }
459
51
}
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
435
2
void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
436
2
  DenseMap<size_t, CieRecord *> OffsetToCie;
437
4
  for (EhSectionPiece &Piece : Sec->Pieces) {
438
4
    // The empty record is the end marker.
439
4
    if (Piece.Size == 4)
440
0
      return;
441
4
442
4
    size_t Offset = Piece.InputOff;
443
4
    uint32_t ID = read32(Piece.data().data() + 4, Config->Endianness);
444
4
    if (ID == 0) {
445
2
      OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
446
2
      continue;
447
2
    }
448
2
449
2
    uint32_t CieOffset = Offset + 4 - ID;
450
2
    CieRecord *Rec = OffsetToCie[CieOffset];
451
2
    if (!Rec)
452
0
      fatal(toString(Sec) + ": invalid CIE reference");
453
2
454
2
    if (!isFdeLive<ELFT>(Piece, Rels))
455
0
      continue;
456
2
    Rec->Fdes.push_back(&Piece);
457
2
    NumFdes++;
458
2
  }
459
2
}
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
435
1
void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
436
1
  DenseMap<size_t, CieRecord *> OffsetToCie;
437
2
  for (EhSectionPiece &Piece : Sec->Pieces) {
438
2
    // The empty record is the end marker.
439
2
    if (Piece.Size == 4)
440
0
      return;
441
2
442
2
    size_t Offset = Piece.InputOff;
443
2
    uint32_t ID = read32(Piece.data().data() + 4, Config->Endianness);
444
2
    if (ID == 0) {
445
1
      OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
446
1
      continue;
447
1
    }
448
1
449
1
    uint32_t CieOffset = Offset + 4 - ID;
450
1
    CieRecord *Rec = OffsetToCie[CieOffset];
451
1
    if (!Rec)
452
0
      fatal(toString(Sec) + ": invalid CIE reference");
453
1
454
1
    if (!isFdeLive<ELFT>(Piece, Rels))
455
0
      continue;
456
1
    Rec->Fdes.push_back(&Piece);
457
1
    NumFdes++;
458
1
  }
459
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
435
43
void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
436
43
  DenseMap<size_t, CieRecord *> OffsetToCie;
437
108
  for (EhSectionPiece &Piece : Sec->Pieces) {
438
108
    // The empty record is the end marker.
439
108
    if (Piece.Size == 4)
440
0
      return;
441
108
442
108
    size_t Offset = Piece.InputOff;
443
108
    uint32_t ID = read32(Piece.data().data() + 4, Config->Endianness);
444
108
    if (ID == 0) {
445
44
      OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
446
44
      continue;
447
44
    }
448
64
449
64
    uint32_t CieOffset = Offset + 4 - ID;
450
64
    CieRecord *Rec = OffsetToCie[CieOffset];
451
64
    if (!Rec)
452
0
      fatal(toString(Sec) + ": invalid CIE reference");
453
64
454
64
    if (!isFdeLive<ELFT>(Piece, Rels))
455
6
      continue;
456
58
    Rec->Fdes.push_back(&Piece);
457
58
    NumFdes++;
458
58
  }
459
43
}
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
435
2
void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
436
2
  DenseMap<size_t, CieRecord *> OffsetToCie;
437
2
  for (EhSectionPiece &Piece : Sec->Pieces) {
438
2
    // The empty record is the end marker.
439
2
    if (Piece.Size == 4)
440
2
      return;
441
0
442
0
    size_t Offset = Piece.InputOff;
443
0
    uint32_t ID = read32(Piece.data().data() + 4, Config->Endianness);
444
0
    if (ID == 0) {
445
0
      OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
446
0
      continue;
447
0
    }
448
0
449
0
    uint32_t CieOffset = Offset + 4 - ID;
450
0
    CieRecord *Rec = OffsetToCie[CieOffset];
451
0
    if (!Rec)
452
0
      fatal(toString(Sec) + ": invalid CIE reference");
453
0
454
0
    if (!isFdeLive<ELFT>(Piece, Rels))
455
0
      continue;
456
0
    Rec->Fdes.push_back(&Piece);
457
0
    NumFdes++;
458
0
  }
459
2
}
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
435
2
void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
436
2
  DenseMap<size_t, CieRecord *> OffsetToCie;
437
4
  for (EhSectionPiece &Piece : Sec->Pieces) {
438
4
    // The empty record is the end marker.
439
4
    if (Piece.Size == 4)
440
0
      return;
441
4
442
4
    size_t Offset = Piece.InputOff;
443
4
    uint32_t ID = read32(Piece.data().data() + 4, Config->Endianness);
444
4
    if (ID == 0) {
445
2
      OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
446
2
      continue;
447
2
    }
448
2
449
2
    uint32_t CieOffset = Offset + 4 - ID;
450
2
    CieRecord *Rec = OffsetToCie[CieOffset];
451
2
    if (!Rec)
452
0
      fatal(toString(Sec) + ": invalid CIE reference");
453
2
454
2
    if (!isFdeLive<ELFT>(Piece, Rels))
455
0
      continue;
456
2
    Rec->Fdes.push_back(&Piece);
457
2
    NumFdes++;
458
2
  }
459
2
}
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
435
1
void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef<RelTy> Rels) {
436
1
  DenseMap<size_t, CieRecord *> OffsetToCie;
437
1
  for (EhSectionPiece &Piece : Sec->Pieces) {
438
1
    // The empty record is the end marker.
439
1
    if (Piece.Size == 4)
440
0
      return;
441
1
442
1
    size_t Offset = Piece.InputOff;
443
1
    uint32_t ID = read32(Piece.data().data() + 4, Config->Endianness);
444
1
    if (ID == 0) {
445
1
      OffsetToCie[Offset] = addCie<ELFT>(Piece, Rels);
446
1
      continue;
447
1
    }
448
0
449
0
    uint32_t CieOffset = Offset + 4 - ID;
450
0
    CieRecord *Rec = OffsetToCie[CieOffset];
451
0
    if (!Rec)
452
0
      fatal(toString(Sec) + ": invalid CIE reference");
453
0
454
0
    if (!isFdeLive<ELFT>(Piece, Rels))
455
0
      continue;
456
0
    Rec->Fdes.push_back(&Piece);
457
0
    NumFdes++;
458
0
  }
459
1
}
460
461
53
template <class ELFT> void EhFrameSection::addSection(InputSectionBase *C) {
462
53
  auto *Sec = cast<EhInputSection>(C);
463
53
  Sec->Parent = this;
464
53
465
53
  Alignment = std::max(Alignment, Sec->Alignment);
466
53
  Sections.push_back(Sec);
467
53
468
53
  for (auto *DS : Sec->DependentSections)
469
0
    DependentSections.push_back(DS);
470
53
471
53
  // .eh_frame is a sequence of CIE or FDE records. This function
472
53
  // splits it into pieces so that we can call
473
53
  // SplitInputSection::getSectionPiece on the section.
474
53
  Sec->split<ELFT>();
475
53
  if (Sec->Pieces.empty())
476
2
    return;
477
51
478
51
  if (Sec->AreRelocsRela)
479
45
    addSectionAux<ELFT>(Sec, Sec->template relas<ELFT>());
480
6
  else
481
6
    addSectionAux<ELFT>(Sec, Sec->template rels<ELFT>());
482
51
}
void lld::elf::EhFrameSection::addSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >(lld::elf::InputSectionBase*)
Line
Count
Source
461
2
template <class ELFT> void EhFrameSection::addSection(InputSectionBase *C) {
462
2
  auto *Sec = cast<EhInputSection>(C);
463
2
  Sec->Parent = this;
464
2
465
2
  Alignment = std::max(Alignment, Sec->Alignment);
466
2
  Sections.push_back(Sec);
467
2
468
2
  for (auto *DS : Sec->DependentSections)
469
0
    DependentSections.push_back(DS);
470
2
471
2
  // .eh_frame is a sequence of CIE or FDE records. This function
472
2
  // splits it into pieces so that we can call
473
2
  // SplitInputSection::getSectionPiece on the section.
474
2
  Sec->split<ELFT>();
475
2
  if (Sec->Pieces.empty())
476
0
    return;
477
2
478
2
  if (Sec->AreRelocsRela)
479
0
    addSectionAux<ELFT>(Sec, Sec->template relas<ELFT>());
480
2
  else
481
2
    addSectionAux<ELFT>(Sec, Sec->template rels<ELFT>());
482
2
}
void lld::elf::EhFrameSection::addSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >(lld::elf::InputSectionBase*)
Line
Count
Source
461
1
template <class ELFT> void EhFrameSection::addSection(InputSectionBase *C) {
462
1
  auto *Sec = cast<EhInputSection>(C);
463
1
  Sec->Parent = this;
464
1
465
1
  Alignment = std::max(Alignment, Sec->Alignment);
466
1
  Sections.push_back(Sec);
467
1
468
1
  for (auto *DS : Sec->DependentSections)
469
0
    DependentSections.push_back(DS);
470
1
471
1
  // .eh_frame is a sequence of CIE or FDE records. This function
472
1
  // splits it into pieces so that we can call
473
1
  // SplitInputSection::getSectionPiece on the section.
474
1
  Sec->split<ELFT>();
475
1
  if (Sec->Pieces.empty())
476
0
    return;
477
1
478
1
  if (Sec->AreRelocsRela)
479
0
    addSectionAux<ELFT>(Sec, Sec->template relas<ELFT>());
480
1
  else
481
1
    addSectionAux<ELFT>(Sec, Sec->template rels<ELFT>());
482
1
}
void lld::elf::EhFrameSection::addSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >(lld::elf::InputSectionBase*)
Line
Count
Source
461
47
template <class ELFT> void EhFrameSection::addSection(InputSectionBase *C) {
462
47
  auto *Sec = cast<EhInputSection>(C);
463
47
  Sec->Parent = this;
464
47
465
47
  Alignment = std::max(Alignment, Sec->Alignment);
466
47
  Sections.push_back(Sec);
467
47
468
47
  for (auto *DS : Sec->DependentSections)
469
0
    DependentSections.push_back(DS);
470
47
471
47
  // .eh_frame is a sequence of CIE or FDE records. This function
472
47
  // splits it into pieces so that we can call
473
47
  // SplitInputSection::getSectionPiece on the section.
474
47
  Sec->split<ELFT>();
475
47
  if (Sec->Pieces.empty())
476
2
    return;
477
45
478
45
  if (Sec->AreRelocsRela)
479
43
    addSectionAux<ELFT>(Sec, Sec->template relas<ELFT>());
480
2
  else
481
2
    addSectionAux<ELFT>(Sec, Sec->template rels<ELFT>());
482
45
}
void lld::elf::EhFrameSection::addSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >(lld::elf::InputSectionBase*)
Line
Count
Source
461
3
template <class ELFT> void EhFrameSection::addSection(InputSectionBase *C) {
462
3
  auto *Sec = cast<EhInputSection>(C);
463
3
  Sec->Parent = this;
464
3
465
3
  Alignment = std::max(Alignment, Sec->Alignment);
466
3
  Sections.push_back(Sec);
467
3
468
3
  for (auto *DS : Sec->DependentSections)
469
0
    DependentSections.push_back(DS);
470
3
471
3
  // .eh_frame is a sequence of CIE or FDE records. This function
472
3
  // splits it into pieces so that we can call
473
3
  // SplitInputSection::getSectionPiece on the section.
474
3
  Sec->split<ELFT>();
475
3
  if (Sec->Pieces.empty())
476
0
    return;
477
3
478
3
  if (Sec->AreRelocsRela)
479
2
    addSectionAux<ELFT>(Sec, Sec->template relas<ELFT>());
480
1
  else
481
1
    addSectionAux<ELFT>(Sec, Sec->template rels<ELFT>());
482
3
}
483
484
102
static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
485
102
  memcpy(Buf, D.data(), D.size());
486
102
487
102
  size_t Aligned = alignTo(D.size(), Config->Wordsize);
488
102
489
102
  // Zero-clear trailing padding if it exists.
490
102
  memset(Buf + D.size(), 0, Aligned - D.size());
491
102
492
102
  // Fix the size field. -4 since size does not include the size field itself.
493
102
  write32(Buf, Aligned - 4);
494
102
}
495
496
46
void EhFrameSection::finalizeContents() {
497
46
  if (this->Size)
498
0
    return; // Already finalized.
499
46
500
46
  size_t Off = 0;
501
46
  for (CieRecord *Rec : CieRecords) {
502
43
    Rec->Cie->OutputOff = Off;
503
43
    Off += alignTo(Rec->Cie->Size, Config->Wordsize);
504
43
505
63
    for (EhSectionPiece *Fde : Rec->Fdes) {
506
63
      Fde->OutputOff = Off;
507
63
      Off += alignTo(Fde->Size, Config->Wordsize);
508
63
    }
509
43
  }
510
46
511
46
  // The LSB standard does not allow a .eh_frame section with zero
512
46
  // Call Frame Information records. Therefore add a CIE record length
513
46
  // 0 as a terminator if this .eh_frame section is empty.
514
46
  if (Off == 0)
515
3
    Off = 4;
516
46
517
46
  this->Size = Off;
518
46
}
519
520
// Returns data for .eh_frame_hdr. .eh_frame_hdr is a binary search table
521
// to get an FDE from an address to which FDE is applied. This function
522
// returns a list of such pairs.
523
8
std::vector<EhFrameSection::FdeData> EhFrameSection::getFdeData() const {
524
8
  uint8_t *Buf = getParent()->Loc + OutSecOff;
525
8
  std::vector<FdeData> Ret;
526
8
527
8
  for (CieRecord *Rec : CieRecords) {
528
8
    uint8_t Enc = getFdeEncoding(Rec->Cie);
529
10
    for (EhSectionPiece *Fde : Rec->Fdes) {
530
10
      uint32_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
531
10
      uint32_t FdeVA = getParent()->Addr + Fde->OutputOff;
532
10
      Ret.push_back({Pc, FdeVA});
533
10
    }
534
8
  }
535
8
  return Ret;
536
8
}
537
538
10
static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
539
10
  switch (Size) {
540
10
  case DW_EH_PE_udata2:
541
0
    return read16(Buf, Config->Endianness);
542
10
  case DW_EH_PE_udata4:
543
8
    return read32(Buf, Config->Endianness);
544
10
  case DW_EH_PE_udata8:
545
2
    return read64(Buf, Config->Endianness);
546
10
  case DW_EH_PE_absptr:
547
0
    return readUint(Buf);
548
0
  }
549
0
  fatal("unknown FDE size encoding");
550
0
}
551
552
// Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
553
// We need it to create .eh_frame_hdr section.
554
uint64_t EhFrameSection::getFdePc(uint8_t *Buf, size_t FdeOff,
555
10
                                  uint8_t Enc) const {
556
10
  // The starting address to which this FDE applies is
557
10
  // stored at FDE + 8 byte.
558
10
  size_t Off = FdeOff + 8;
559
10
  uint64_t Addr = readFdeAddr(Buf + Off, Enc & 0x7);
560
10
  if ((Enc & 0x70) == DW_EH_PE_absptr)
561
3
    return Addr;
562
7
  if ((Enc & 0x70) == DW_EH_PE_pcrel)
563
7
    return Addr + getParent()->Addr + Off;
564
0
  fatal("unknown FDE size relative encoding");
565
0
}
566
567
44
void EhFrameSection::writeTo(uint8_t *Buf) {
568
44
  // Write CIE and FDE records.
569
44
  for (CieRecord *Rec : CieRecords) {
570
41
    size_t CieOffset = Rec->Cie->OutputOff;
571
41
    writeCieFde(Buf + CieOffset, Rec->Cie->data());
572
41
573
61
    for (EhSectionPiece *Fde : Rec->Fdes) {
574
61
      size_t Off = Fde->OutputOff;
575
61
      writeCieFde(Buf + Off, Fde->data());
576
61
577
61
      // FDE's second word should have the offset to an associated CIE.
578
61
      // Write it.
579
61
      write32(Buf + Off + 4, Off + 4 - CieOffset);
580
61
    }
581
41
  }
582
44
583
44
  // Apply relocations. .eh_frame section contents are not contiguous
584
44
  // in the output buffer, but relocateAlloc() still works because
585
44
  // getOffset() takes care of discontiguous section pieces.
586
44
  for (EhInputSection *S : Sections)
587
50
    S->relocateAlloc(Buf, nullptr);
588
44
}
589
590
GotSection::GotSection()
591
    : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
592
862
                       Target->GotEntrySize, ".got") {}
593
594
75
void GotSection::addEntry(Symbol &Sym) {
595
75
  Sym.GotIndex = NumEntries;
596
75
  ++NumEntries;
597
75
}
598
599
12
bool GotSection::addDynTlsEntry(Symbol &Sym) {
600
12
  if (Sym.GlobalDynIndex != -1U)
601
0
    return false;
602
12
  Sym.GlobalDynIndex = NumEntries;
603
12
  // Global Dynamic TLS entries take two GOT slots.
604
12
  NumEntries += 2;
605
12
  return true;
606
12
}
607
608
// Reserves TLS entries for a TLS module ID and a TLS block offset.
609
// In total it takes two GOT slots.
610
5
bool GotSection::addTlsIndex() {
611
5
  if (TlsIndexOff != uint32_t(-1))
612
2
    return false;
613
3
  TlsIndexOff = NumEntries * Config->Wordsize;
614
3
  NumEntries += 2;
615
3
  return true;
616
3
}
617
618
10
uint64_t GotSection::getGlobalDynAddr(const Symbol &B) const {
619
10
  return this->getVA() + B.GlobalDynIndex * Config->Wordsize;
620
10
}
621
622
14
uint64_t GotSection::getGlobalDynOffset(const Symbol &B) const {
623
14
  return B.GlobalDynIndex * Config->Wordsize;
624
14
}
625
626
55
void GotSection::finalizeContents() { Size = NumEntries * Config->Wordsize; }
627
628
1.70k
bool GotSection::empty() const {
629
1.70k
  // We need to emit a GOT even if it's empty if there's a relocation that is
630
1.70k
  // relative to GOT(such as GOTOFFREL) or there's a symbol that points to a GOT
631
1.70k
  // (i.e. _GLOBAL_OFFSET_TABLE_).
632
1.70k
  return NumEntries == 0 && 
!HasGotOffRel1.54k
&&
!ElfSym::GlobalOffsetTable1.53k
;
633
1.70k
}
634
635
54
void GotSection::writeTo(uint8_t *Buf) {
636
54
  // Buf points to the start of this section's buffer,
637
54
  // whereas InputSectionBase::relocateAlloc() expects its argument
638
54
  // to point to the start of the output section.
639
54
  relocateAlloc(Buf - OutSecOff, Buf - OutSecOff + Size);
640
54
}
641
642
MipsGotSection::MipsGotSection()
643
    : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16,
644
74
                       ".got") {}
645
646
10.0k
void MipsGotSection::addEntry(Symbol &Sym, int64_t Addend, RelExpr Expr) {
647
10.0k
  // For "true" local symbols which can be referenced from the same module
648
10.0k
  // only compiler creates two instructions for address loading:
649
10.0k
  //
650
10.0k
  // lw   $8, 0($gp) # R_MIPS_GOT16
651
10.0k
  // addi $8, $8, 0  # R_MIPS_LO16
652
10.0k
  //
653
10.0k
  // The first instruction loads high 16 bits of the symbol address while
654
10.0k
  // the second adds an offset. That allows to reduce number of required
655
10.0k
  // GOT entries because only one global offset table entry is necessary
656
10.0k
  // for every 64 KBytes of local data. So for local symbols we need to
657
10.0k
  // allocate number of GOT entries to hold all required "page" addresses.
658
10.0k
  //
659
10.0k
  // All global symbols (hidden and regular) considered by compiler uniformly.
660
10.0k
  // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
661
10.0k
  // to load address of the symbol. So for each such symbol we need to
662
10.0k
  // allocate dedicated GOT entry to store its address.
663
10.0k
  //
664
10.0k
  // If a symbol is preemptible we need help of dynamic linker to get its
665
10.0k
  // final address. The corresponding GOT entries are allocated in the
666
10.0k
  // "global" part of GOT. Entries for non preemptible global symbol allocated
667
10.0k
  // in the "local" part of GOT.
668
10.0k
  //
669
10.0k
  // See "Global Offset Table" in Chapter 5:
670
10.0k
  // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
671
10.0k
  if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
672
17
    // At this point we do not know final symbol value so to reduce number
673
17
    // of allocated GOT entries do the following trick. Save all output
674
17
    // sections referenced by GOT relocations. Then later in the `finalize`
675
17
    // method calculate number of "pages" required to cover all saved output
676
17
    // section and allocate appropriate number of GOT entries.
677
17
    PageIndexMap.insert({Sym.getOutputSection(), 0});
678
17
    return;
679
17
  }
680
10.0k
  if (Sym.isTls()) {
681
1
    // GOT entries created for MIPS TLS relocations behave like
682
1
    // almost GOT entries from other ABIs. They go to the end
683
1
    // of the global offset table.
684
1
    Sym.GotIndex = TlsEntries.size();
685
1
    TlsEntries.push_back(&Sym);
686
1
    return;
687
1
  }
688
10.0k
  auto AddEntry = [&](Symbol &S, uint64_t A, GotEntries &Items) {
689
10.0k
    if (S.isInGot() && 
!A10
)
690
10
      return;
691
10.0k
    size_t NewIndex = Items.size();
692
10.0k
    if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second)
693
0
      return;
694
10.0k
    Items.emplace_back(&S, A);
695
10.0k
    if (!A)
696
10.0k
      S.GotIndex = NewIndex;
697
10.0k
  };
698
10.0k
  if (Sym.IsPreemptible) {
699
15
    // Ignore addends for preemptible symbols. They got single GOT entry anyway.
700
15
    AddEntry(Sym, 0, GlobalEntries);
701
15
    Sym.IsInGlobalMipsGot = true;
702
10.0k
  } else if (Expr == R_MIPS_GOT_OFF32) {
703
12
    AddEntry(Sym, Addend, LocalEntries32);
704
12
    Sym.Is32BitMipsGot = true;
705
10.0k
  } else {
706
10.0k
    // Hold local GOT entries accessed via a 16-bit index separately.
707
10.0k
    // That allows to write them in the beginning of the GOT and keep
708
10.0k
    // their indexes as less as possible to escape relocation's overflow.
709
10.0k
    AddEntry(Sym, Addend, LocalEntries);
710
10.0k
  }
711
10.0k
}
712
713
1
bool MipsGotSection::addDynTlsEntry(Symbol &Sym) {
714
1
  if (Sym.GlobalDynIndex != -1U)
715
0
    return false;
716
1
  Sym.GlobalDynIndex = TlsEntries.size();
717
1
  // Global Dynamic TLS entries take two GOT slots.
718
1
  TlsEntries.push_back(nullptr);
719
1
  TlsEntries.push_back(&Sym);
720
1
  return true;
721
1
}
722
723
// Reserves TLS entries for a TLS module ID and a TLS block offset.
724
// In total it takes two GOT slots.
725
1
bool MipsGotSection::addTlsIndex() {
726
1
  if (TlsIndexOff != uint32_t(-1))
727
0
    return false;
728
1
  TlsIndexOff = TlsEntries.size() * Config->Wordsize;
729
1
  TlsEntries.push_back(nullptr);
730
1
  TlsEntries.push_back(nullptr);
731
1
  return true;
732
1
}
733
734
43
static uint64_t getMipsPageAddr(uint64_t Addr) {
735
43
  return (Addr + 0x8000) & ~0xffff;
736
43
}
737
738
27
static uint64_t getMipsPageCount(uint64_t Size) {
739
27
  return (Size + 0xfffe) / 0xffff + 1;
740
27
}
741
742
uint64_t MipsGotSection::getPageEntryOffset(const Symbol &B,
743
17
                                            int64_t Addend) const {
744
17
  const OutputSection *OutSec = B.getOutputSection();
745
17
  uint64_t SecAddr = getMipsPageAddr(OutSec->Addr);
746
17
  uint64_t SymAddr = getMipsPageAddr(B.getVA(Addend));
747
17
  uint64_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff;
748
17
  assert(Index < PageEntriesNum);
749
17
  return (HeaderEntriesNum + Index) * Config->Wordsize;
750
17
}
751
752
uint64_t MipsGotSection::getSymEntryOffset(const Symbol &B,
753
10.0k
                                           int64_t Addend) const {
754
10.0k
  // Calculate offset of the GOT entries block: TLS, global, local.
755
10.0k
  uint64_t Index = HeaderEntriesNum + PageEntriesNum;
756
10.0k
  if (B.isTls())
757
1
    Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size();
758
10.0k
  else if (B.IsInGlobalMipsGot)
759
14
    Index += LocalEntries.size() + LocalEntries32.size();
760
10.0k
  else if (B.Is32BitMipsGot)
761
12
    Index += LocalEntries.size();
762
10.0k
  // Calculate offset of the GOT entry in the block.
763
10.0k
  if (B.isInGot())
764
10.0k
    Index += B.GotIndex;
765
0
  else {
766
0
    auto It = EntryIndexMap.find({&B, Addend});
767
0
    assert(It != EntryIndexMap.end());
768
0
    Index += It->second;
769
0
  }
770
10.0k
  return Index * Config->Wordsize;
771
10.0k
}
772
773
2
uint64_t MipsGotSection::getTlsOffset() const {
774
2
  return (getLocalEntriesNum() + GlobalEntries.size()) * Config->Wordsize;
775
2
}
776
777
1
uint64_t MipsGotSection::getGlobalDynOffset(const Symbol &B) const {
778
1
  return B.GlobalDynIndex * Config->Wordsize;
779
1
}
780
781
40
const Symbol *MipsGotSection::getFirstGlobalEntry() const {
782
40
  return GlobalEntries.empty() ? 
nullptr28
:
GlobalEntries.front().first12
;
783
40
}
784
785
186
unsigned MipsGotSection::getLocalEntriesNum() const {
786
186
  return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() +
787
186
         LocalEntries32.size();
788
186
}
789
790
67
void MipsGotSection::finalizeContents() { updateAllocSize(); }
791
792
144
bool MipsGotSection::updateAllocSize() {
793
144
  PageEntriesNum = 0;
794
144
  for (std::pair<const OutputSection *, size_t> &P : PageIndexMap) {
795
18
    // For each output section referenced by GOT page relocations calculate
796
18
    // and save into PageIndexMap an upper bound of MIPS GOT entries required
797
18
    // to store page addresses of local symbols. We assume the worst case -
798
18
    // each 64kb page of the output section has at least one GOT relocation
799
18
    // against it. And take in account the case when the section intersects
800
18
    // page boundaries.
801
18
    P.second = PageEntriesNum;
802
18
    PageEntriesNum += getMipsPageCount(P.first->Size);
803
18
  }
804
144
  Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) *
805
144
         Config->Wordsize;
806
144
  return false;
807
144
}
808
809
282
bool MipsGotSection::empty() const {
810
282
  // We add the .got section to the result for dynamic MIPS target because
811
282
  // its address and properties are mentioned in the .dynamic section.
812
282
  return Config->Relocatable;
813
282
}
814
815
10.1k
uint64_t MipsGotSection::getGp() const { return ElfSym::MipsGp->getVA(0); }
816
817
67
void MipsGotSection::writeTo(uint8_t *Buf) {
818
67
  // Set the MSB of the second GOT slot. This is not required by any
819
67
  // MIPS ABI documentation, though.
820
67
  //
821
67
  // There is a comment in glibc saying that "The MSB of got[1] of a
822
67
  // gnu object is set to identify gnu objects," and in GNU gold it
823
67
  // says "the second entry will be used by some runtime loaders".
824
67
  // But how this field is being used is unclear.
825
67
  //
826
67
  // We are not really willing to mimic other linkers behaviors
827
67
  // without understanding why they do that, but because all files
828
67
  // generated by GNU tools have this special GOT value, and because
829
67
  // we've been doing this for years, it is probably a safe bet to
830
67
  // keep doing this for now. We really need to revisit this to see
831
67
  // if we had to do this.
832
67
  writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1));
833
67
  Buf += HeaderEntriesNum * Config->Wordsize;
834
67
  // Write 'page address' entries to the local part of the GOT.
835
67
  for (std::pair<const OutputSection *, size_t> &L : PageIndexMap) {
836
9
    size_t PageCount = getMipsPageCount(L.first->Size);
837
9
    uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr);
838
32
    for (size_t PI = 0; PI < PageCount; 
++PI23
) {
839
23
      uint8_t *Entry = Buf + (L.second + PI) * Config->Wordsize;
840
23
      writeUint(Entry, FirstPageAddr + PI * 0x10000);
841
23
    }
842
9
  }
843
67
  Buf += PageEntriesNum * Config->Wordsize;
844
10.0k
  auto AddEntry = [&](const GotEntry &SA) {
845
10.0k
    uint8_t *Entry = Buf;
846
10.0k
    Buf += Config->Wordsize;
847
10.0k
    const Symbol *Sym = SA.first;
848
10.0k
    uint64_t VA = Sym->getVA(SA.second);
849
10.0k
    if (Sym->StOther & STO_MIPS_MICROMIPS)
850
1
      VA |= 1;
851
10.0k
    writeUint(Entry, VA);
852
10.0k
  };
853
67
  std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry);
854
67
  std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry);
855
67
  std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry);
856
67
  // Initialize TLS-related GOT entries. If the entry has a corresponding
857
67
  // dynamic relocations, leave it initialized by zero. Write down adjusted
858
67
  // TLS symbol's values otherwise. To calculate the adjustments use offsets
859
67
  // for thread-local storage.
860
67
  // https://www.linux-mips.org/wiki/NPTL
861
67
  if (TlsIndexOff != -1U && 
!Config->Pic1
)
862
1
    writeUint(Buf + TlsIndexOff, 1);
863
67
  for (const Symbol *B : TlsEntries) {
864
5
    if (!B || 
B->IsPreemptible2
)
865
3
      continue;
866
2
    uint64_t VA = B->getVA();
867
2
    if (B->GotIndex != -1U) {
868
2
      uint8_t *Entry = Buf + B->GotIndex * Config->Wordsize;
869
2
      writeUint(Entry, VA - 0x7000);
870
2
    }
871
2
    if (B->GlobalDynIndex != -1U) {
872
2
      uint8_t *Entry = Buf + B->GlobalDynIndex * Config->Wordsize;
873
2
      writeUint(Entry, 1);
874
2
      Entry += Config->Wordsize;
875
2
      writeUint(Entry, VA - 0x8000);
876
2
    }
877
2
  }
878
67
}
879
880
GotPltSection::GotPltSection()
881
    : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
882
936
                       Target->GotPltEntrySize, ".got.plt") {}
883
884
125
void GotPltSection::addEntry(Symbol &Sym) {
885
125
  Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
886
125
  Entries.push_back(&Sym);
887
125
}
888
889
224
size_t GotPltSection::getSize() const {
890
224
  return (Target->GotPltHeaderEntriesNum + Entries.size()) *
891
224
         Target->GotPltEntrySize;
892
224
}
893
894
87
void GotPltSection::writeTo(uint8_t *Buf) {
895
87
  Target->writeGotPltHeader(Buf);
896
87
  Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
897
125
  for (const Symbol *B : Entries) {
898
125
    Target->writeGotPlt(Buf, *B);
899
125
    Buf += Config->Wordsize;
900
125
  }
901
87
}
902
903
// On ARM the IgotPltSection is part of the GotSection, on other Targets it is
904
// part of the .got.plt
905
IgotPltSection::IgotPltSection()
906
    : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
907
                       Target->GotPltEntrySize,
908
936
                       Config->EMachine == EM_ARM ? ".got" : ".got.plt") {}
909
910
21
void IgotPltSection::addEntry(Symbol &Sym) {
911
21
  Sym.IsInIgot = true;
912
21
  Sym.GotPltIndex = Entries.size();
913
21
  Entries.push_back(&Sym);
914
21
}
915
916
35
size_t IgotPltSection::getSize() const {
917
35
  return Entries.size() * Target->GotPltEntrySize;
918
35
}
919
920
12
void IgotPltSection::writeTo(uint8_t *Buf) {
921
21
  for (const Symbol *B : Entries) {
922
21
    Target->writeIgotPlt(Buf, *B);
923
21
    Buf += Config->Wordsize;
924
21
  }
925
12
}
926
927
StringTableSection::StringTableSection(StringRef Name, bool Dynamic)
928
    : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name),
929
2.80k
      Dynamic(Dynamic) {
930
2.80k
  // ELF string tables start with a NUL byte.
931
2.80k
  addString("");
932
2.80k
}
933
934
// Adds a string to the string table. If HashIt is true we hash and check for
935
// duplicates. It is optional because the name of global symbols are already
936
// uniqued and hashing them again has a big cost for a small value: uniquing
937
// them with some other string that happens to be the same.
938
90.8k
unsigned StringTableSection::addString(StringRef S, bool HashIt) {
939
90.8k
  if (HashIt) {
940
77.3k
    auto R = StringMap.insert(std::make_pair(S, this->Size));
941
77.3k
    if (!R.second)
942
206
      return R.first->second;
943
90.6k
  }
944
90.6k
  unsigned Ret = this->Size;
945
90.6k
  this->Size = this->Size + S.size() + 1;
946
90.6k
  Strings.push_back(S);
947
90.6k
  return Ret;
948
90.6k
}
949
950
2.20k
void StringTableSection::writeTo(uint8_t *Buf) {
951
89.7k
  for (StringRef S : Strings) {
952
89.7k
    memcpy(Buf, S.data(), S.size());
953
89.7k
    Buf[S.size()] = '\0';
954
89.7k
    Buf += S.size() + 1;
955
89.7k
  }
956
2.20k
}
957
958
// Returns the number of version definition entries. Because the first entry
959
// is for the version definition itself, it is the number of versioned symbols
960
// plus one. Note that we don't support multiple versions yet.
961
580
static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
962
963
template <class ELFT>
964
DynamicSection<ELFT>::DynamicSection()
965
    : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize,
966
936
                       ".dynamic") {
967
936
  this->Entsize = ELFT::Is64Bits ? 
16766
:
8170
;
968
936
969
936
  // .dynamic section is not writable on MIPS and on Fuchsia OS
970
936
  // which passes -z rodynamic.
971
936
  // See "Special Section" in Chapter 4 in the following document:
972
936
  // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
973
936
  if (Config->EMachine == EM_MIPS || 
Config->ZRodynamic862
)
974
75
    this->Flags = SHF_ALLOC;
975
936
976
936
  // Add strings to .dynstr early so that .dynstr's size will be
977
936
  // fixed early.
978
936
  for (StringRef S : Config->FilterList)
979
0
    addInt(DT_FILTER, InX::DynStrTab->addString(S));
980
936
  for (StringRef S : Config->AuxiliaryList)
981
0
    addInt(DT_AUXILIARY, InX::DynStrTab->addString(S));
982
936
983
936
  if (!Config->Rpath.empty())
984
5
    addInt(Config->EnableNewDtags ? 
DT_RUNPATH4
:
DT_RPATH1
,
985
5
           InX::DynStrTab->addString(Config->Rpath));
986
936
987
936
  for (InputFile *File : SharedFiles) {
988
144
    SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File);
989
144
    if (F->IsNeeded)
990
136
      addInt(DT_NEEDED, InX::DynStrTab->addString(F->SoName));
991
144
  }
992
936
  if (!Config->SoName.empty())
993
10
    addInt(DT_SONAME, InX::DynStrTab->addString(Config->SoName));
994
936
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::DynamicSection()
Line
Count
Source
966
118
                       ".dynamic") {
967
118
  this->Entsize = ELFT::Is64Bits ? 
160
: 8;
968
118
969
118
  // .dynamic section is not writable on MIPS and on Fuchsia OS
970
118
  // which passes -z rodynamic.
971
118
  // See "Special Section" in Chapter 4 in the following document:
972
118
  // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
973
118
  if (Config->EMachine == EM_MIPS || 
Config->ZRodynamic114
)
974
4
    this->Flags = SHF_ALLOC;
975
118
976
118
  // Add strings to .dynstr early so that .dynstr's size will be
977
118
  // fixed early.
978
118
  for (StringRef S : Config->FilterList)
979
0
    addInt(DT_FILTER, InX::DynStrTab->addString(S));
980
118
  for (StringRef S : Config->AuxiliaryList)
981
0
    addInt(DT_AUXILIARY, InX::DynStrTab->addString(S));
982
118
983
118
  if (!Config->Rpath.empty())
984
2
    addInt(Config->EnableNewDtags ? DT_RUNPATH : 
DT_RPATH0
,
985
2
           InX::DynStrTab->addString(Config->Rpath));
986
118
987
118
  for (InputFile *File : SharedFiles) {
988
31
    SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File);
989
31
    if (F->IsNeeded)
990
27
      addInt(DT_NEEDED, InX::DynStrTab->addString(F->SoName));
991
31
  }
992
118
  if (!Config->SoName.empty())
993
0
    addInt(DT_SONAME, InX::DynStrTab->addString(Config->SoName));
994
118
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::DynamicSection()
Line
Count
Source
966
52
                       ".dynamic") {
967
52
  this->Entsize = ELFT::Is64Bits ? 
160
: 8;
968
52
969
52
  // .dynamic section is not writable on MIPS and on Fuchsia OS
970
52
  // which passes -z rodynamic.
971
52
  // See "Special Section" in Chapter 4 in the following document:
972
52
  // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
973
52
  if (Config->EMachine == EM_MIPS || 
Config->ZRodynamic1
)
974
51
    this->Flags = SHF_ALLOC;
975
52
976
52
  // Add strings to .dynstr early so that .dynstr's size will be
977
52
  // fixed early.
978
52
  for (StringRef S : Config->FilterList)
979
0
    addInt(DT_FILTER, InX::DynStrTab->addString(S));
980
52
  for (StringRef S : Config->AuxiliaryList)
981
0
    addInt(DT_AUXILIARY, InX::DynStrTab->addString(S));
982
52
983
52
  if (!Config->Rpath.empty())
984
0
    addInt(Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
985
0
           InX::DynStrTab->addString(Config->Rpath));
986
52
987
52
  for (InputFile *File : SharedFiles) {
988
8
    SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File);
989
8
    if (F->IsNeeded)
990
8
      addInt(DT_NEEDED, InX::DynStrTab->addString(F->SoName));
991
8
  }
992
52
  if (!Config->SoName.empty())
993
0
    addInt(DT_SONAME, InX::DynStrTab->addString(Config->SoName));
994
52
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::DynamicSection()
Line
Count
Source
966
738
                       ".dynamic") {
967
738
  this->Entsize = ELFT::Is64Bits ? 16 : 
80
;
968
738
969
738
  // .dynamic section is not writable on MIPS and on Fuchsia OS
970
738
  // which passes -z rodynamic.
971
738
  // See "Special Section" in Chapter 4 in the following document:
972
738
  // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
973
738
  if (Config->EMachine == EM_MIPS || Config->ZRodynamic)
974
1
    this->Flags = SHF_ALLOC;
975
738
976
738
  // Add strings to .dynstr early so that .dynstr's size will be
977
738
  // fixed early.
978
738
  for (StringRef S : Config->FilterList)
979
0
    addInt(DT_FILTER, InX::DynStrTab->addString(S));
980
738
  for (StringRef S : Config->AuxiliaryList)
981
0
    addInt(DT_AUXILIARY, InX::DynStrTab->addString(S));
982
738
983
738
  if (!Config->Rpath.empty())
984
2
    addInt(Config->EnableNewDtags ? 
DT_RUNPATH1
:
DT_RPATH1
,
985
2
           InX::DynStrTab->addString(Config->Rpath));
986
738
987
738
  for (InputFile *File : SharedFiles) {
988
101
    SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File);
989
101
    if (F->IsNeeded)
990
97
      addInt(DT_NEEDED, InX::DynStrTab->addString(F->SoName));
991
101
  }
992
738
  if (!Config->SoName.empty())
993
10
    addInt(DT_SONAME, InX::DynStrTab->addString(Config->SoName));
994
738
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::DynamicSection()
Line
Count
Source
966
28
                       ".dynamic") {
967
28
  this->Entsize = ELFT::Is64Bits ? 16 : 
80
;
968
28
969
28
  // .dynamic section is not writable on MIPS and on Fuchsia OS
970
28
  // which passes -z rodynamic.
971
28
  // See "Special Section" in Chapter 4 in the following document:
972
28
  // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
973
28
  if (Config->EMachine == EM_MIPS || 
Config->ZRodynamic9
)
974
19
    this->Flags = SHF_ALLOC;
975
28
976
28
  // Add strings to .dynstr early so that .dynstr's size will be
977
28
  // fixed early.
978
28
  for (StringRef S : Config->FilterList)
979
0
    addInt(DT_FILTER, InX::DynStrTab->addString(S));
980
28
  for (StringRef S : Config->AuxiliaryList)
981
0
    addInt(DT_AUXILIARY, InX::DynStrTab->addString(S));
982
28
983
28
  if (!Config->Rpath.empty())
984
1
    addInt(Config->EnableNewDtags ? DT_RUNPATH : 
DT_RPATH0
,
985
1
           InX::DynStrTab->addString(Config->Rpath));
986
28
987
28
  for (InputFile *File : SharedFiles) {
988
4
    SharedFile<ELFT> *F = cast<SharedFile<ELFT>>(File);
989
4
    if (F->IsNeeded)
990
4
      addInt(DT_NEEDED, InX::DynStrTab->addString(F->SoName));
991
4
  }
992
28
  if (!Config->SoName.empty())
993
0
    addInt(DT_SONAME, InX::DynStrTab->addString(Config->SoName));
994
28
}
995
996
template <class ELFT>
997
40
void DynamicSection<ELFT>::add(int32_t Tag, std::function<uint64_t()> Fn) {
998
40
  Entries.push_back({Tag, Fn});
999
40
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::add(int, std::__1::function<unsigned long long ()>)
Line
Count
Source
997
2
void DynamicSection<ELFT>::add(int32_t Tag, std::function<uint64_t()> Fn) {
998
2
  Entries.push_back({Tag, Fn});
999
2
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::add(int, std::__1::function<unsigned long long ()>)
Line
Count
Source
997
27
void DynamicSection<ELFT>::add(int32_t Tag, std::function<uint64_t()> Fn) {
998
27
  Entries.push_back({Tag, Fn});
999
27
}
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
997
11
void DynamicSection<ELFT>::add(int32_t Tag, std::function<uint64_t()> Fn) {
998
11
  Entries.push_back({Tag, Fn});
999
11
}
1000
1001
template <class ELFT>
1002
2.07k
void DynamicSection<ELFT>::addInt(int32_t Tag, uint64_t Val) {
1003
2.07k
  Entries.push_back({Tag, [=] 
{ return Val; }2.04k
});
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addInt(int, unsigned long long)::'lambda'()::operator()() const
Line
Count
Source
1003
318
  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
1003
238
  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
1003
1.36k
  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
1003
126
  Entries.push_back({Tag, [=] { return Val; }});
1004
2.07k
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addInt(int, unsigned long long)
Line
Count
Source
1002
318
void DynamicSection<ELFT>::addInt(int32_t Tag, uint64_t Val) {
1003
318
  Entries.push_back({Tag, [=] { return Val; }});
1004
318
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addInt(int, unsigned long long)
Line
Count
Source
1002
238
void DynamicSection<ELFT>::addInt(int32_t Tag, uint64_t Val) {
1003
238
  Entries.push_back({Tag, [=] { return Val; }});
1004
238
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addInt(int, unsigned long long)
Line
Count
Source
1002
1.39k
void DynamicSection<ELFT>::addInt(int32_t Tag, uint64_t Val) {
1003
1.39k
  Entries.push_back({Tag, [=] { return Val; }});
1004
1.39k
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addInt(int, unsigned long long)
Line
Count
Source
1002
126
void DynamicSection<ELFT>::addInt(int32_t Tag, uint64_t Val) {
1003
126
  Entries.push_back({Tag, [=] { return Val; }});
1004
126
}
1005
1006
template <class ELFT>
1007
2.08k
void DynamicSection<ELFT>::addInSec(int32_t Tag, InputSection *Sec) {
1008
2.08k
  Entries.push_back(
1009
2.08k
      {Tag, [=] 
{ return Sec->getParent()->Addr + Sec->OutSecOff; }2.06k
});
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addInSec(int, lld::elf::InputSection*)::'lambda'()::operator()() const
Line
Count
Source
1009
305
      {Tag, [=] { return Sec->getParent()->Addr + Sec->OutSecOff; }});
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addInSec(int, lld::elf::InputSection*)::'lambda'()::operator()() const
Line
Count
Source
1009
124
      {Tag, [=] { return Sec->getParent()->Addr + Sec->OutSecOff; }});
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addInSec(int, lld::elf::InputSection*)::'lambda'()::operator()() const
Line
Count
Source
1009
1.55k
      {Tag, [=] { return Sec->getParent()->Addr + Sec->OutSecOff; }});
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addInSec(int, lld::elf::InputSection*)::'lambda'()::operator()() const
Line
Count
Source
1009
81
      {Tag, [=] { return Sec->getParent()->Addr + Sec->OutSecOff; }});
1010
2.08k
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addInSec(int, lld::elf::InputSection*)
Line
Count
Source
1007
305
void DynamicSection<ELFT>::addInSec(int32_t Tag, InputSection *Sec) {
1008
305
  Entries.push_back(
1009
305
      {Tag, [=] { return Sec->getParent()->Addr + Sec->OutSecOff; }});
1010
305
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addInSec(int, lld::elf::InputSection*)
Line
Count
Source
1007
124
void DynamicSection<ELFT>::addInSec(int32_t Tag, InputSection *Sec) {
1008
124
  Entries.push_back(
1009
124
      {Tag, [=] { return Sec->getParent()->Addr + Sec->OutSecOff; }});
1010
124
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addInSec(int, lld::elf::InputSection*)
Line
Count
Source
1007
1.57k
void DynamicSection<ELFT>::addInSec(int32_t Tag, InputSection *Sec) {
1008
1.57k
  Entries.push_back(
1009
1.57k
      {Tag, [=] { return Sec->getParent()->Addr + Sec->OutSecOff; }});
1010
1.57k
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addInSec(int, lld::elf::InputSection*)
Line
Count
Source
1007
81
void DynamicSection<ELFT>::addInSec(int32_t Tag, InputSection *Sec) {
1008
81
  Entries.push_back(
1009
81
      {Tag, [=] { return Sec->getParent()->Addr + Sec->OutSecOff; }});
1010
81
}
1011
1012
template <class ELFT>
1013
8
void DynamicSection<ELFT>::addOutSec(int32_t Tag, OutputSection *Sec) {
1014
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
1014
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
1015
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
1013
8
void DynamicSection<ELFT>::addOutSec(int32_t Tag, OutputSection *Sec) {
1014
8
  Entries.push_back({Tag, [=] { return Sec->Addr; }});
1015
8
}
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addOutSec(int, lld::elf::OutputSection*)
1016
1017
template <class ELFT>
1018
187
void DynamicSection<ELFT>::addSize(int32_t Tag, OutputSection *Sec) {
1019
187
  Entries.push_back({Tag, [=] 
{ return Sec->Size; }186
});
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addSize(int, lld::elf::OutputSection*)::'lambda'()::operator()() const
Line
Count
Source
1019
45
  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
1019
4
  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
1019
129
  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
1019
8
  Entries.push_back({Tag, [=] { return Sec->Size; }});
1020
187
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addSize(int, lld::elf::OutputSection*)
Line
Count
Source
1018
45
void DynamicSection<ELFT>::addSize(int32_t Tag, OutputSection *Sec) {
1019
45
  Entries.push_back({Tag, [=] { return Sec->Size; }});
1020
45
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addSize(int, lld::elf::OutputSection*)
Line
Count
Source
1018
4
void DynamicSection<ELFT>::addSize(int32_t Tag, OutputSection *Sec) {
1019
4
  Entries.push_back({Tag, [=] { return Sec->Size; }});
1020
4
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addSize(int, lld::elf::OutputSection*)
Line
Count
Source
1018
130
void DynamicSection<ELFT>::addSize(int32_t Tag, OutputSection *Sec) {
1019
130
  Entries.push_back({Tag, [=] { return Sec->Size; }});
1020
130
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addSize(int, lld::elf::OutputSection*)
Line
Count
Source
1018
8
void DynamicSection<ELFT>::addSize(int32_t Tag, OutputSection *Sec) {
1019
8
  Entries.push_back({Tag, [=] { return Sec->Size; }});
1020
8
}
1021
1022
template <class ELFT>
1023
0
void DynamicSection<ELFT>::addSym(int32_t Tag, Symbol *Sym) {
1024
0
  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
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addSym(int, lld::elf::Symbol*)::'lambda'()::operator()() const
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addSym(int, lld::elf::Symbol*)::'lambda'()::operator()() const
1025
0
}
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*)
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addSym(int, lld::elf::Symbol*)
Unexecuted instantiation: lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addSym(int, lld::elf::Symbol*)
1026
1027
// Add remaining entries to complete .dynamic contents.
1028
457
template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1029
457
  if (this->Size)
1030
0
    return; // Already finalized.
1031
457
1032
457
  // Set DT_FLAGS and DT_FLAGS_1.
1033
457
  uint32_t DtFlags = 0;
1034
457
  uint32_t DtFlags1 = 0;
1035
457
  if (Config->Bsymbolic)
1036
3
    DtFlags |= DF_SYMBOLIC;
1037
457
  if (Config->ZNodelete)
1038
0
    DtFlags1 |= DF_1_NODELETE;
1039
457
  if (Config->ZNodlopen)
1040
0
    DtFlags1 |= DF_1_NOOPEN;
1041
457
  if (Config->ZNow) {
1042
1
    DtFlags |= DF_BIND_NOW;
1043
1
    DtFlags1 |= DF_1_NOW;
1044
1
  }
1045
457
  if (Config->ZOrigin) {
1046
0
    DtFlags |= DF_ORIGIN;
1047
0
    DtFlags1 |= DF_1_ORIGIN;
1048
0
  }
1049
457
1050
457
  if (DtFlags)
1051
4
    addInt(DT_FLAGS, DtFlags);
1052
457
  if (DtFlags1)
1053
1
    addInt(DT_FLAGS_1, DtFlags1);
1054
457
1055
457
  // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1056
457
  // need it for each process, so we don't write it for DSOs. The loader writes
1057
457
  // the pointer into this entry.
1058
457
  //
1059
457
  // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1060
457
  // systems (currently only Fuchsia OS) provide other means to give the
1061
457
  // debugger this information. Such systems may choose make .dynamic read-only.
1062
457
  // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1063
457
  if (!Config->Shared && 
!Config->Relocatable120
&&
!Config->ZRodynamic119
)
1064
118
    addInt(DT_DEBUG, 0);
1065
457
1066
457
  this->Link = InX::DynStrTab->getParent()->SectionIndex;
1067
457
  if (!InX::RelaDyn->empty()) {
1068
91
    addInSec(InX::RelaDyn->DynamicTag, InX::RelaDyn);
1069
91
    addSize(InX::RelaDyn->SizeDynamicTag, InX::RelaDyn->getParent());
1070
91
1071
91
    bool IsRela = Config->IsRela;
1072
91
    addInt(IsRela ? 
DT_RELAENT59
:
DT_RELENT32
,
1073
91
           IsRela ? 
sizeof(Elf_Rela)59
:
sizeof(Elf_Rel)32
);
1074
91
1075
91
    // MIPS dynamic loader does not support RELCOUNT tag.
1076
91
    // The problem is in the tight relation between dynamic
1077
91
    // relocations and GOT. So do not emit this tag on MIPS.
1078
91
    if (Config->EMachine != EM_MIPS) {
1079
87
      size_t NumRelativeRels = InX::RelaDyn->getRelativeRelocCount();
1080
87
      if (Config->ZCombreloc && NumRelativeRels)
1081
19
        addInt(IsRela ? 
DT_RELACOUNT11
:
DT_RELCOUNT8
, NumRelativeRels);
1082
87
    }
1083
91
  }
1084
457
  // .rel[a].plt section usually consists of two parts, containing plt and
1085
457
  // iplt relocations. It is possible to have only iplt relocations in the
1086
457
  // output. In that case RelaPlt is empty and have zero offset, the same offset
1087
457
  // as RelaIplt have. And we still want to emit proper dynamic tags for that
1088
457
  // case, so here we always use RelaPlt as marker for the begining of
1089
457
  // .rel[a].plt section.
1090
457
  if (InX::RelaPlt->getParent()->Live) {
1091
88
    addInSec(DT_JMPREL, InX::RelaPlt);
1092
88
    addSize(DT_PLTRELSZ, InX::RelaPlt->getParent());
1093
88
    switch (Config->EMachine) {
1094
88
    case EM_MIPS:
1095
5
      addInSec(DT_MIPS_PLTGOT, InX::GotPlt);
1096
5
      break;
1097
88
    case EM_SPARCV9:
1098
0
      addInSec(DT_PLTGOT, InX::Plt);
1099
0
      break;
1100
88
    default:
1101
83
      addInSec(DT_PLTGOT, InX::GotPlt);
1102
83
      break;
1103
88
    }
1104
88
    addInt(DT_PLTREL, Config->IsRela ? 
DT_RELA71
:
DT_REL17
);
1105
88
  }
1106
457
1107
457
  addInSec(DT_SYMTAB, InX::DynSymTab);
1108
457
  addInt(DT_SYMENT, sizeof(Elf_Sym));
1109
457
  addInSec(DT_STRTAB, InX::DynStrTab);
1110
457
  addInt(DT_STRSZ, InX::DynStrTab->getSize());
1111
457
  if (!Config->ZText)
1112
5
    addInt(DT_TEXTREL, 0);
1113
457
  if (InX::GnuHashTab)
1114
344
    addInSec(DT_GNU_HASH, InX::GnuHashTab);
1115
457
  if (InX::HashTab)
1116
453
    addInSec(DT_HASH, InX::HashTab);
1117
457
1118
457
  if (Out::PreinitArray) {
1119
3
    addOutSec(DT_PREINIT_ARRAY, Out::PreinitArray);
1120
3
    addSize(DT_PREINIT_ARRAYSZ, Out::PreinitArray);
1121
3
  }
1122
457
  if (Out::InitArray) {
1123
3
    addOutSec(DT_INIT_ARRAY, Out::InitArray);
1124
3
    addSize(DT_INIT_ARRAYSZ, Out::InitArray);
1125
3
  }
1126
457
  if (Out::FiniArray) {
1127
2
    addOutSec(DT_FINI_ARRAY, Out::FiniArray);
1128
2
    addSize(DT_FINI_ARRAYSZ, Out::FiniArray);
1129
2
  }
1130
457
1131
457
  if (Symbol *B = Symtab->find(Config->Init))
1132
1
    if (B->isDefined())
1133
0
      addSym(DT_INIT, B);
1134
457
  if (Symbol *B = Symtab->find(Config->Fini))
1135
1
    if (B->isDefined())
1136
0
      addSym(DT_FINI, B);
1137
457
1138
457
  bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1139
457
  if (HasVerNeed || 
In<ELFT>::VerDef453
)
1140
26
    addInSec(DT_VERSYM, In<ELFT>::VerSym);
1141
457
  if (In<ELFT>::VerDef) {
1142
23
    addInSec(DT_VERDEF, In<ELFT>::VerDef);
1143
23
    addInt(DT_VERDEFNUM, getVerDefNum());
1144
23
  }
1145
457
  if (HasVerNeed) {
1146
4
    addInSec(DT_VERNEED, In<ELFT>::VerNeed);
1147
4
    addInt(DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum());
1148
4
  }
1149
457
1150
457
  if (Config->EMachine == EM_MIPS) {
1151
40
    addInt(DT_MIPS_RLD_VERSION, 1);
1152
40
    addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1153
40
    addInt(DT_MIPS_BASE_ADDRESS, Target->getImageBase());
1154
40
    addInt(DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols());
1155
40
1156
40
    add(DT_MIPS_LOCAL_GOTNO, [] { return InX::MipsGot->getLocalEntriesNum(); });
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::finalizeContents()::'lambda'()::operator()() const
Line
Count
Source
1156
2
    add(DT_MIPS_LOCAL_GOTNO, [] { return InX::MipsGot->getLocalEntriesNum(); });
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::finalizeContents()::'lambda'()::operator()() const
Line
Count
Source
1156
27
    add(DT_MIPS_LOCAL_GOTNO, [] { return InX::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
1156
11
    add(DT_MIPS_LOCAL_GOTNO, [] { return InX::MipsGot->getLocalEntriesNum(); });
1157
40
1158
40
    if (const Symbol *B = InX::MipsGot->getFirstGlobalEntry())
1159
12
      addInt(DT_MIPS_GOTSYM, B->DynsymIndex);
1160
28
    else
1161
28
      addInt(DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols());
1162
40
    addInSec(DT_PLTGOT, InX::MipsGot);
1163
40
    if (InX::MipsRldMap)
1164
10
      addInSec(DT_MIPS_RLD_MAP, InX::MipsRldMap);
1165
40
  }
1166
457
1167
457
  addInt(DT_NULL, 0);
1168
457
1169
457
  getParent()->Link = this->Link;
1170
457
  this->Size = Entries.size() * this->Entsize;
1171
457
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::finalizeContents()
Line
Count
Source
1028
67
template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1029
67
  if (this->Size)
1030
0
    return; // Already finalized.
1031
67
1032
67
  // Set DT_FLAGS and DT_FLAGS_1.
1033
67
  uint32_t DtFlags = 0;
1034
67
  uint32_t DtFlags1 = 0;
1035
67
  if (Config->Bsymbolic)
1036
1
    DtFlags |= DF_SYMBOLIC;
1037
67
  if (Config->ZNodelete)
1038
0
    DtFlags1 |= DF_1_NODELETE;
1039
67
  if (Config->ZNodlopen)
1040
0
    DtFlags1 |= DF_1_NOOPEN;
1041
67
  if (Config->ZNow) {
1042
0
    DtFlags |= DF_BIND_NOW;
1043
0
    DtFlags1 |= DF_1_NOW;
1044
0
  }
1045
67
  if (Config->ZOrigin) {
1046
0
    DtFlags |= DF_ORIGIN;
1047
0
    DtFlags1 |= DF_1_ORIGIN;
1048
0
  }
1049
67
1050
67
  if (DtFlags)
1051
1
    addInt(DT_FLAGS, DtFlags);
1052
67
  if (DtFlags1)
1053
0
    addInt(DT_FLAGS_1, DtFlags1);
1054
67
1055
67
  // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1056
67
  // need it for each process, so we don't write it for DSOs. The loader writes
1057
67
  // the pointer into this entry.
1058
67
  //
1059
67
  // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1060
67
  // systems (currently only Fuchsia OS) provide other means to give the
1061
67
  // debugger this information. Such systems may choose make .dynamic read-only.
1062
67
  // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1063
67
  if (!Config->Shared && 
!Config->Relocatable24
&&
!Config->ZRodynamic24
)
1064
24
    addInt(DT_DEBUG, 0);
1065
67
1066
67
  this->Link = InX::DynStrTab->getParent()->SectionIndex;
1067
67
  if (!InX::RelaDyn->empty()) {
1068
31
    addInSec(InX::RelaDyn->DynamicTag, InX::RelaDyn);
1069
31
    addSize(InX::RelaDyn->SizeDynamicTag, InX::RelaDyn->getParent());
1070
31
1071
31
    bool IsRela = Config->IsRela;
1072
31
    addInt(IsRela ? 
DT_RELAENT0
: DT_RELENT,
1073
31
           IsRela ? 
sizeof(Elf_Rela)0
: sizeof(Elf_Rel));
1074
31
1075
31
    // MIPS dynamic loader does not support RELCOUNT tag.
1076
31
    // The problem is in the tight relation between dynamic
1077
31
    // relocations and GOT. So do not emit this tag on MIPS.
1078
31
    if (Config->EMachine != EM_MIPS) {
1079
30
      size_t NumRelativeRels = InX::RelaDyn->getRelativeRelocCount();
1080
30
      if (Config->ZCombreloc && NumRelativeRels)
1081
8
        addInt(IsRela ? 
DT_RELACOUNT0
: DT_RELCOUNT, NumRelativeRels);
1082
30
    }
1083
31
  }
1084
67
  // .rel[a].plt section usually consists of two parts, containing plt and
1085
67
  // iplt relocations. It is possible to have only iplt relocations in the
1086
67
  // output. In that case RelaPlt is empty and have zero offset, the same offset
1087
67
  // as RelaIplt have. And we still want to emit proper dynamic tags for that
1088
67
  // case, so here we always use RelaPlt as marker for the begining of
1089
67
  // .rel[a].plt section.
1090
67
  if (InX::RelaPlt->getParent()->Live) {
1091
14
    addInSec(DT_JMPREL, InX::RelaPlt);
1092
14
    addSize(DT_PLTRELSZ, InX::RelaPlt->getParent());
1093
14
    switch (Config->EMachine) {
1094
14
    case EM_MIPS:
1095
1
      addInSec(DT_MIPS_PLTGOT, InX::GotPlt);
1096
1
      break;
1097
14
    case EM_SPARCV9:
1098
0
      addInSec(DT_PLTGOT, InX::Plt);
1099
0
      break;
1100
14
    default:
1101
13
      addInSec(DT_PLTGOT, InX::GotPlt);
1102
13
      break;
1103
14
    }
1104
14
    addInt(DT_PLTREL, Config->IsRela ? 
DT_RELA0
: DT_REL);
1105
14
  }
1106
67
1107
67
  addInSec(DT_SYMTAB, InX::DynSymTab);
1108
67
  addInt(DT_SYMENT, sizeof(Elf_Sym));
1109
67
  addInSec(DT_STRTAB, InX::DynStrTab);
1110
67
  addInt(DT_STRSZ, InX::DynStrTab->getSize());
1111
67
  if (!Config->ZText)
1112
0
    addInt(DT_TEXTREL, 0);
1113
67
  if (InX::GnuHashTab)
1114
44
    addInSec(DT_GNU_HASH, InX::GnuHashTab);
1115
67
  if (InX::HashTab)
1116
65
    addInSec(DT_HASH, InX::HashTab);
1117
67
1118
67
  if (Out::PreinitArray) {
1119
0
    addOutSec(DT_PREINIT_ARRAY, Out::PreinitArray);
1120
0
    addSize(DT_PREINIT_ARRAYSZ, Out::PreinitArray);
1121
0
  }
1122
67
  if (Out::InitArray) {
1123
0
    addOutSec(DT_INIT_ARRAY, Out::InitArray);
1124
0
    addSize(DT_INIT_ARRAYSZ, Out::InitArray);
1125
0
  }
1126
67
  if (Out::FiniArray) {
1127
0
    addOutSec(DT_FINI_ARRAY, Out::FiniArray);
1128
0
    addSize(DT_FINI_ARRAYSZ, Out::FiniArray);
1129
0
  }
1130
67
1131
67
  if (Symbol *B = Symtab->find(Config->Init))
1132
0
    if (B->isDefined())
1133
0
      addSym(DT_INIT, B);
1134
67
  if (Symbol *B = Symtab->find(Config->Fini))
1135
0
    if (B->isDefined())
1136
0
      addSym(DT_FINI, B);
1137
67
1138
67
  bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1139
67
  if (HasVerNeed || In<ELFT>::VerDef)
1140
0
    addInSec(DT_VERSYM, In<ELFT>::VerSym);
1141
67
  if (In<ELFT>::VerDef) {
1142
0
    addInSec(DT_VERDEF, In<ELFT>::VerDef);
1143
0
    addInt(DT_VERDEFNUM, getVerDefNum());
1144
0
  }
1145
67
  if (HasVerNeed) {
1146
0
    addInSec(DT_VERNEED, In<ELFT>::VerNeed);
1147
0
    addInt(DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum());
1148
0
  }
1149
67
1150
67
  if (Config->EMachine == EM_MIPS) {
1151
2
    addInt(DT_MIPS_RLD_VERSION, 1);
1152
2
    addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1153
2
    addInt(DT_MIPS_BASE_ADDRESS, Target->getImageBase());
1154
2
    addInt(DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols());
1155
2
1156
2
    add(DT_MIPS_LOCAL_GOTNO, [] { return InX::MipsGot->getLocalEntriesNum(); });
1157
2
1158
2
    if (const Symbol *B = InX::MipsGot->getFirstGlobalEntry())
1159
1
      addInt(DT_MIPS_GOTSYM, B->DynsymIndex);
1160
1
    else
1161
1
      addInt(DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols());
1162
2
    addInSec(DT_PLTGOT, InX::MipsGot);
1163
2
    if (InX::MipsRldMap)
1164
1
      addInSec(DT_MIPS_RLD_MAP, InX::MipsRldMap);
1165
2
  }
1166
67
1167
67
  addInt(DT_NULL, 0);
1168
67
1169
67
  getParent()->Link = this->Link;
1170
67
  this->Size = Entries.size() * this->Entsize;
1171
67
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::finalizeContents()
Line
Count
Source
1028
28
template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1029
28
  if (this->Size)
1030
0
    return; // Already finalized.
1031
28
1032
28
  // Set DT_FLAGS and DT_FLAGS_1.
1033
28
  uint32_t DtFlags = 0;
1034
28
  uint32_t DtFlags1 = 0;
1035
28
  if (Config->Bsymbolic)
1036
1
    DtFlags |= DF_SYMBOLIC;
1037
28
  if (Config->ZNodelete)
1038
0
    DtFlags1 |= DF_1_NODELETE;
1039
28
  if (Config->ZNodlopen)
1040
0
    DtFlags1 |= DF_1_NOOPEN;
1041
28
  if (Config->ZNow) {
1042
0
    DtFlags |= DF_BIND_NOW;
1043
0
    DtFlags1 |= DF_1_NOW;
1044
0
  }
1045
28
  if (Config->ZOrigin) {
1046
0
    DtFlags |= DF_ORIGIN;
1047
0
    DtFlags1 |= DF_1_ORIGIN;
1048
0
  }
1049
28
1050
28
  if (DtFlags)
1051
1
    addInt(DT_FLAGS, DtFlags);
1052
28
  if (DtFlags1)
1053
0
    addInt(DT_FLAGS_1, DtFlags1);
1054
28
1055
28
  // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1056
28
  // need it for each process, so we don't write it for DSOs. The loader writes
1057
28
  // the pointer into this entry.
1058
28
  //
1059
28
  // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1060
28
  // systems (currently only Fuchsia OS) provide other means to give the
1061
28
  // debugger this information. Such systems may choose make .dynamic read-only.
1062
28
  // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1063
28
  if (!Config->Shared && 
!Config->Relocatable6
&&
!Config->ZRodynamic6
)
1064
6
    addInt(DT_DEBUG, 0);
1065
28
1066
28
  this->Link = InX::DynStrTab->getParent()->SectionIndex;
1067
28
  if (!InX::RelaDyn->empty()) {
1068
1
    addInSec(InX::RelaDyn->DynamicTag, InX::RelaDyn);
1069
1
    addSize(InX::RelaDyn->SizeDynamicTag, InX::RelaDyn->getParent());
1070
1
1071
1
    bool IsRela = Config->IsRela;
1072
1
    addInt(IsRela ? 
DT_RELAENT0
: DT_RELENT,
1073
1
           IsRela ? 
sizeof(Elf_Rela)0
: sizeof(Elf_Rel));
1074
1
1075
1
    // MIPS dynamic loader does not support RELCOUNT tag.
1076
1
    // The problem is in the tight relation between dynamic
1077
1
    // relocations and GOT. So do not emit this tag on MIPS.
1078
1
    if (Config->EMachine != EM_MIPS) {
1079
0
      size_t NumRelativeRels = InX::RelaDyn->getRelativeRelocCount();
1080
0
      if (Config->ZCombreloc && NumRelativeRels)
1081
0
        addInt(IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels);
1082
0
    }
1083
1
  }
1084
28
  // .rel[a].plt section usually consists of two parts, containing plt and
1085
28
  // iplt relocations. It is possible to have only iplt relocations in the
1086
28
  // output. In that case RelaPlt is empty and have zero offset, the same offset
1087
28
  // as RelaIplt have. And we still want to emit proper dynamic tags for that
1088
28
  // case, so here we always use RelaPlt as marker for the begining of
1089
28
  // .rel[a].plt section.
1090
28
  if (InX::RelaPlt->getParent()->Live) {
1091
3
    addInSec(DT_JMPREL, InX::RelaPlt);
1092
3
    addSize(DT_PLTRELSZ, InX::RelaPlt->getParent());
1093
3
    switch (Config->EMachine) {
1094
3
    case EM_MIPS:
1095
3
      addInSec(DT_MIPS_PLTGOT, InX::GotPlt);
1096
3
      break;
1097
3
    case EM_SPARCV9:
1098
0
      addInSec(DT_PLTGOT, InX::Plt);
1099
0
      break;
1100
3
    default:
1101
0
      addInSec(DT_PLTGOT, InX::GotPlt);
1102
0
      break;
1103
3
    }
1104
3
    addInt(DT_PLTREL, Config->IsRela ? 
DT_RELA0
: DT_REL);
1105
3
  }
1106
28
1107
28
  addInSec(DT_SYMTAB, InX::DynSymTab);
1108
28
  addInt(DT_SYMENT, sizeof(Elf_Sym));
1109
28
  addInSec(DT_STRTAB, InX::DynStrTab);
1110
28
  addInt(DT_STRSZ, InX::DynStrTab->getSize());
1111
28
  if (!Config->ZText)
1112
0
    addInt(DT_TEXTREL, 0);
1113
28
  if (InX::GnuHashTab)
1114
0
    addInSec(DT_GNU_HASH, InX::GnuHashTab);
1115
28
  if (InX::HashTab)
1116
28
    addInSec(DT_HASH, InX::HashTab);
1117
28
1118
28
  if (Out::PreinitArray) {
1119
0
    addOutSec(DT_PREINIT_ARRAY, Out::PreinitArray);
1120
0
    addSize(DT_PREINIT_ARRAYSZ, Out::PreinitArray);
1121
0
  }
1122
28
  if (Out::InitArray) {
1123
0
    addOutSec(DT_INIT_ARRAY, Out::InitArray);
1124
0
    addSize(DT_INIT_ARRAYSZ, Out::InitArray);
1125
0
  }
1126
28
  if (Out::FiniArray) {
1127
0
    addOutSec(DT_FINI_ARRAY, Out::FiniArray);
1128
0
    addSize(DT_FINI_ARRAYSZ, Out::FiniArray);
1129
0
  }
1130
28
1131
28
  if (Symbol *B = Symtab->find(Config->Init))
1132
0
    if (B->isDefined())
1133
0
      addSym(DT_INIT, B);
1134
28
  if (Symbol *B = Symtab->find(Config->Fini))
1135
0
    if (B->isDefined())
1136
0
      addSym(DT_FINI, B);
1137
28
1138
28
  bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1139
28
  if (HasVerNeed || In<ELFT>::VerDef)
1140
0
    addInSec(DT_VERSYM, In<ELFT>::VerSym);
1141
28
  if (In<ELFT>::VerDef) {
1142
0
    addInSec(DT_VERDEF, In<ELFT>::VerDef);
1143
0
    addInt(DT_VERDEFNUM, getVerDefNum());
1144
0
  }
1145
28
  if (HasVerNeed) {
1146
0
    addInSec(DT_VERNEED, In<ELFT>::VerNeed);
1147
0
    addInt(DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum());
1148
0
  }
1149
28
1150
28
  if (Config->EMachine == EM_MIPS) {
1151
27
    addInt(DT_MIPS_RLD_VERSION, 1);
1152
27
    addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1153
27
    addInt(DT_MIPS_BASE_ADDRESS, Target->getImageBase());
1154
27
    addInt(DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols());
1155
27
1156
27
    add(DT_MIPS_LOCAL_GOTNO, [] { return InX::MipsGot->getLocalEntriesNum(); });
1157
27
1158
27
    if (const Symbol *B = InX::MipsGot->getFirstGlobalEntry())
1159
9
      addInt(DT_MIPS_GOTSYM, B->DynsymIndex);
1160
18
    else
1161
18
      addInt(DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols());
1162
27
    addInSec(DT_PLTGOT, InX::MipsGot);
1163
27
    if (InX::MipsRldMap)
1164
6
      addInSec(DT_MIPS_RLD_MAP, InX::MipsRldMap);
1165
27
  }
1166
28
1167
28
  addInt(DT_NULL, 0);
1168
28
1169
28
  getParent()->Link = this->Link;
1170
28
  this->Size = Entries.size() * this->Entsize;
1171
28
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::finalizeContents()
Line
Count
Source
1028
345
template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1029
345
  if (this->Size)
1030
0
    return; // Already finalized.
1031
345
1032
345
  // Set DT_FLAGS and DT_FLAGS_1.
1033
345
  uint32_t DtFlags = 0;
1034
345
  uint32_t DtFlags1 = 0;
1035
345
  if (Config->Bsymbolic)
1036
1
    DtFlags |= DF_SYMBOLIC;
1037
345
  if (Config->ZNodelete)
1038
0
    DtFlags1 |= DF_1_NODELETE;
1039
345
  if (Config->ZNodlopen)
1040
0
    DtFlags1 |= DF_1_NOOPEN;
1041
345
  if (Config->ZNow) {
1042
1
    DtFlags |= DF_BIND_NOW;
1043
1
    DtFlags1 |= DF_1_NOW;
1044
1
  }
1045
345
  if (Config->ZOrigin) {
1046
0
    DtFlags |= DF_ORIGIN;
1047
0
    DtFlags1 |= DF_1_ORIGIN;
1048
0
  }
1049
345
1050
345
  if (DtFlags)
1051
2
    addInt(DT_FLAGS, DtFlags);
1052
345
  if (DtFlags1)
1053
1
    addInt(DT_FLAGS_1, DtFlags1);
1054
345
1055
345
  // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1056
345
  // need it for each process, so we don't write it for DSOs. The loader writes
1057
345
  // the pointer into this entry.
1058
345
  //
1059
345
  // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1060
345
  // systems (currently only Fuchsia OS) provide other means to give the
1061
345
  // debugger this information. Such systems may choose make .dynamic read-only.
1062
345
  // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1063
345
  if (!Config->Shared && 
!Config->Relocatable86
&&
!Config->ZRodynamic85
)
1064
84
    addInt(DT_DEBUG, 0);
1065
345
1066
345
  this->Link = InX::DynStrTab->getParent()->SectionIndex;
1067
345
  if (!InX::RelaDyn->empty()) {
1068
53
    addInSec(InX::RelaDyn->DynamicTag, InX::RelaDyn);
1069
53
    addSize(InX::RelaDyn->SizeDynamicTag, InX::RelaDyn->getParent());
1070
53
1071
53
    bool IsRela = Config->IsRela;
1072
53
    addInt(IsRela ? DT_RELAENT : 
DT_RELENT0
,
1073
53
           IsRela ? sizeof(Elf_Rela) : 
sizeof(Elf_Rel)0
);
1074
53
1075
53
    // MIPS dynamic loader does not support RELCOUNT tag.
1076
53
    // The problem is in the tight relation between dynamic
1077
53
    // relocations and GOT. So do not emit this tag on MIPS.
1078
53
    if (Config->EMachine != EM_MIPS) {
1079
53
      size_t NumRelativeRels = InX::RelaDyn->getRelativeRelocCount();
1080
53
      if (Config->ZCombreloc && NumRelativeRels)
1081
10
        addInt(IsRela ? DT_RELACOUNT : 
DT_RELCOUNT0
, NumRelativeRels);
1082
53
    }
1083
53
  }
1084
345
  // .rel[a].plt section usually consists of two parts, containing plt and
1085
345
  // iplt relocations. It is possible to have only iplt relocations in the
1086
345
  // output. In that case RelaPlt is empty and have zero offset, the same offset
1087
345
  // as RelaIplt have. And we still want to emit proper dynamic tags for that
1088
345
  // case, so here we always use RelaPlt as marker for the begining of
1089
345
  // .rel[a].plt section.
1090
345
  if (InX::RelaPlt->getParent()->Live) {
1091
69
    addInSec(DT_JMPREL, InX::RelaPlt);
1092
69
    addSize(DT_PLTRELSZ, InX::RelaPlt->getParent());
1093
69
    switch (Config->EMachine) {
1094
69
    case EM_MIPS:
1095
0
      addInSec(DT_MIPS_PLTGOT, InX::GotPlt);
1096
0
      break;
1097
69
    case EM_SPARCV9:
1098
0
      addInSec(DT_PLTGOT, InX::Plt);
1099
0
      break;
1100
69
    default:
1101
69
      addInSec(DT_PLTGOT, InX::GotPlt);
1102
69
      break;
1103
69
    }
1104
69
    addInt(DT_PLTREL, Config->IsRela ? DT_RELA : 
DT_REL0
);
1105
69
  }
1106
345
1107
345
  addInSec(DT_SYMTAB, InX::DynSymTab);
1108
345
  addInt(DT_SYMENT, sizeof(Elf_Sym));
1109
345
  addInSec(DT_STRTAB, InX::DynStrTab);
1110
345
  addInt(DT_STRSZ, InX::DynStrTab->getSize());
1111
345
  if (!Config->ZText)
1112
3
    addInt(DT_TEXTREL, 0);
1113
345
  if (InX::GnuHashTab)
1114
294
    addInSec(DT_GNU_HASH, InX::GnuHashTab);
1115
345
  if (InX::HashTab)
1116
343
    addInSec(DT_HASH, InX::HashTab);
1117
345
1118
345
  if (Out::PreinitArray) {
1119
3
    addOutSec(DT_PREINIT_ARRAY, Out::PreinitArray);
1120
3
    addSize(DT_PREINIT_ARRAYSZ, Out::PreinitArray);
1121
3
  }
1122
345
  if (Out::InitArray) {
1123
3
    addOutSec(DT_INIT_ARRAY, Out::InitArray);
1124
3
    addSize(DT_INIT_ARRAYSZ, Out::InitArray);
1125
3
  }
1126
345
  if (Out::FiniArray) {
1127
2
    addOutSec(DT_FINI_ARRAY, Out::FiniArray);
1128
2
    addSize(DT_FINI_ARRAYSZ, Out::FiniArray);
1129
2
  }
1130
345
1131
345
  if (Symbol *B = Symtab->find(Config->Init))
1132
1
    if (B->isDefined())
1133
0
      addSym(DT_INIT, B);
1134
345
  if (Symbol *B = Symtab->find(Config->Fini))
1135
1
    if (B->isDefined())
1136
0
      addSym(DT_FINI, B);
1137
345
1138
345
  bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1139
345
  if (HasVerNeed || 
In<ELFT>::VerDef341
)
1140
26
    addInSec(DT_VERSYM, In<ELFT>::VerSym);
1141
345
  if (In<ELFT>::VerDef) {
1142
23
    addInSec(DT_VERDEF, In<ELFT>::VerDef);
1143
23
    addInt(DT_VERDEFNUM, getVerDefNum());
1144
23
  }
1145
345
  if (HasVerNeed) {
1146
4
    addInSec(DT_VERNEED, In<ELFT>::VerNeed);
1147
4
    addInt(DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum());
1148
4
  }
1149
345
1150
345
  if (Config->EMachine == EM_MIPS) {
1151
0
    addInt(DT_MIPS_RLD_VERSION, 1);
1152
0
    addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1153
0
    addInt(DT_MIPS_BASE_ADDRESS, Target->getImageBase());
1154
0
    addInt(DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols());
1155
0
1156
0
    add(DT_MIPS_LOCAL_GOTNO, [] { return InX::MipsGot->getLocalEntriesNum(); });
1157
0
1158
0
    if (const Symbol *B = InX::MipsGot->getFirstGlobalEntry())
1159
0
      addInt(DT_MIPS_GOTSYM, B->DynsymIndex);
1160
0
    else
1161
0
      addInt(DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols());
1162
0
    addInSec(DT_PLTGOT, InX::MipsGot);
1163
0
    if (InX::MipsRldMap)
1164
0
      addInSec(DT_MIPS_RLD_MAP, InX::MipsRldMap);
1165
0
  }
1166
345
1167
345
  addInt(DT_NULL, 0);
1168
345
1169
345
  getParent()->Link = this->Link;
1170
345
  this->Size = Entries.size() * this->Entsize;
1171
345
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::finalizeContents()
Line
Count
Source
1028
17
template <class ELFT> void DynamicSection<ELFT>::finalizeContents() {
1029
17
  if (this->Size)
1030
0
    return; // Already finalized.
1031
17
1032
17
  // Set DT_FLAGS and DT_FLAGS_1.
1033
17
  uint32_t DtFlags = 0;
1034
17
  uint32_t DtFlags1 = 0;
1035
17
  if (Config->Bsymbolic)
1036
0
    DtFlags |= DF_SYMBOLIC;
1037
17
  if (Config->ZNodelete)
1038
0
    DtFlags1 |= DF_1_NODELETE;
1039
17
  if (Config->ZNodlopen)
1040
0
    DtFlags1 |= DF_1_NOOPEN;
1041
17
  if (Config->ZNow) {
1042
0
    DtFlags |= DF_BIND_NOW;
1043
0
    DtFlags1 |= DF_1_NOW;
1044
0
  }
1045
17
  if (Config->ZOrigin) {
1046
0
    DtFlags |= DF_ORIGIN;
1047
0
    DtFlags1 |= DF_1_ORIGIN;
1048
0
  }
1049
17
1050
17
  if (DtFlags)
1051
0
    addInt(DT_FLAGS, DtFlags);
1052
17
  if (DtFlags1)
1053
0
    addInt(DT_FLAGS_1, DtFlags1);
1054
17
1055
17
  // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We
1056
17
  // need it for each process, so we don't write it for DSOs. The loader writes
1057
17
  // the pointer into this entry.
1058
17
  //
1059
17
  // DT_DEBUG is the only .dynamic entry that needs to be written to. Some
1060
17
  // systems (currently only Fuchsia OS) provide other means to give the
1061
17
  // debugger this information. Such systems may choose make .dynamic read-only.
1062
17
  // If the target is such a system (used -z rodynamic) don't write DT_DEBUG.
1063
17
  if (!Config->Shared && 
!Config->Relocatable4
&&
!Config->ZRodynamic4
)
1064
4
    addInt(DT_DEBUG, 0);
1065
17
1066
17
  this->Link = InX::DynStrTab->getParent()->SectionIndex;
1067
17
  if (!InX::RelaDyn->empty()) {
1068
6
    addInSec(InX::RelaDyn->DynamicTag, InX::RelaDyn);
1069
6
    addSize(InX::RelaDyn->SizeDynamicTag, InX::RelaDyn->getParent());
1070
6
1071
6
    bool IsRela = Config->IsRela;
1072
6
    addInt(IsRela ? DT_RELAENT : 
DT_RELENT0
,
1073
6
           IsRela ? sizeof(Elf_Rela) : 
sizeof(Elf_Rel)0
);
1074
6
1075
6
    // MIPS dynamic loader does not support RELCOUNT tag.
1076
6
    // The problem is in the tight relation between dynamic
1077
6
    // relocations and GOT. So do not emit this tag on MIPS.
1078
6
    if (Config->EMachine != EM_MIPS) {
1079
4
      size_t NumRelativeRels = InX::RelaDyn->getRelativeRelocCount();
1080
4
      if (Config->ZCombreloc && NumRelativeRels)
1081
1
        addInt(IsRela ? DT_RELACOUNT : 
DT_RELCOUNT0
, NumRelativeRels);
1082
4
    }
1083
6
  }
1084
17
  // .rel[a].plt section usually consists of two parts, containing plt and
1085
17
  // iplt relocations. It is possible to have only iplt relocations in the
1086
17
  // output. In that case RelaPlt is empty and have zero offset, the same offset
1087
17
  // as RelaIplt have. And we still want to emit proper dynamic tags for that
1088
17
  // case, so here we always use RelaPlt as marker for the begining of
1089
17
  // .rel[a].plt section.
1090
17
  if (InX::RelaPlt->getParent()->Live) {
1091
2
    addInSec(DT_JMPREL, InX::RelaPlt);
1092
2
    addSize(DT_PLTRELSZ, InX::RelaPlt->getParent());
1093
2
    switch (Config->EMachine) {
1094
2
    case EM_MIPS:
1095
1
      addInSec(DT_MIPS_PLTGOT, InX::GotPlt);
1096
1
      break;
1097
2
    case EM_SPARCV9:
1098
0
      addInSec(DT_PLTGOT, InX::Plt);
1099
0
      break;
1100
2
    default:
1101
1
      addInSec(DT_PLTGOT, InX::GotPlt);
1102
1
      break;
1103
2
    }
1104
2
    addInt(DT_PLTREL, Config->IsRela ? DT_RELA : 
DT_REL0
);
1105
2
  }
1106
17
1107
17
  addInSec(DT_SYMTAB, InX::DynSymTab);
1108
17
  addInt(DT_SYMENT, sizeof(Elf_Sym));
1109
17
  addInSec(DT_STRTAB, InX::DynStrTab);
1110
17
  addInt(DT_STRSZ, InX::DynStrTab->getSize());
1111
17
  if (!Config->ZText)
1112
2
    addInt(DT_TEXTREL, 0);
1113
17
  if (InX::GnuHashTab)
1114
6
    addInSec(DT_GNU_HASH, InX::GnuHashTab);
1115
17
  if (InX::HashTab)
1116
17
    addInSec(DT_HASH, InX::HashTab);
1117
17
1118
17
  if (Out::PreinitArray) {
1119
0
    addOutSec(DT_PREINIT_ARRAY, Out::PreinitArray);
1120
0
    addSize(DT_PREINIT_ARRAYSZ, Out::PreinitArray);
1121
0
  }
1122
17
  if (Out::InitArray) {
1123
0
    addOutSec(DT_INIT_ARRAY, Out::InitArray);
1124
0
    addSize(DT_INIT_ARRAYSZ, Out::InitArray);
1125
0
  }
1126
17
  if (Out::FiniArray) {
1127
0
    addOutSec(DT_FINI_ARRAY, Out::FiniArray);
1128
0
    addSize(DT_FINI_ARRAYSZ, Out::FiniArray);
1129
0
  }
1130
17
1131
17
  if (Symbol *B = Symtab->find(Config->Init))
1132
0
    if (B->isDefined())
1133
0
      addSym(DT_INIT, B);
1134
17
  if (Symbol *B = Symtab->find(Config->Fini))
1135
0
    if (B->isDefined())
1136
0
      addSym(DT_FINI, B);
1137
17
1138
17
  bool HasVerNeed = In<ELFT>::VerNeed->getNeedNum() != 0;
1139
17
  if (HasVerNeed || In<ELFT>::VerDef)
1140
0
    addInSec(DT_VERSYM, In<ELFT>::VerSym);
1141
17
  if (In<ELFT>::VerDef) {
1142
0
    addInSec(DT_VERDEF, In<ELFT>::VerDef);
1143
0
    addInt(DT_VERDEFNUM, getVerDefNum());
1144
0
  }
1145
17
  if (HasVerNeed) {
1146
0
    addInSec(DT_VERNEED, In<ELFT>::VerNeed);
1147
0
    addInt(DT_VERNEEDNUM, In<ELFT>::VerNeed->getNeedNum());
1148
0
  }
1149
17
1150
17
  if (Config->EMachine == EM_MIPS) {
1151
11
    addInt(DT_MIPS_RLD_VERSION, 1);
1152
11
    addInt(DT_MIPS_FLAGS, RHF_NOTPOT);
1153
11
    addInt(DT_MIPS_BASE_ADDRESS, Target->getImageBase());
1154
11
    addInt(DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols());
1155
11
1156
11
    add(DT_MIPS_LOCAL_GOTNO, [] { return InX::MipsGot->getLocalEntriesNum(); });
1157
11
1158
11
    if (const Symbol *B = InX::MipsGot->getFirstGlobalEntry())
1159
2
      addInt(DT_MIPS_GOTSYM, B->DynsymIndex);
1160
9
    else
1161
9
      addInt(DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols());
1162
11
    addInSec(DT_PLTGOT, InX::MipsGot);
1163
11
    if (InX::MipsRldMap)
1164
3
      addInSec(DT_MIPS_RLD_MAP, InX::MipsRldMap);
1165
11
  }
1166
17
1167
17
  addInt(DT_NULL, 0);
1168
17
1169
17
  getParent()->Link = this->Link;
1170
17
  this->Size = Entries.size() * this->Entsize;
1171
17
}
1172
1173
453
template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1174
453
  auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1175
453
1176
4.34k
  for (std::pair<int32_t, std::function<uint64_t()>> &KV : Entries) {
1177
4.34k
    P->d_tag = KV.first;
1178
4.34k
    P->d_un.d_val = KV.second();
1179
4.34k
    ++P;
1180
4.34k
  }
1181
453
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::writeTo(unsigned char*)
Line
Count
Source
1173
67
template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1174
67
  auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1175
67
1176
670
  for (std::pair<int32_t, std::function<uint64_t()>> &KV : Entries) {
1177
670
    P->d_tag = KV.first;
1178
670
    P->d_un.d_val = KV.second();
1179
670
    ++P;
1180
670
  }
1181
67
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::writeTo(unsigned char*)
Line
Count
Source
1173
28
template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1174
28
  auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1175
28
1176
393
  for (std::pair<int32_t, std::function<uint64_t()>> &KV : Entries) {
1177
393
    P->d_tag = KV.first;
1178
393
    P->d_un.d_val = KV.second();
1179
393
    ++P;
1180
393
  }
1181
28
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::writeTo(unsigned char*)
Line
Count
Source
1173
341
template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1174
341
  auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1175
341
1176
3.05k
  for (std::pair<int32_t, std::function<uint64_t()>> &KV : Entries) {
1177
3.05k
    P->d_tag = KV.first;
1178
3.05k
    P->d_un.d_val = KV.second();
1179
3.05k
    ++P;
1180
3.05k
  }
1181
341
}
lld::elf::DynamicSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::writeTo(unsigned char*)
Line
Count
Source
1173
17
template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
1174
17
  auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
1175
17
1176
226
  for (std::pair<int32_t, std::function<uint64_t()>> &KV : Entries) {
1177
226
    P->d_tag = KV.first;
1178
226
    P->d_un.d_val = KV.second();
1179
226
    ++P;
1180
226
  }
1181
17
}
1182
1183
483
uint64_t DynamicReloc::getOffset() const {
1184
483
  return InputSec->getOutputSection()->Addr + InputSec->getOffset(OffsetInSec);
1185
483
}
1186
1187
290
int64_t DynamicReloc::getAddend() const {
1188
290
  if (UseSymVA)
1189
98
    return Sym->getVA(Addend);
1190
192
  return Addend;
1191
192
}
1192
1193
483
uint32_t DynamicReloc::getSymIndex() const {
1194
483
  if (Sym && 
!UseSymVA480
)
1195
284
    return Sym->DynsymIndex;
1196
199
  return 0;
1197
199
}
1198
1199
RelocationBaseSection::RelocationBaseSection(StringRef Name, uint32_t Type,
1200
                                             int32_t DynamicTag,
1201
                                             int32_t SizeDynamicTag)
1202
    : SyntheticSection(SHF_ALLOC, Type, Config->Wordsize, Name),
1203
2.80k
      DynamicTag(DynamicTag), SizeDynamicTag(SizeDynamicTag) {}
1204
1205
void RelocationBaseSection::addReloc(uint32_t DynType,
1206
                                     InputSectionBase *InputSec,
1207
                                     uint64_t OffsetInSec, bool UseSymVA,
1208
                                     Symbol *Sym, int64_t Addend, RelExpr Expr,
1209
183
                                     RelType Type) {
1210
183
  // REL type relocations don't have addend fields unlike RELAs, and
1211
183
  // their addends are stored to the section to which they are applied.
1212
183
  // So, store addends if we need to.
1213
183
  if (!Config->IsRela && 
UseSymVA86
)
1214
65
    InputSec->Relocations.push_back({Expr, Type, OffsetInSec, Addend, Sym});
1215
183
  addReloc({DynType, InputSec, OffsetInSec, UseSymVA, Sym, Addend});
1216
183
}
1217
1218
434
void RelocationBaseSection::addReloc(const DynamicReloc &Reloc) {
1219
434
  if (Reloc.Type == Target->RelativeRel)
1220
128
    ++NumRelativeRelocs;
1221
434
  Relocs.push_back(Reloc);
1222
434
}
1223
1224
190
void RelocationBaseSection::finalizeContents() {
1225
190
  // If all relocations are R_*_RELATIVE they don't refer to any
1226
190
  // dynamic symbol and we don't need a dynamic symbol table. If that
1227
190
  // is the case, just use 0 as the link.
1228
190
  Link = InX::DynSymTab ? 
InX::DynSymTab->getParent()->SectionIndex183
:
07
;
1229
190
1230
190
  // Set required output section properties.
1231
190
  getParent()->Link = Link;
1232
190
}
1233
1234
template <class ELFT>
1235
static void encodeDynamicReloc(typename ELFT::Rela *P,
1236
483
                               const DynamicReloc &Rel) {
1237
483
  if (Config->IsRela)
1238
290
    P->r_addend = Rel.getAddend();
1239
483
  P->r_offset = Rel.getOffset();
1240
483
  if (Config->EMachine == EM_MIPS && 
Rel.getInputSec() == InX::MipsGot11
)
1241
0
    // The MIPS GOT section contains dynamic relocations that correspond to TLS
1242
0
    // entries. These entries are placed after the global and local sections of
1243
0
    // the GOT. At the point when we create these relocations, the size of the
1244
0
    // global and local sections is unknown, so the offset that we store in the
1245
0
    // TLS entry's DynamicReloc is relative to the start of the TLS section of
1246
0
    // the GOT, rather than being relative to the start of the GOT. This line of
1247
0
    // code adds the size of the global and local sections to the virtual
1248
0
    // address computed by getOffset() in order to adjust it into the TLS
1249
0
    // section.
1250
0
    P->r_offset += InX::MipsGot->getTlsOffset();
1251
483
  P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
1252
483
}
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
1236
187
                               const DynamicReloc &Rel) {
1237
187
  if (Config->IsRela)
1238
0
    P->r_addend = Rel.getAddend();
1239
187
  P->r_offset = Rel.getOffset();
1240
187
  if (Config->EMachine == EM_MIPS && 
Rel.getInputSec() == InX::MipsGot3
)
1241
0
    // The MIPS GOT section contains dynamic relocations that correspond to TLS
1242
0
    // entries. These entries are placed after the global and local sections of
1243
0
    // the GOT. At the point when we create these relocations, the size of the
1244
0
    // global and local sections is unknown, so the offset that we store in the
1245
0
    // TLS entry's DynamicReloc is relative to the start of the TLS section of
1246
0
    // the GOT, rather than being relative to the start of the GOT. This line of
1247
0
    // code adds the size of the global and local sections to the virtual
1248
0
    // address computed by getOffset() in order to adjust it into the TLS
1249
0
    // section.
1250
0
    P->r_offset += InX::MipsGot->getTlsOffset();
1251
187
  P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
1252
187
}
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
1236
5
                               const DynamicReloc &Rel) {
1237
5
  if (Config->IsRela)
1238
0
    P->r_addend = Rel.getAddend();
1239
5
  P->r_offset = Rel.getOffset();
1240
5
  if (Config->EMachine == EM_MIPS && Rel.getInputSec() == InX::MipsGot)
1241
0
    // The MIPS GOT section contains dynamic relocations that correspond to TLS
1242
0
    // entries. These entries are placed after the global and local sections of
1243
0
    // the GOT. At the point when we create these relocations, the size of the
1244
0
    // global and local sections is unknown, so the offset that we store in the
1245
0
    // TLS entry's DynamicReloc is relative to the start of the TLS section of
1246
0
    // the GOT, rather than being relative to the start of the GOT. This line of
1247
0
    // code adds the size of the global and local sections to the virtual
1248
0
    // address computed by getOffset() in order to adjust it into the TLS
1249
0
    // section.
1250
0
    P->r_offset += InX::MipsGot->getTlsOffset();
1251
5
  P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
1252
5
}
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
1236
280
                               const DynamicReloc &Rel) {
1237
280
  if (Config->IsRela)
1238
279
    P->r_addend = Rel.getAddend();
1239
280
  P->r_offset = Rel.getOffset();
1240
280
  if (Config->EMachine == EM_MIPS && 
Rel.getInputSec() == InX::MipsGot0
)
1241
0
    // The MIPS GOT section contains dynamic relocations that correspond to TLS
1242
0
    // entries. These entries are placed after the global and local sections of
1243
0
    // the GOT. At the point when we create these relocations, the size of the
1244
0
    // global and local sections is unknown, so the offset that we store in the
1245
0
    // TLS entry's DynamicReloc is relative to the start of the TLS section of
1246
0
    // the GOT, rather than being relative to the start of the GOT. This line of
1247
0
    // code adds the size of the global and local sections to the virtual
1248
0
    // address computed by getOffset() in order to adjust it into the TLS
1249
0
    // section.
1250
0
    P->r_offset += InX::MipsGot->getTlsOffset();
1251
280
  P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
1252
280
}
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
1236
11
                               const DynamicReloc &Rel) {
1237
11
  if (Config->IsRela)
1238
11
    P->r_addend = Rel.getAddend();
1239
11
  P->r_offset = Rel.getOffset();
1240
11
  if (Config->EMachine == EM_MIPS && 
Rel.getInputSec() == InX::MipsGot3
)
1241
0
    // The MIPS GOT section contains dynamic relocations that correspond to TLS
1242
0
    // entries. These entries are placed after the global and local sections of
1243
0
    // the GOT. At the point when we create these relocations, the size of the
1244
0
    // global and local sections is unknown, so the offset that we store in the
1245
0
    // TLS entry's DynamicReloc is relative to the start of the TLS section of
1246
0
    // the GOT, rather than being relative to the start of the GOT. This line of
1247
0
    // code adds the size of the global and local sections to the virtual
1248
0
    // address computed by getOffset() in order to adjust it into the TLS
1249
0
    // section.
1250
0
    P->r_offset += InX::MipsGot->getTlsOffset();
1251
11
  P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL);
1252
11
}
1253
1254
template <class ELFT>
1255
RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
1256
    : RelocationBaseSection(Name, Config->IsRela ? SHT_RELA : SHT_REL,
1257
                            Config->IsRela ? DT_RELA : DT_REL,
1258
                            Config->IsRela ? DT_RELASZ : DT_RELSZ),
1259
2.80k
      Sort(Sort) {
1260
2.80k
  this->Entsize = Config->IsRela ? 
sizeof(Elf_Rela)2.30k
:
sizeof(Elf_Rel)506
;
1261
2.80k
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::RelocationSection(llvm::StringRef, bool)
Line
Count
Source
1259
353
      Sort(Sort) {
1260
353
  this->Entsize = Config->IsRela ? 
sizeof(Elf_Rela)3
:
sizeof(Elf_Rel)350
;
1261
353
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::RelocationSection(llvm::StringRef, bool)
Line
Count
Source
1259
156
      Sort(Sort) {
1260
156
  this->Entsize = Config->IsRela ? 
sizeof(Elf_Rela)0
: sizeof(Elf_Rel);
1261
156
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::RelocationSection(llvm::StringRef, bool)
Line
Count
Source
1259
2.21k
      Sort(Sort) {
1260
2.21k
  this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : 
sizeof(Elf_Rel)0
;
1261
2.21k
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::RelocationSection(llvm::StringRef, bool)
Line
Count
Source
1259
84
      Sort(Sort) {
1260
84
  this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : 
sizeof(Elf_Rel)0
;
1261
84
}
1262
1263
template <class ELFT, class RelTy>
1264
256
static bool compRelocations(const RelTy &A, const RelTy &B) {
1265
256
  bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel;
1266
256
  bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel;
1267
256
  if (AIsRel != BIsRel)
1268
84
    return AIsRel;
1269
172
1270
172
  return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL);
1271
172
}
Unexecuted instantiation: SyntheticSections.cpp:bool compRelocations<llvm::object::ELFType<(llvm::support::endianness)1, false>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, true> >(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&)
SyntheticSections.cpp:bool compRelocations<llvm::object::ELFType<(llvm::support::endianness)1, false>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false>, false> >(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&)
Line
Count
Source
1264
120
static bool compRelocations(const RelTy &A, const RelTy &B) {
1265
120
  bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel;
1266
120
  bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel;
1267
120
  if (AIsRel != BIsRel)
1268
40
    return AIsRel;
1269
80
1270
80
  return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL);
1271
80
}
Unexecuted instantiation: SyntheticSections.cpp:bool compRelocations<llvm::object::ELFType<(llvm::support::endianness)0, false>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, true> >(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&)
SyntheticSections.cpp:bool compRelocations<llvm::object::ELFType<(llvm::support::endianness)0, false>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false>, false> >(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&)
Line
Count
Source
1264
1
static bool compRelocations(const RelTy &A, const RelTy &B) {
1265
1
  bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel;
1266
1
  bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel;
1267
1
  if (AIsRel != BIsRel)
1268
0
    return AIsRel;
1269
1
1270
1
  return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL);
1271
1
}
SyntheticSections.cpp:bool compRelocations<llvm::object::ELFType<(llvm::support::endianness)1, true>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, true> >(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&)
Line
Count
Source
1264
132
static bool compRelocations(const RelTy &A, const RelTy &B) {
1265
132
  bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel;
1266
132
  bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel;
1267
132
  if (AIsRel != BIsRel)
1268
44
    return AIsRel;
1269
88
1270
88
  return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL);
1271
88
}
Unexecuted instantiation: SyntheticSections.cpp:bool compRelocations<llvm::object::ELFType<(llvm::support::endianness)1, true>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true>, false> >(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&)
SyntheticSections.cpp:bool compRelocations<llvm::object::ELFType<(llvm::support::endianness)0, true>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, true> >(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&)
Line
Count
Source
1264
3
static bool compRelocations(const RelTy &A, const RelTy &B) {
1265
3
  bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel;
1266
3
  bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel;
1267
3
  if (AIsRel != BIsRel)
1268
0
    return AIsRel;
1269
3
1270
3
  return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL);
1271
3
}
Unexecuted instantiation: SyntheticSections.cpp:bool compRelocations<llvm::object::ELFType<(llvm::support::endianness)0, true>, llvm::object::Elf_Rel_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true>, false> >(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&)
1272
1273
187
template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1274
187
  uint8_t *BufBegin = Buf;
1275
379
  for (const DynamicReloc &Rel : Relocs) {
1276
379
    encodeDynamicReloc<ELFT>(reinterpret_cast<Elf_Rela *>(Buf), Rel);
1277
379
    Buf += Config->IsRela ? 
sizeof(Elf_Rela)239
:
sizeof(Elf_Rel)140
;
1278
379
  }
1279
187
1280
187
  if (Sort) {
1281
88
    if (Config->IsRela)
1282
57
      std::stable_sort((Elf_Rela *)BufBegin,
1283
57
                       (Elf_Rela *)BufBegin + Relocs.size(),
1284
57
                       compRelocations<ELFT, Elf_Rela>);
1285
31
    else
1286
31
      std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1287
31
                       compRelocations<ELFT, Elf_Rel>);
1288
88
  }
1289
187
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::writeTo(unsigned char*)
Line
Count
Source
1273
49
template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1274
49
  uint8_t *BufBegin = Buf;
1275
135
  for (const DynamicReloc &Rel : Relocs) {
1276
135
    encodeDynamicReloc<ELFT>(reinterpret_cast<Elf_Rela *>(Buf), Rel);
1277
135
    Buf += Config->IsRela ? 
sizeof(Elf_Rela)0
: sizeof(Elf_Rel);
1278
135
  }
1279
49
1280
49
  if (Sort) {
1281
30
    if (Config->IsRela)
1282
0
      std::stable_sort((Elf_Rela *)BufBegin,
1283
0
                       (Elf_Rela *)BufBegin + Relocs.size(),
1284
0
                       compRelocations<ELFT, Elf_Rela>);
1285
30
    else
1286
30
      std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1287
30
                       compRelocations<ELFT, Elf_Rel>);
1288
30
  }
1289
49
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::writeTo(unsigned char*)
Line
Count
Source
1273
4
template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1274
4
  uint8_t *BufBegin = Buf;
1275
5
  for (const DynamicReloc &Rel : Relocs) {
1276
5
    encodeDynamicReloc<ELFT>(reinterpret_cast<Elf_Rela *>(Buf), Rel);
1277
5
    Buf += Config->IsRela ? 
sizeof(Elf_Rela)0
: sizeof(Elf_Rel);
1278
5
  }
1279
4
1280
4
  if (Sort) {
1281
1
    if (Config->IsRela)
1282
0
      std::stable_sort((Elf_Rela *)BufBegin,
1283
0
                       (Elf_Rela *)BufBegin + Relocs.size(),
1284
0
                       compRelocations<ELFT, Elf_Rela>);
1285
1
    else
1286
1
      std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1287
1
                       compRelocations<ELFT, Elf_Rel>);
1288
1
  }
1289
4
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::writeTo(unsigned char*)
Line
Count
Source
1273
126
template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1274
126
  uint8_t *BufBegin = Buf;
1275
228
  for (const DynamicReloc &Rel : Relocs) {
1276
228
    encodeDynamicReloc<ELFT>(reinterpret_cast<Elf_Rela *>(Buf), Rel);
1277
228
    Buf += Config->IsRela ? sizeof(Elf_Rela) : 
sizeof(Elf_Rel)0
;
1278
228
  }
1279
126
1280
126
  if (Sort) {
1281
51
    if (Config->IsRela)
1282
51
      std::stable_sort((Elf_Rela *)BufBegin,
1283
51
                       (Elf_Rela *)BufBegin + Relocs.size(),
1284
51
                       compRelocations<ELFT, Elf_Rela>);
1285
0
    else
1286
0
      std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1287
0
                       compRelocations<ELFT, Elf_Rel>);
1288
51
  }
1289
126
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::writeTo(unsigned char*)
Line
Count
Source
1273
8
template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
1274
8
  uint8_t *BufBegin = Buf;
1275
11
  for (const DynamicReloc &Rel : Relocs) {
1276
11
    encodeDynamicReloc<ELFT>(reinterpret_cast<Elf_Rela *>(Buf), Rel);
1277
11
    Buf += Config->IsRela ? sizeof(Elf_Rela) : 
sizeof(Elf_Rel)0
;
1278
11
  }
1279
8
1280
8
  if (Sort) {
1281
6
    if (Config->IsRela)
1282
6
      std::stable_sort((Elf_Rela *)BufBegin,
1283
6
                       (Elf_Rela *)BufBegin + Relocs.size(),
1284
6
                       compRelocations<ELFT, Elf_Rela>);
1285
0
    else
1286
0
      std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
1287
0
                       compRelocations<ELFT, Elf_Rel>);
1288
6
  }
1289
8
}
1290
1291
146
template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1292
146
  return this->Entsize * Relocs.size();
1293
146
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::getRelocOffset()
Line
Count
Source
1291
35
template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1292
35
  return this->Entsize * Relocs.size();
1293
35
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::getRelocOffset()
Line
Count
Source
1291
3
template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1292
3
  return this->Entsize * Relocs.size();
1293
3
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::getRelocOffset()
Line
Count
Source
1291
106
template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1292
106
  return this->Entsize * Relocs.size();
1293
106
}
lld::elf::RelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::getRelocOffset()
Line
Count
Source
1291
2
template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
1292
2
  return this->Entsize * Relocs.size();
1293
2
}
1294
1295
template <class ELFT>
1296
AndroidPackedRelocationSection<ELFT>::AndroidPackedRelocationSection(
1297
    StringRef Name)
1298
    : RelocationBaseSection(
1299
          Name, Config->IsRela ? SHT_ANDROID_RELA : SHT_ANDROID_REL,
1300
          Config->IsRela ? DT_ANDROID_RELA : DT_ANDROID_REL,
1301
2
          Config->IsRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ) {
1302
2
  this->Entsize = 1;
1303
2
}
lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::AndroidPackedRelocationSection(llvm::StringRef)
Line
Count
Source
1301
1
          Config->IsRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ) {
1302
1
  this->Entsize = 1;
1303
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
1301
1
          Config->IsRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ) {
1302
1
  this->Entsize = 1;
1303
1
}
Unexecuted instantiation: lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::AndroidPackedRelocationSection(llvm::StringRef)
1304
1305
template <class ELFT>
1306
4
bool AndroidPackedRelocationSection<ELFT>::updateAllocSize() {
1307
4
  // This function computes the contents of an Android-format packed relocation
1308
4
  // section.
1309
4
  //
1310
4
  // This format compresses relocations by using relocation groups to factor out
1311
4
  // fields that are common between relocations and storing deltas from previous
1312
4
  // relocations in SLEB128 format (which has a short representation for small
1313
4
  // numbers). A good example of a relocation type with common fields is
1314
4
  // R_*_RELATIVE, which is normally used to represent function pointers in
1315
4
  // vtables. In the REL format, each relative relocation has the same r_info
1316
4
  // field, and is only different from other relative relocations in terms of
1317
4
  // the r_offset field. By sorting relocations by offset, grouping them by
1318
4
  // r_info and representing each relocation with only the delta from the
1319
4
  // previous offset, each 8-byte relocation can be compressed to as little as 1
1320
4
  // byte (or less with run-length encoding). This relocation packer was able to
1321
4
  // reduce the size of the relocation section in an Android Chromium DSO from
1322
4
  // 2,911,184 bytes to 174,693 bytes, or 6% of the original size.
1323
4
  //
1324
4
  // A relocation section consists of a header containing the literal bytes
1325
4
  // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two
1326
4
  // elements are the total number of relocations in the section and an initial
1327
4
  // r_offset value. The remaining elements define a sequence of relocation
1328
4
  // groups. Each relocation group starts with a header consisting of the
1329
4
  // following elements:
1330
4
  //
1331
4
  // - the number of relocations in the relocation group
1332
4
  // - flags for the relocation group
1333
4
  // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta
1334
4
  //   for each relocation in the group.
1335
4
  // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info
1336
4
  //   field for each relocation in the group.
1337
4
  // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and
1338
4
  //   RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for
1339
4
  //   each relocation in the group.
1340
4
  //
1341
4
  // Following the relocation group header are descriptions of each of the
1342
4
  // relocations in the group. They consist of the following elements:
1343
4
  //
1344
4
  // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset
1345
4
  //   delta for this relocation.
1346
4
  // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info
1347
4
  //   field for this relocation.
1348
4
  // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and
1349
4
  //   RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for
1350
4
  //   this relocation.
1351
4
1352
4
  size_t OldSize = RelocData.size();
1353
4
1354
4
  RelocData = {'A', 'P', 'S', '2'};
1355
4
  raw_svector_ostream OS(RelocData);
1356
188
  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
1356
68
  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
1356
120
  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
1357
4
1358
4
  // The format header includes the number of relocations and the initial
1359
4
  // offset (we set this to zero because the first relocation group will
1360
4
  // perform the initial adjustment).
1361
4
  Add(Relocs.size());
1362
4
  Add(0);
1363
4
1364
4
  std::vector<Elf_Rela> Relatives, NonRelatives;
1365
4
1366
104
  for (const DynamicReloc &Rel : Relocs) {
1367
104
    Elf_Rela R;
1368
104
    encodeDynamicReloc<ELFT>(&R, Rel);
1369
104
1370
104
    if (R.getType(Config->IsMips64EL) == Target->RelativeRel)
1371
96
      Relatives.push_back(R);
1372
8
    else
1373
8
      NonRelatives.push_back(R);
1374
104
  }
1375
4
1376
4
  std::sort(Relatives.begin(), Relatives.end(),
1377
92
            [](const Elf_Rel &A, const Elf_Rel &B) {
1378
92
              return A.r_offset < B.r_offset;
1379
92
            });
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
1377
46
            [](const Elf_Rel &A, const Elf_Rel &B) {
1378
46
              return A.r_offset < B.r_offset;
1379
46
            });
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
1377
46
            [](const Elf_Rel &A, const Elf_Rel &B) {
1378
46
              return A.r_offset < B.r_offset;
1379
46
            });
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
1380
4
1381
4
  // Try to find groups of relative relocations which are spaced one word
1382
4
  // apart from one another. These generally correspond to vtable entries. The
1383
4
  // format allows these groups to be encoded using a sort of run-length
1384
4
  // encoding, but each group will cost 7 bytes in addition to the offset from
1385
4
  // the previous group, so it is only profitable to do this for groups of
1386
4
  // size 8 or larger.
1387
4
  std::vector<Elf_Rela> UngroupedRelatives;
1388
4
  std::vector<std::vector<Elf_Rela>> RelativeGroups;
1389
16
  for (auto I = Relatives.begin(), E = Relatives.end(); I != E;) {
1390
12
    std::vector<Elf_Rela> Group;
1391
96
    do {
1392
96
      Group.push_back(*I++);
1393
96
    } while (I != E && 
(I - 1)->r_offset + Config->Wordsize == I->r_offset92
);
1394
12
1395
12
    if (Group.size() < 8)
1396
4
      UngroupedRelatives.insert(UngroupedRelatives.end(), Group.begin(),
1397
4
                                Group.end());
1398
8
    else
1399
8
      RelativeGroups.emplace_back(std::move(Group));
1400
12
  }
1401
4
1402
4
  unsigned HasAddendIfRela =
1403
4
      Config->IsRela ? 
RELOCATION_GROUP_HAS_ADDEND_FLAG2
:
02
;
1404
4
1405
4
  uint64_t Offset = 0;
1406
4
  uint64_t Addend = 0;
1407
4
1408
4
  // Emit the run-length encoding for the groups of adjacent relative
1409
4
  // relocations. Each group is represented using two groups in the packed
1410
4
  // format. The first is used to set the current offset to the start of the
1411
4
  // group (and also encodes the first relocation), and the second encodes the
1412
4
  // remaining relocations.
1413
8
  for (std::vector<Elf_Rela> &G : RelativeGroups) {
1414
8
    // The first relocation in the group.
1415
8
    Add(1);
1416
8
    Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1417
8
        RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1418
8
    Add(G[0].r_offset - Offset);
1419
8
    Add(Target->RelativeRel);
1420
8
    if (Config->IsRela) {
1421
4
      Add(G[0].r_addend - Addend);
1422
4
      Addend = G[0].r_addend;
1423
4
    }
1424
8
1425
8
    // The remaining relocations.
1426
8
    Add(G.size() - 1);
1427
8
    Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1428
8
        RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1429
8
    Add(Config->Wordsize);
1430
8
    Add(Target->RelativeRel);
1431
8
    if (Config->IsRela) {
1432
34
      for (auto I = G.begin() + 1, E = G.end(); I != E; 
++I30
) {
1433
30
        Add(I->r_addend - Addend);
1434
30
        Addend = I->r_addend;
1435
30
      }
1436
4
    }
1437
8
1438
8
    Offset = G.back().r_offset;
1439
8
  }
1440
4
1441
4
  // Now the ungrouped relatives.
1442
4
  if (!UngroupedRelatives.empty()) {
1443
4
    Add(UngroupedRelatives.size());
1444
4
    Add(RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1445
4
    Add(Target->RelativeRel);
1446
28
    for (Elf_Rela &R : UngroupedRelatives) {
1447
28
      Add(R.r_offset - Offset);
1448
28
      Offset = R.r_offset;
1449
28
      if (Config->IsRela) {
1450
14
        Add(R.r_addend - Addend);
1451
14
        Addend = R.r_addend;
1452
14
      }
1453
28
    }
1454
4
  }
1455
4
1456
4
  // Finally the non-relative relocations.
1457
4
  std::sort(NonRelatives.begin(), NonRelatives.end(),
1458
4
            [](const Elf_Rela &A, const Elf_Rela &B) {
1459
4
              return A.r_offset < B.r_offset;
1460
4
            });
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
1458
2
            [](const Elf_Rela &A, const Elf_Rela &B) {
1459
2
              return A.r_offset < B.r_offset;
1460
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
1458
2
            [](const Elf_Rela &A, const Elf_Rela &B) {
1459
2
              return A.r_offset < B.r_offset;
1460
2
            });
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
1461
4
  if (!NonRelatives.empty()) {
1462
4
    Add(NonRelatives.size());
1463
4
    Add(HasAddendIfRela);
1464
8
    for (Elf_Rela &R : NonRelatives) {
1465
8
      Add(R.r_offset - Offset);
1466
8
      Offset = R.r_offset;
1467
8
      Add(R.r_info);
1468
8
      if (Config->IsRela) {
1469
4
        Add(R.r_addend - Addend);
1470
4
        Addend = R.r_addend;
1471
4
      }
1472
8
    }
1473
4
  }
1474
4
1475
4
  // Returns whether the section size changed. We need to keep recomputing both
1476
4
  // section layout and the contents of this section until the size converges
1477
4
  // because changing this section's size can affect section layout, which in
1478
4
  // turn can affect the sizes of the LEB-encoded integers stored in this
1479
4
  // section.
1480
4
  return RelocData.size() != OldSize;
1481
4
}
lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::updateAllocSize()
Line
Count
Source
1306
2
bool AndroidPackedRelocationSection<ELFT>::updateAllocSize() {
1307
2
  // This function computes the contents of an Android-format packed relocation
1308
2
  // section.
1309
2
  //
1310
2
  // This format compresses relocations by using relocation groups to factor out
1311
2
  // fields that are common between relocations and storing deltas from previous
1312
2
  // relocations in SLEB128 format (which has a short representation for small
1313
2
  // numbers). A good example of a relocation type with common fields is
1314
2
  // R_*_RELATIVE, which is normally used to represent function pointers in
1315
2
  // vtables. In the REL format, each relative relocation has the same r_info
1316
2
  // field, and is only different from other relative relocations in terms of
1317
2
  // the r_offset field. By sorting relocations by offset, grouping them by
1318
2
  // r_info and representing each relocation with only the delta from the
1319
2
  // previous offset, each 8-byte relocation can be compressed to as little as 1
1320
2
  // byte (or less with run-length encoding). This relocation packer was able to
1321
2
  // reduce the size of the relocation section in an Android Chromium DSO from
1322
2
  // 2,911,184 bytes to 174,693 bytes, or 6% of the original size.
1323
2
  //
1324
2
  // A relocation section consists of a header containing the literal bytes
1325
2
  // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two
1326
2
  // elements are the total number of relocations in the section and an initial
1327
2
  // r_offset value. The remaining elements define a sequence of relocation
1328
2
  // groups. Each relocation group starts with a header consisting of the
1329
2
  // following elements:
1330
2
  //
1331
2
  // - the number of relocations in the relocation group
1332
2
  // - flags for the relocation group
1333
2
  // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta
1334
2
  //   for each relocation in the group.
1335
2
  // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info
1336
2
  //   field for each relocation in the group.
1337
2
  // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and
1338
2
  //   RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for
1339
2
  //   each relocation in the group.
1340
2
  //
1341
2
  // Following the relocation group header are descriptions of each of the
1342
2
  // relocations in the group. They consist of the following elements:
1343
2
  //
1344
2
  // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset
1345
2
  //   delta for this relocation.
1346
2
  // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info
1347
2
  //   field for this relocation.
1348
2
  // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and
1349
2
  //   RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for
1350
2
  //   this relocation.
1351
2
1352
2
  size_t OldSize = RelocData.size();
1353
2
1354
2
  RelocData = {'A', 'P', 'S', '2'};
1355
2
  raw_svector_ostream OS(RelocData);
1356
2
  auto Add = [&](int64_t V) { encodeSLEB128(V, OS); };
1357
2
1358
2
  // The format header includes the number of relocations and the initial
1359
2
  // offset (we set this to zero because the first relocation group will
1360
2
  // perform the initial adjustment).
1361
2
  Add(Relocs.size());
1362
2
  Add(0);
1363
2
1364
2
  std::vector<Elf_Rela> Relatives, NonRelatives;
1365
2
1366
52
  for (const DynamicReloc &Rel : Relocs) {
1367
52
    Elf_Rela R;
1368
52
    encodeDynamicReloc<ELFT>(&R, Rel);
1369
52
1370
52
    if (R.getType(Config->IsMips64EL) == Target->RelativeRel)
1371
48
      Relatives.push_back(R);
1372
4
    else
1373
4
      NonRelatives.push_back(R);
1374
52
  }
1375
2
1376
2
  std::sort(Relatives.begin(), Relatives.end(),
1377
2
            [](const Elf_Rel &A, const Elf_Rel &B) {
1378
2
              return A.r_offset < B.r_offset;
1379
2
            });
1380
2
1381
2
  // Try to find groups of relative relocations which are spaced one word
1382
2
  // apart from one another. These generally correspond to vtable entries. The
1383
2
  // format allows these groups to be encoded using a sort of run-length
1384
2
  // encoding, but each group will cost 7 bytes in addition to the offset from
1385
2
  // the previous group, so it is only profitable to do this for groups of
1386
2
  // size 8 or larger.
1387
2
  std::vector<Elf_Rela> UngroupedRelatives;
1388
2
  std::vector<std::vector<Elf_Rela>> RelativeGroups;
1389
8
  for (auto I = Relatives.begin(), E = Relatives.end(); I != E;) {
1390
6
    std::vector<Elf_Rela> Group;
1391
48
    do {
1392
48
      Group.push_back(*I++);
1393
48
    } while (I != E && 
(I - 1)->r_offset + Config->Wordsize == I->r_offset46
);
1394
6
1395
6
    if (Group.size() < 8)
1396
2
      UngroupedRelatives.insert(UngroupedRelatives.end(), Group.begin(),
1397
2
                                Group.end());
1398
4
    else
1399
4
      RelativeGroups.emplace_back(std::move(Group));
1400
6
  }
1401
2
1402
2
  unsigned HasAddendIfRela =
1403
2
      Config->IsRela ? 
RELOCATION_GROUP_HAS_ADDEND_FLAG0
: 0;
1404
2
1405
2
  uint64_t Offset = 0;
1406
2
  uint64_t Addend = 0;
1407
2
1408
2
  // Emit the run-length encoding for the groups of adjacent relative
1409
2
  // relocations. Each group is represented using two groups in the packed
1410
2
  // format. The first is used to set the current offset to the start of the
1411
2
  // group (and also encodes the first relocation), and the second encodes the
1412
2
  // remaining relocations.
1413
4
  for (std::vector<Elf_Rela> &G : RelativeGroups) {
1414
4
    // The first relocation in the group.
1415
4
    Add(1);
1416
4
    Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1417
4
        RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1418
4
    Add(G[0].r_offset - Offset);
1419
4
    Add(Target->RelativeRel);
1420
4
    if (Config->IsRela) {
1421
0
      Add(G[0].r_addend - Addend);
1422
0
      Addend = G[0].r_addend;
1423
0
    }
1424
4
1425
4
    // The remaining relocations.
1426
4
    Add(G.size() - 1);
1427
4
    Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1428
4
        RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1429
4
    Add(Config->Wordsize);
1430
4
    Add(Target->RelativeRel);
1431
4
    if (Config->IsRela) {
1432
0
      for (auto I = G.begin() + 1, E = G.end(); I != E; ++I) {
1433
0
        Add(I->r_addend - Addend);
1434
0
        Addend = I->r_addend;
1435
0
      }
1436
0
    }
1437
4
1438
4
    Offset = G.back().r_offset;
1439
4
  }
1440
2
1441
2
  // Now the ungrouped relatives.
1442
2
  if (!UngroupedRelatives.empty()) {
1443
2
    Add(UngroupedRelatives.size());
1444
2
    Add(RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1445
2
    Add(Target->RelativeRel);
1446
14
    for (Elf_Rela &R : UngroupedRelatives) {
1447
14
      Add(R.r_offset - Offset);
1448
14
      Offset = R.r_offset;
1449
14
      if (Config->IsRela) {
1450
0
        Add(R.r_addend - Addend);
1451
0
        Addend = R.r_addend;
1452
0
      }
1453
14
    }
1454
2
  }
1455
2
1456
2
  // Finally the non-relative relocations.
1457
2
  std::sort(NonRelatives.begin(), NonRelatives.end(),
1458
2
            [](const Elf_Rela &A, const Elf_Rela &B) {
1459
2
              return A.r_offset < B.r_offset;
1460
2
            });
1461
2
  if (!NonRelatives.empty()) {
1462
2
    Add(NonRelatives.size());
1463
2
    Add(HasAddendIfRela);
1464
4
    for (Elf_Rela &R : NonRelatives) {
1465
4
      Add(R.r_offset - Offset);
1466
4
      Offset = R.r_offset;
1467
4
      Add(R.r_info);
1468
4
      if (Config->IsRela) {
1469
0
        Add(R.r_addend - Addend);
1470
0
        Addend = R.r_addend;
1471
0
      }
1472
4
    }
1473
2
  }
1474
2
1475
2
  // Returns whether the section size changed. We need to keep recomputing both
1476
2
  // section layout and the contents of this section until the size converges
1477
2
  // because changing this section's size can affect section layout, which in
1478
2
  // turn can affect the sizes of the LEB-encoded integers stored in this
1479
2
  // section.
1480
2
  return RelocData.size() != OldSize;
1481
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
1306
2
bool AndroidPackedRelocationSection<ELFT>::updateAllocSize() {
1307
2
  // This function computes the contents of an Android-format packed relocation
1308
2
  // section.
1309
2
  //
1310
2
  // This format compresses relocations by using relocation groups to factor out
1311
2
  // fields that are common between relocations and storing deltas from previous
1312
2
  // relocations in SLEB128 format (which has a short representation for small
1313
2
  // numbers). A good example of a relocation type with common fields is
1314
2
  // R_*_RELATIVE, which is normally used to represent function pointers in
1315
2
  // vtables. In the REL format, each relative relocation has the same r_info
1316
2
  // field, and is only different from other relative relocations in terms of
1317
2
  // the r_offset field. By sorting relocations by offset, grouping them by
1318
2
  // r_info and representing each relocation with only the delta from the
1319
2
  // previous offset, each 8-byte relocation can be compressed to as little as 1
1320
2
  // byte (or less with run-length encoding). This relocation packer was able to
1321
2
  // reduce the size of the relocation section in an Android Chromium DSO from
1322
2
  // 2,911,184 bytes to 174,693 bytes, or 6% of the original size.
1323
2
  //
1324
2
  // A relocation section consists of a header containing the literal bytes
1325
2
  // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two
1326
2
  // elements are the total number of relocations in the section and an initial
1327
2
  // r_offset value. The remaining elements define a sequence of relocation
1328
2
  // groups. Each relocation group starts with a header consisting of the
1329
2
  // following elements:
1330
2
  //
1331
2
  // - the number of relocations in the relocation group
1332
2
  // - flags for the relocation group
1333
2
  // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta
1334
2
  //   for each relocation in the group.
1335
2
  // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info
1336
2
  //   field for each relocation in the group.
1337
2
  // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and
1338
2
  //   RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for
1339
2
  //   each relocation in the group.
1340
2
  //
1341
2
  // Following the relocation group header are descriptions of each of the
1342
2
  // relocations in the group. They consist of the following elements:
1343
2
  //
1344
2
  // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset
1345
2
  //   delta for this relocation.
1346
2
  // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info
1347
2
  //   field for this relocation.
1348
2
  // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and
1349
2
  //   RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for
1350
2
  //   this relocation.
1351
2
1352
2
  size_t OldSize = RelocData.size();
1353
2
1354
2
  RelocData = {'A', 'P', 'S', '2'};
1355
2
  raw_svector_ostream OS(RelocData);
1356
2
  auto Add = [&](int64_t V) { encodeSLEB128(V, OS); };
1357
2
1358
2
  // The format header includes the number of relocations and the initial
1359
2
  // offset (we set this to zero because the first relocation group will
1360
2
  // perform the initial adjustment).
1361
2
  Add(Relocs.size());
1362
2
  Add(0);
1363
2
1364
2
  std::vector<Elf_Rela> Relatives, NonRelatives;
1365
2
1366
52
  for (const DynamicReloc &Rel : Relocs) {
1367
52
    Elf_Rela R;
1368
52
    encodeDynamicReloc<ELFT>(&R, Rel);
1369
52
1370
52
    if (R.getType(Config->IsMips64EL) == Target->RelativeRel)
1371
48
      Relatives.push_back(R);
1372
4
    else
1373
4
      NonRelatives.push_back(R);
1374
52
  }
1375
2
1376
2
  std::sort(Relatives.begin(), Relatives.end(),
1377
2
            [](const Elf_Rel &A, const Elf_Rel &B) {
1378
2
              return A.r_offset < B.r_offset;
1379
2
            });
1380
2
1381
2
  // Try to find groups of relative relocations which are spaced one word
1382
2
  // apart from one another. These generally correspond to vtable entries. The
1383
2
  // format allows these groups to be encoded using a sort of run-length
1384
2
  // encoding, but each group will cost 7 bytes in addition to the offset from
1385
2
  // the previous group, so it is only profitable to do this for groups of
1386
2
  // size 8 or larger.
1387
2
  std::vector<Elf_Rela> UngroupedRelatives;
1388
2
  std::vector<std::vector<Elf_Rela>> RelativeGroups;
1389
8
  for (auto I = Relatives.begin(), E = Relatives.end(); I != E;) {
1390
6
    std::vector<Elf_Rela> Group;
1391
48
    do {
1392
48
      Group.push_back(*I++);
1393
48
    } while (I != E && 
(I - 1)->r_offset + Config->Wordsize == I->r_offset46
);
1394
6
1395
6
    if (Group.size() < 8)
1396
2
      UngroupedRelatives.insert(UngroupedRelatives.end(), Group.begin(),
1397
2
                                Group.end());
1398
4
    else
1399
4
      RelativeGroups.emplace_back(std::move(Group));
1400
6
  }
1401
2
1402
2
  unsigned HasAddendIfRela =
1403
2
      Config->IsRela ? RELOCATION_GROUP_HAS_ADDEND_FLAG : 
00
;
1404
2
1405
2
  uint64_t Offset = 0;
1406
2
  uint64_t Addend = 0;
1407
2
1408
2
  // Emit the run-length encoding for the groups of adjacent relative
1409
2
  // relocations. Each group is represented using two groups in the packed
1410
2
  // format. The first is used to set the current offset to the start of the
1411
2
  // group (and also encodes the first relocation), and the second encodes the
1412
2
  // remaining relocations.
1413
4
  for (std::vector<Elf_Rela> &G : RelativeGroups) {
1414
4
    // The first relocation in the group.
1415
4
    Add(1);
1416
4
    Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1417
4
        RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1418
4
    Add(G[0].r_offset - Offset);
1419
4
    Add(Target->RelativeRel);
1420
4
    if (Config->IsRela) {
1421
4
      Add(G[0].r_addend - Addend);
1422
4
      Addend = G[0].r_addend;
1423
4
    }
1424
4
1425
4
    // The remaining relocations.
1426
4
    Add(G.size() - 1);
1427
4
    Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG |
1428
4
        RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1429
4
    Add(Config->Wordsize);
1430
4
    Add(Target->RelativeRel);
1431
4
    if (Config->IsRela) {
1432
34
      for (auto I = G.begin() + 1, E = G.end(); I != E; 
++I30
) {
1433
30
        Add(I->r_addend - Addend);
1434
30
        Addend = I->r_addend;
1435
30
      }
1436
4
    }
1437
4
1438
4
    Offset = G.back().r_offset;
1439
4
  }
1440
2
1441
2
  // Now the ungrouped relatives.
1442
2
  if (!UngroupedRelatives.empty()) {
1443
2
    Add(UngroupedRelatives.size());
1444
2
    Add(RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela);
1445
2
    Add(Target->RelativeRel);
1446
14
    for (Elf_Rela &R : UngroupedRelatives) {
1447
14
      Add(R.r_offset - Offset);
1448
14
      Offset = R.r_offset;
1449
14
      if (Config->IsRela) {
1450
14
        Add(R.r_addend - Addend);
1451
14
        Addend = R.r_addend;
1452
14
      }
1453
14
    }
1454
2
  }
1455
2
1456
2
  // Finally the non-relative relocations.
1457
2
  std::sort(NonRelatives.begin(), NonRelatives.end(),
1458
2
            [](const Elf_Rela &A, const Elf_Rela &B) {
1459
2
              return A.r_offset < B.r_offset;
1460
2
            });
1461
2
  if (!NonRelatives.empty()) {
1462
2
    Add(NonRelatives.size());
1463
2
    Add(HasAddendIfRela);
1464
4
    for (Elf_Rela &R : NonRelatives) {
1465
4
      Add(R.r_offset - Offset);
1466
4
      Offset = R.r_offset;
1467
4
      Add(R.r_info);
1468
4
      if (Config->IsRela) {
1469
4
        Add(R.r_addend - Addend);
1470
4
        Addend = R.r_addend;
1471
4
      }
1472
4
    }
1473
2
  }
1474
2
1475
2
  // Returns whether the section size changed. We need to keep recomputing both
1476
2
  // section layout and the contents of this section until the size converges
1477
2
  // because changing this section's size can affect section layout, which in
1478
2
  // turn can affect the sizes of the LEB-encoded integers stored in this
1479
2
  // section.
1480
2
  return RelocData.size() != OldSize;
1481
2
}
Unexecuted instantiation: lld::elf::AndroidPackedRelocationSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::updateAllocSize()
1482
1483
SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec)
1484
    : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0,
1485
                       StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
1486
                       Config->Wordsize,
1487
                       StrTabSec.isDynamic() ? ".dynsym" : ".symtab"),
1488
1.42k
      StrTabSec(StrTabSec) {}
1489
1490
// Orders symbols according to their positions in the GOT,
1491
// in compliance with MIPS ABI rules.
1492
// See "Global Offset Table" in Chapter 5 in the following document
1493
// for detailed description:
1494
// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1495
static bool sortMipsSymbols(const SymbolTableEntry &L,
1496
57
                            const SymbolTableEntry &R) {
1497
57
  // Sort entries related to non-local preemptible symbols by GOT indexes.
1498
57
  // All other entries go to the first part of GOT in arbitrary order.
1499
57
  bool LIsInLocalGot = !L.Sym->IsInGlobalMipsGot;
1500
57
  bool RIsInLocalGot = !R.Sym->IsInGlobalMipsGot;
1501
57
  if (LIsInLocalGot || 
RIsInLocalGot5
)
1502
56
    return !RIsInLocalGot;
1503
1
  return L.Sym->GotIndex < R.Sym->GotIndex;
1504
1
}
1505
1506
1.34k
void SymbolTableBaseSection::finalizeContents() {
1507
1.34k
  getParent()->Link = StrTabSec.getParent()->SectionIndex;
1508
1.34k
1509
1.34k
  // If it is a .dynsym, there should be no local symbols, but we need
1510
1.34k
  // to do a few things for the dynamic linker.
1511
1.34k
  if (this->Type == SHT_DYNSYM) {
1512
457
    // Section's Info field has the index of the first non-local symbol.
1513
457
    // Because the first symbol entry is a null entry, 1 is the first.
1514
457
    getParent()->Info = 1;
1515
457
1516
457
    if (InX::GnuHashTab) {
1517
344
      // NB: It also sorts Symbols to meet the GNU hash table requirements.
1518
344
      InX::GnuHashTab->addSymbols(Symbols);
1519
344
    } else 
if (113
Config->EMachine == EM_MIPS113
) {
1520
40
      std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1521
40
    }
1522
457
1523
457
    size_t I = 0;
1524
800
    for (const SymbolTableEntry &S : Symbols) S.Sym->DynsymIndex = ++I;
1525
457
    return;
1526
457
  }
1527
884
}
1528
1529
// The ELF spec requires that all local symbols precede global symbols, so we
1530
// sort symbol entries in this function. (For .dynsym, we don't do that because
1531
// symbols for dynamic linking are inherently all globals.)
1532
884
void SymbolTableBaseSection::postThunkContents() {
1533
884
  if (this->Type == SHT_DYNSYM)
1534
0
    return;
1535
884
  // move all local symbols before global symbols.
1536
884
  auto It = std::stable_partition(
1537
13.4k
      Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) {
1538
13.4k
        return S.Sym->isLocal() || 
S.Sym->computeBinding() == STB_LOCAL12.5k
;
1539
13.4k
      });
1540
884
  size_t NumLocals = It - Symbols.begin();
1541
884
  getParent()->Info = NumLocals + 1;
1542
884
}
1543
1544
14.3k
void SymbolTableBaseSection::addSymbol(Symbol *B) {
1545
14.3k
  // Adding a local symbol to a .dynsym is a bug.
1546
14.3k
  assert(this->Type != SHT_DYNSYM || !B->isLocal());
1547
14.3k
1548
14.3k
  bool HashIt = B->isLocal();
1549
14.3k
  Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)});
1550
14.3k
}
1551
1552
40
size_t SymbolTableBaseSection::getSymbolIndex(Symbol *Sym) {
1553
40
  // Initializes symbol lookup tables lazily. This is used only
1554
40
  // for -r or -emit-relocs.
1555
40
  llvm::call_once(OnceFlag, [&] {
1556
19
    SymbolIndexMap.reserve(Symbols.size());
1557
19
    size_t I = 0;
1558
91
    for (const SymbolTableEntry &E : Symbols) {
1559
91
      if (E.Sym->Type == STT_SECTION)
1560
47
        SectionIndexMap[E.Sym->getOutputSection()] = ++I;
1561
44
      else
1562
44
        SymbolIndexMap[E.Sym] = ++I;
1563
91
    }
1564
19
  });
1565
40
1566
40
  // Section symbols are mapped based on their output sections
1567
40
  // to maintain their semantics.
1568
40
  if (Sym->Type == STT_SECTION)
1569
9
    return SectionIndexMap.lookup(Sym->getOutputSection());
1570
31
  return SymbolIndexMap.lookup(Sym);
1571
31
}
1572
1573
template <class ELFT>
1574
SymbolTableSection<ELFT>::SymbolTableSection(StringTableSection &StrTabSec)
1575
1.42k
    : SymbolTableBaseSection(StrTabSec) {
1576
1.42k
  this->Entsize = sizeof(Elf_Sym);
1577
1.42k
}
lld::elf::SymbolTableSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::SymbolTableSection(lld::elf::StringTableSection&)
Line
Count
Source
1575
187
    : SymbolTableBaseSection(StrTabSec) {
1576
187
  this->Entsize = sizeof(Elf_Sym);
1577
187
}
lld::elf::SymbolTableSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::SymbolTableSection(lld::elf::StringTableSection&)
Line
Count
Source
1575
80
    : SymbolTableBaseSection(StrTabSec) {
1576
80
  this->Entsize = sizeof(Elf_Sym);
1577
80
}
lld::elf::SymbolTableSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::SymbolTableSection(lld::elf::StringTableSection&)
Line
Count
Source
1575
1.10k
    : SymbolTableBaseSection(StrTabSec) {
1576
1.10k
  this->Entsize = sizeof(Elf_Sym);
1577
1.10k
}
lld::elf::SymbolTableSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::SymbolTableSection(lld::elf::StringTableSection&)
Line
Count
Source
1575
45
    : SymbolTableBaseSection(StrTabSec) {
1576
45
  this->Entsize = sizeof(Elf_Sym);
1577
45
}
1578
1579
// Write the internal symbol table contents to the output symbol table.
1580
1.32k
template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
1581
1.32k
  // The first entry is a null entry as per the ELF spec.
1582
1.32k
  memset(Buf, 0, sizeof(Elf_Sym));
1583
1.32k
  Buf += sizeof(Elf_Sym);
1584
1.32k
1585
1.32k
  auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1586
1.32k
1587
14.2k
  for (SymbolTableEntry &Ent : Symbols) {
1588
14.2k
    Symbol *Sym = Ent.Sym;
1589
14.2k
1590
14.2k
    // Set st_info and st_other.
1591
14.2k
    ESym->st_other = 0;
1592
14.2k
    if (Sym->isLocal()) {
1593
845
      ESym->setBindingAndType(STB_LOCAL, Sym->Type);
1594
13.3k
    } else {
1595
13.3k
      ESym->setBindingAndType(Sym->computeBinding(), Sym->Type);
1596
13.3k
      ESym->setVisibility(Sym->Visibility);
1597
13.3k
    }
1598
14.2k
1599
14.2k
    ESym->st_name = Ent.StrTabOffset;
1600
14.2k
1601
14.2k
    // Set a section index.
1602
14.2k
    BssSection *CommonSec = nullptr;
1603
14.2k
    if (!Config->DefineCommon)
1604
112
      if (auto *D = dyn_cast<Defined>(Sym))
1605
102
        CommonSec = dyn_cast_or_null<BssSection>(D->Section);
1606
14.2k
    if (CommonSec)
1607
1
      ESym->st_shndx = SHN_COMMON;
1608
14.2k
    else if (const OutputSection *OutSec = Sym->getOutputSection())
1609
13.6k
      ESym->st_shndx = OutSec->SectionIndex;
1610
586
    else if (isa<Defined>(Sym))
1611
121
      ESym->st_shndx = SHN_ABS;
1612
465
    else
1613
465
      ESym->st_shndx = SHN_UNDEF;
1614
14.2k
1615
14.2k
    // Copy symbol size if it is a defined symbol. st_size is not significant
1616
14.2k
    // for undefined symbols, so whether copying it or not is up to us if that's
1617
14.2k
    // the case. We'll leave it as zero because by not setting a value, we can
1618
14.2k
    // get the exact same outputs for two sets of input files that differ only
1619
14.2k
    // in undefined symbol size in DSOs.
1620
14.2k
    if (ESym->st_shndx == SHN_UNDEF)
1621
465
      ESym->st_size = 0;
1622
13.7k
    else
1623
13.7k
      ESym->st_size = Sym->getSize();
1624
14.2k
1625
14.2k
    // st_value is usually an address of a symbol, but that has a
1626
14.2k
    // special meaining for uninstantiated common symbols (this can
1627
14.2k
    // occur if -r is given).
1628
14.2k
    if (CommonSec)
1629
1
      ESym->st_value = CommonSec->Alignment;
1630
14.2k
    else
1631
14.2k
      ESym->st_value = Sym->getVA();
1632
14.2k
1633
14.2k
    ++ESym;
1634
14.2k
  }
1635
1.32k
1636
1.32k
  // On MIPS we need to mark symbol which has a PLT entry and requires
1637
1.32k
  // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1638
1.32k
  // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1639
1.32k
  // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1640
1.32k
  if (Config->EMachine == EM_MIPS) {
1641
111
    auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1642
111
1643
10.4k
    for (SymbolTableEntry &Ent : Symbols) {
1644
10.4k
      Symbol *Sym = Ent.Sym;
1645
10.4k
      if (Sym->isInPlt() && 
Sym->NeedsPltAddr10
)
1646
0
        ESym->st_other |= STO_MIPS_PLT;
1647
10.4k
      if (isMicroMips()) {
1648
70
        // Set STO_MIPS_MICROMIPS flag and less-significant bit for
1649
70
        // defined microMIPS symbols and shared symbols with PLT record.
1650
70
        if ((Sym->isDefined() && 
(Sym->StOther & STO_MIPS_MICROMIPS)62
) ||
1651
70
            
(57
Sym->isShared()57
&&
Sym->NeedsPltAddr8
)) {
1652
13
          if (StrTabSec.isDynamic())
1653
1
            ESym->st_value |= 1;
1654
13
          ESym->st_other |= STO_MIPS_MICROMIPS;
1655
13
        }
1656
70
      }
1657
10.4k
      if (Config->Relocatable)
1658
26
        if (auto *D = dyn_cast<Defined>(Sym))
1659
26
          if (isMipsPIC<ELFT>(D))
1660
5
            ESym->st_other |= STO_MIPS_PIC;
1661
10.4k
      ++ESym;
1662
10.4k
    }
1663
111
  }
1664
1.32k
}
lld::elf::SymbolTableSection<llvm::object::ELFType<(llvm::support::endianness)1, false> >::writeTo(unsigned char*)
Line
Count
Source
1580
183
template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
1581
183
  // The first entry is a null entry as per the ELF spec.
1582
183
  memset(Buf, 0, sizeof(Elf_Sym));
1583
183
  Buf += sizeof(Elf_Sym);
1584
183
1585
183
  auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1586
183
1587
1.08k
  for (SymbolTableEntry &Ent : Symbols) {
1588
1.08k
    Symbol *Sym = Ent.Sym;
1589
1.08k
1590
1.08k
    // Set st_info and st_other.
1591
1.08k
    ESym->st_other = 0;
1592
1.08k
    if (Sym->isLocal()) {
1593
416
      ESym->setBindingAndType(STB_LOCAL, Sym->Type);
1594
669
    } else {
1595
669
      ESym->setBindingAndType(Sym->computeBinding(), Sym->Type);
1596
669
      ESym->setVisibility(Sym->Visibility);
1597
669
    }
1598
1.08k
1599
1.08k
    ESym->st_name = Ent.StrTabOffset;
1600
1.08k
1601
1.08k
    // Set a section index.
1602
1.08k
    BssSection *CommonSec = nullptr;
1603
1.08k
    if (!Config->DefineCommon)
1604
3
      if (auto *D = dyn_cast<Defined>(Sym))
1605
2
        CommonSec = dyn_cast_or_null<BssSection>(D->Section);
1606
1.08k
    if (CommonSec)
1607
0
      ESym->st_shndx = SHN_COMMON;
1608
1.08k
    else if (const OutputSection *OutSec = Sym->getOutputSection())
1609
958
      ESym->st_shndx = OutSec->SectionIndex;
1610
127
    else if (isa<Defined>(Sym))
1611
17
      ESym->st_shndx = SHN_ABS;
1612
110
    else
1613
110
      ESym->st_shndx = SHN_UNDEF;
1614
1.08k
1615
1.08k
    // Copy symbol size if it is a defined symbol. st_size is not significant
1616
1.08k
    // for undefined symbols, so whether copying it or not is up to us if that's
1617
1.08k
    // the case. We'll leave it as zero because by not setting a value, we can
1618
1.08k
    // get the exact same outputs for two sets of input files that differ only
1619
1.08k
    // in undefined symbol size in DSOs.
1620
1.08k
    if (ESym->st_shndx == SHN_UNDEF)
1621
110
      ESym->st_size = 0;
1622
975
    else
1623
975
      ESym->st_size = Sym->getSize();
1624
1.08k
1625
1.08k
    // st_value is usually an address of a symbol, but that has a
1626
1.08k
    // special meaining for uninstantiated common symbols (this can
1627
1.08k
    // occur if -r is given).
1628
1.08k
    if (CommonSec)
1629
0
      ESym->st_value = CommonSec->Alignment;
1630
1.08k
    else
1631
1.08k
      ESym->st_value = Sym->getVA();
1632
1.08k
1633
1.08k
    ++ESym;
1634
1.08k
  }
1635
183
1636
183
  // On MIPS we need to mark symbol which has a PLT entry and requires
1637
183
  // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1638
183
  // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1639
183
  // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1640
183
  if (Config->EMachine == EM_MIPS) {
1641
6
    auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1642
6
1643
19
    for (SymbolTableEntry &Ent : Symbols) {
1644
19
      Symbol *Sym = Ent.Sym;
1645
19
      if (Sym->isInPlt() && 
Sym->NeedsPltAddr2
)
1646
0
        ESym->st_other |= STO_MIPS_PLT;
1647
19
      if (isMicroMips()) {
1648
10
        // Set STO_MIPS_MICROMIPS flag and less-significant bit for
1649
10
        // defined microMIPS symbols and shared symbols with PLT record.
1650
10
        if ((Sym->isDefined() && 
(Sym->StOther & STO_MIPS_MICROMIPS)8
) ||
1651
10
            
(6
Sym->isShared()6
&&
Sym->NeedsPltAddr2
)) {
1652
4
          if (StrTabSec.isDynamic())
1653
0
            ESym->st_value |= 1;
1654
4
          ESym->st_other |= STO_MIPS_MICROMIPS;
1655
4
        }
1656
10
      }
1657
19
      if (Config->Relocatable)
1658
0
        if (auto *D = dyn_cast<Defined>(Sym))
1659
0
          if (isMipsPIC<ELFT>(D))
1660
0
            ESym->st_other |= STO_MIPS_PIC;
1661
19
      ++ESym;
1662
19
    }
1663
6
  }
1664
183
}
lld::elf::SymbolTableSection<llvm::object::ELFType<(llvm::support::endianness)0, false> >::writeTo(unsigned char*)
Line
Count
Source
1580
78
template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
1581
78
  // The first entry is a null entry as per the ELF spec.
1582
78
  memset(Buf, 0, sizeof(Elf_Sym));
1583
78
  Buf += sizeof(Elf_Sym);
1584
78
1585
78
  auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1586
78
1587
334
  for (SymbolTableEntry &Ent : Symbols) {
1588
334
    Symbol *Sym = Ent.Sym;
1589
334
1590
334
    // Set st_info and st_other.
1591
334
    ESym->st_other = 0;
1592
334
    if (Sym->isLocal()) {
1593
63
      ESym->setBindingAndType(STB_LOCAL, Sym->Type);
1594
271
    } else {
1595
271
      ESym->setBindingAndType(Sym->computeBinding(), Sym->Type);
1596
271
      ESym->setVisibility(Sym->Visibility);
1597
271
    }
1598
334
1599
334
    ESym->st_name = Ent.StrTabOffset;
1600
334
1601
334
    // Set a section index.
1602
334
    BssSection *CommonSec = nullptr;
1603
334
    if (!Config->DefineCommon)
1604
26
      if (auto *D = dyn_cast<Defined>(Sym))
1605
26
        CommonSec = dyn_cast_or_null<BssSection>(D->Section);
1606
334
    if (CommonSec)
1607
0
      ESym->st_shndx = SHN_COMMON;
1608
334
    else if (const OutputSection *OutSec = Sym->getOutputSection())
1609
314
      ESym->st_shndx = OutSec->SectionIndex;
1610
20
    else if (isa<Defined>(Sym))
1611
2
      ESym->st_shndx = SHN_ABS;
1612
18
    else
1613
18
      ESym->st_shndx = SHN_UNDEF;
1614
334
1615
334
    // Copy symbol size if it is a defined symbol. st_size is not significant
1616
334
    // for undefined symbols, so whether copying it or not is up to us if that's
1617
334
    // the case. We'll leave it as zero because by not setting a value, we can
1618
334
    // get the exact same outputs for two sets of input files that differ only
1619
334
    // in undefined symbol size in DSOs.
1620
334
    if (ESym->st_shndx == SHN_UNDEF)
1621
18
      ESym->st_size = 0;
1622
316
    else
1623
316
      ESym->st_size = Sym->getSize();
1624
334
1625
334
    // st_value is usually an address of a symbol, but that has a
1626
334
    // special meaining for uninstantiated common symbols (this can
1627
334
    // occur if -r is given).
1628
334
    if (CommonSec)
1629
0
      ESym->st_value = CommonSec->Alignment;
1630
334
    else
1631
334
      ESym->st_value = Sym->getVA();
1632
334
1633
334
    ++ESym;
1634
334
  }
1635
78
1636
78
  // On MIPS we need to mark symbol which has a PLT entry and requires
1637
78
  // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1638
78
  // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1639
78
  // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1640
78
  if (Config->EMachine == EM_MIPS) {
1641
76
    auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1642
76
1643
333
    for (SymbolTableEntry &Ent : Symbols) {
1644
333
      Symbol *Sym = Ent.Sym;
1645
333
      if (Sym->isInPlt() && 
Sym->NeedsPltAddr6
)
1646
0
        ESym->st_other |= STO_MIPS_PLT;
1647
333
      if (isMicroMips()) {
1648
48
        // Set STO_MIPS_MICROMIPS flag and less-significant bit for
1649
48
        // defined microMIPS symbols and shared symbols with PLT record.
1650
48
        if ((Sym->isDefined() && 
(Sym->StOther & STO_MIPS_MICROMIPS)42
) ||
1651
48
            
(39
Sym->isShared()39
&&
Sym->NeedsPltAddr6
)) {
1652
9
          if (StrTabSec.isDynamic())
1653
1
            ESym->st_value |= 1;
1654
9
          ESym->st_other |= STO_MIPS_MICROMIPS;
1655
9
        }
1656
48
      }
1657
333
      if (Config->Relocatable)
1658
26
        if (auto *D = dyn_cast<Defined>(Sym))
1659
26
          if (isMipsPIC<ELFT>(D))
1660
5
            ESym->st_other |= STO_MIPS_PIC;
1661
333
      ++ESym;
1662
333
    }
1663
76
  }
1664
78
}
lld::elf::SymbolTableSection<llvm::object::ELFType<(llvm::support::endianness)1, true> >::writeTo(unsigned char*)
Line
Count
Source
1580
1.02k
template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
1581
1.02k
  // The first entry is a null entry as per the ELF spec.
1582
1.02k
  memset(Buf, 0, sizeof(Elf_Sym));
1583
1.02k
  Buf += sizeof(Elf_Sym);
1584
1.02k
1585
1.02k
  auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1586
1.02k
1587
2.63k
  for (SymbolTableEntry &Ent : Symbols) {
1588
2.63k
    Symbol *Sym = Ent.Sym;
1589
2.63k
1590
2.63k
    // Set st_info and st_other.
1591
2.63k
    ESym->st_other = 0;
1592
2.63k
    if (Sym->isLocal()) {
1593
358
      ESym->setBindingAndType(STB_LOCAL, Sym->Type);
1594
2.27k
    } else {
1595
2.27k
      ESym->setBindingAndType(Sym->computeBinding(), Sym->Type);
1596
2.27k
      ESym->setVisibility(Sym->Visibility);
1597
2.27k
    }
1598
2.63k
1599
2.63k
    ESym->st_name = Ent.StrTabOffset;
1600
2.63k
1601
2.63k
    // Set a section index.
1602
2.63k
    BssSection *CommonSec = nullptr;
1603
2.63k
    if (!Config->DefineCommon)
1604
83
      if (auto *D = dyn_cast<Defined>(Sym))
1605
74
        CommonSec = dyn_cast_or_null<BssSection>(D->Section);
1606
2.63k
    if (CommonSec)
1607
1
      ESym->st_shndx = SHN_COMMON;
1608
2.63k
    else if (const OutputSection *OutSec = Sym->getOutputSection())
1609
2.21k
      ESym->st_shndx = OutSec->SectionIndex;
1610
418
    else if (isa<Defined>(Sym))
1611
101
      ESym->st_shndx = SHN_ABS;
1612
317
    else
1613
317
      ESym->st_shndx = SHN_UNDEF;
1614
2.63k
1615
2.63k
    // Copy symbol size if it is a defined symbol. st_size is not significant
1616
2.63k
    // for undefined symbols, so whether copying it or not is up to us if that's
1617
2.63k
    // the case. We'll leave it as zero because by not setting a value, we can
1618
2.63k
    // get the exact same outputs for two sets of input files that differ only
1619
2.63k
    // in undefined symbol size in DSOs.
1620
2.63k
    if (ESym->st_shndx == SHN_UNDEF)
1621
317
      ESym->st_size = 0;
1622
2.31k
    else
1623
2.31k
      ESym->st_size = Sym->getSize();
1624
2.63k
1625
2.63k
    // st_value is usually an address of a symbol, but that has a
1626
2.63k
    // special meaining for uninstantiated common symbols (this can
1627
2.63k
    // occur if -r is given).
1628
2.63k
    if (CommonSec)
1629
1
      ESym->st_value = CommonSec->Alignment;
1630
2.63k
    else
1631
2.63k
      ESym->st_value = Sym->getVA();
1632
2.63k
1633
2.63k
    ++ESym;
1634
2.63k
  }
1635
1.02k
1636
1.02k
  // On MIPS we need to mark symbol which has a PLT entry and requires
1637
1.02k
  // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1638
1.02k
  // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1639
1.02k
  // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1640
1.02k
  if (Config->EMachine == EM_MIPS) {
1641
0
    auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1642
0
1643
0
    for (SymbolTableEntry &Ent : Symbols) {
1644
0
      Symbol *Sym = Ent.Sym;
1645
0
      if (Sym->isInPlt() && Sym->NeedsPltAddr)
1646
0
        ESym->st_other |= STO_MIPS_PLT;
1647
0
      if (isMicroMips()) {
1648
0
        // Set STO_MIPS_MICROMIPS flag and less-significant bit for
1649
0
        // defined microMIPS symbols and shared symbols with PLT record.
1650
0
        if ((Sym->isDefined() && (Sym->StOther & STO_MIPS_MICROMIPS)) ||
1651
0
            (Sym->isShared() && Sym->NeedsPltAddr)) {
1652
0
          if (StrTabSec.isDynamic())
1653
0
            ESym->st_value |= 1;
1654
0
          ESym->st_other |= STO_MIPS_MICROMIPS;
1655
0
        }
1656
0
      }
1657
0
      if (Config->Relocatable)
1658
0
        if (auto *D = dyn_cast<Defined>(Sym))
1659
0
          if (isMipsPIC<ELFT>(D))
1660
0
            ESym->st_other |= STO_MIPS_PIC;
1661
0
      ++ESym;
1662
0
    }
1663
0
  }
1664
1.02k
}
lld::elf::SymbolTableSection<llvm::object::ELFType<(llvm::support::endianness)0, true> >::writeTo(unsigned char*)
Line
Count
Source
1580
44
template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
1581
44
  // The first entry is a null entry as per the ELF spec.
1582
44
  memset(Buf, 0, sizeof(Elf_Sym));
1583
44
  Buf += sizeof(Elf_Sym);
1584
44
1585
44
  auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1586
44
1587
10.1k
  for (SymbolTableEntry &Ent : Symbols) {
1588
10.1k
    Symbol *Sym = Ent.Sym;
1589
10.1k
1590
10.1k
    // Set st_info and st_other.
1591
10.1k
    ESym->st_other = 0;
1592
10.1k
    if (Sym->isLocal()) {
1593
8
      ESym->setBindingAndType(STB_LOCAL, Sym->Type);
1594
10.1k
    } else {
1595
10.1k
      ESym->setBindingAndType(Sym->computeBinding(), Sym->Type);
1596
10.1k
      ESym->setVisibility(Sym->Visibility);
1597
10.1k
    }
1598
10.1k
1599
10.1k
    ESym->st_name = Ent.StrTabOffset;
1600
10.1k
1601
10.1k
    // Set a section index.
1602
10.1k
    BssSection *CommonSec = nullptr;
1603
10.1k
    if (!Config->DefineCommon)
1604
0
      if (auto *D = dyn_cast<Defined>(Sym))
1605
0
        CommonSec = dyn_cast_or_null<BssSection>(D->Section);
1606
10.1k
    if (CommonSec)
1607
0
      ESym->st_shndx = SHN_COMMON;
1608
10.1k
    else if (const OutputSection *OutSec = Sym->getOutputSection())
1609
10.1k
      ESym->st_shndx = OutSec->SectionIndex;
1610
21
    else if (isa<Defined>(Sym))
1611
1
      ESym->st_shndx = SHN_ABS;
1612
20
    else
1613
20
      ESym->st_shndx = SHN_UNDEF;
1614
10.1k
1615
10.1k
    // Copy symbol size if it is a defined symbol. st_size is not significant
1616
10.1k
    // for undefined symbols, so whether copying it or not is up to us if that's
1617
10.1k
    // the case. We'll leave it as zero because by not setting a value, we can
1618
10.1k
    // get the exact same outputs for two sets of input files that differ only
1619
10.1k
    // in undefined symbol size in DSOs.
1620
10.1k
    if (ESym->st_shndx == SHN_UNDEF)
1621
20
      ESym->st_size = 0;
1622
10.1k
    else
1623
10.1k
      ESym->st_size = Sym->getSize();
1624
10.1k
1625
10.1k
    // st_value is usually an address of a symbol, but that has a
1626
10.1k
    // special meaining for uninstantiated common symbols (this can
1627
10.1k
    // occur if -r is given).
1628
10.1k
    if (CommonSec)
1629
0
      ESym->st_value = CommonSec->Alignment;
1630
10.1k
    else
1631
10.1k
      ESym->st_value = Sym->getVA();
1632
10.1k
1633
10.1k
    ++ESym;
1634
10.1k
  }
1635
44
1636
44
  // On MIPS we need to mark symbol which has a PLT entry and requires
1637
44
  // pointer equality by STO_MIPS_PLT flag. That is necessary to help
1638
44
  // dynamic linker distinguish such symbols and MIPS lazy-binding stubs.
1639
44
  // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1640
44
  if (Config->EMachine == EM_MIPS) {
1641
29
    auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1642
29
1643
10.1k
    for (SymbolTableEntry &Ent : Symbols) {
1644
10.1k
      Symbol *Sym = Ent.Sym;
1645
10.1k
      if (Sym->isInPlt() && 
Sym->NeedsPltAddr2
)
1646
0
        ESym->st_other |= STO_MIPS_PLT;
1647
10.1k
      if (isMicroMips()) {
1648
12
        // Set STO_MIPS_MICROMIPS flag and less-significant bit for
1649
12
        // defined microMIPS symbols and shared symbols with PLT record.
1650
12
        if ((Sym->isDefined() && (Sym->StOther & STO_MIPS_MICROMIPS)) ||
1651
12
            (Sym->isShared() && 
Sym->NeedsPltAddr0
)) {
1652
0
          if (StrTabSec.isDynamic())
1653
0
            ESym->st_value |= 1;
1654
0
          ESym->st_other |= STO_MIPS_MICROMIPS;
1655
0
        }
1656
12
      }
1657
10.1k
      if (Config->Relocatable)
1658
0
        if (auto *D = dyn_cast<Defined>(Sym))
1659
0
          if (isMipsPIC<ELFT>(D))
1660
0
            ESym->st_other |= STO_MIPS_PIC;
1661
10.1k
      ++ESym;
1662
10.1k
    }
1663
29
  }
1664
44
}
1665
1666
// .hash and .gnu.hash sections contain on-disk hash tables that map
1667
// symbol names to their dynamic symbol table indices. Their purpose
1668
// is to help the dynamic linker resolve symbols quickly. If ELF files
1669
// don't have them, the dynamic linker has to do linear search on all
1670
// dynamic symbols, which makes programs slower. Therefore, a .hash
1671
// section is added to a DSO by default. A .gnu.hash is added if you
1672
// give the -hash-style=gnu or -hash-style=both option.
1673
//
1674
// The Unix semantics of resolving dynamic symbols is somewhat expensive.
1675
// Each ELF file has a list of DSOs that the ELF file depends on and a
1676
// list of dynamic symbols that need to be resolved from any of the
1677
// DSOs. That means resolving all dynamic symbols takes O(m)*O(n)
1678
// where m is the number of DSOs and n is the number of dynamic
1679
// symbols. For modern large programs, both m and n are large.  So
1680
// making each step faster by using hash tables substiantially
1681
// improves time to load programs.
1682
//
1683
// (Note that this is not the only way to design the shared library.
1684
// For instance, the Windows DLL takes a different approach. On
1685
// Windows, each dynamic symbol has a name of DLL from which the symbol
1686
// has to be resolved. That makes the cost of symbol resolution O(n).
1687
// This disables some hacky techniques you can use on Unix such as
1688
// LD_PRELOAD, but this is arguably better semantics than the Unix ones.)
1689
//
1690
// Due to historical reasons, we have two different hash tables, .hash
1691
// and .gnu.hash. They are for the same purpose, and .gnu.hash is a new
1692
// and better version of .hash. .hash is just an on-disk hash table, but
1693
// .gnu.hash has a bloom filter in addition to a hash table to skip
1694
// DSOs very quickly. If you are sure that your dynamic linker knows
1695
// about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a
1696
// safe bet is to specify -hash-style=both for backward compatibilty.
1697
GnuHashTableSection::GnuHashTableSection()
1698
375
    : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") {
1699
375
}
1700
1701
344
void GnuHashTableSection::finalizeContents() {
1702
344
  getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
1703
344
1704
344
  // Computes bloom filter size in word size. We want to allocate 8
1705
344
  // bits for each symbol. It must be a power of two.
1706
344
  if (Symbols.empty())
1707
119
    MaskWords = 1;
1708
225
  else
1709
225
    MaskWords = NextPowerOf2((Symbols.size() - 1) / Config->Wordsize);
1710
344
1711
344
  Size = 16;                            // Header
1712
344
  Size += Config->Wordsize * MaskWords; // Bloom filter
1713
344
  Size += NBuckets * 4;                 // Hash buckets
1714
344
  Size += Symbols.size() * 4;           // Hash values
1715
344
}
1716
1717
340
void GnuHashTableSection::writeTo(uint8_t *Buf) {
1718
340
  // The output buffer is not guaranteed to be zero-cleared because we pre-
1719
340
  // fill executable sections with trap instructions. This is a precaution
1720
340
  // for that case, which happens only when -no-rosegment is given.
1721
340
  memset(Buf, 0, Size);
1722
340
1723
340
  // Write a header.
1724
340
  write32(Buf, NBuckets);
1725
340
  write32(Buf + 4, InX::DynSymTab->getNumSymbols() - Symbols.size());
1726
340
  write32(Buf + 8, MaskWords);
1727
340
  write32(Buf + 12, getShift2());
1728
340
  Buf += 16;
1729
340
1730
340
  // Write a bloom filter and a hash table.
1731
340
  writeBloomFilter(Buf);
1732
340
  Buf += Config->Wordsize * MaskWords;
1733
340
  writeHashTable(Buf);
1734
340
}
1735
1736
// This function writes a 2-bit bloom filter. This bloom filter alone
1737
// usually filters out 80% or more of all symbol lookups [1].
1738
// The dynamic linker uses the hash table only when a symbol is not
1739
// filtered out by a bloom filter.
1740
//
1741
// [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2),
1742
//     p.9, https://www.akkadia.org/drepper/dsohowto.pdf
1743
340
void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) {
1744
340
  const unsigned C = Config->Wordsize * 8;
1745
429
  for (const Entry &Sym : Symbols) {
1746
429
    size_t I = (Sym.Hash / C) & (MaskWords - 1);
1747
429
    uint64_t Val = readUint(Buf + I * Config->Wordsize);
1748
429
    Val |= uint64_t(1) << (Sym.Hash % C);
1749
429
    Val |= uint64_t(1) << ((Sym.Hash >> getShift2()) % C);
1750
429
    writeUint(Buf + I * Config->Wordsize, Val);
1751
429
  }
1752
340
}
1753
1754
340
void GnuHashTableSection::writeHashTable(uint8_t *Buf) {
1755
340
  uint32_t *Buckets = reinterpret_cast<uint32_t *>(Buf);
1756
340
  uint32_t OldBucket = -1;
1757
340
  uint32_t *Values = Buckets + NBuckets;
1758
769
  for (auto I = Symbols.begin(), E = Symbols.end(); I != E; 
++I429
) {
1759
429
    // Write a hash value. It represents a sequence of chains that share the
1760
429
    // same hash modulo value. The last element of each chain is terminated by
1761
429
    // LSB 1.
1762
429
    uint32_t Hash = I->Hash;
1763
429
    bool IsLastInChain = (I + 1) == E || 
I->BucketIdx != (I + 1)->BucketIdx206
;
1764
429
    Hash = IsLastInChain ? 
Hash | 1230
:
Hash & ~1199
;
1765
429
    write32(Values++, Hash);
1766
429
1767
429
    if (I->BucketIdx == OldBucket)
1768
199
      continue;
1769
230
    // Write a hash bucket. Hash buckets contain indices in the following hash
1770
230
    // value table.
1771
230
    write32(Buckets + I->BucketIdx, I->Sym->DynsymIndex);
1772
230
    OldBucket = I->BucketIdx;
1773
230
  }
1774
340
}
1775
1776
431
static uint32_t hashGnu(StringRef Name) {
1777
431
  uint32_t H = 5381;
1778
431
  for (uint8_t C : Name)
1779
2.40k
    H = (H << 5) + H + C;
1780
431
  return H;
1781
431
}
1782
1783
// Add symbols to this symbol hash table. Note that this function
1784
// destructively sort a given vector -- which is needed because
1785
// GNU-style hash table places some sorting requirements.
1786
344
void GnuHashTableSection::addSymbols(std::vector<SymbolTableEntry> &V) {
1787
344
  // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce
1788
344
  // its type correctly.
1789
344
  std::vector<SymbolTableEntry>::iterator Mid =
1790
550
      std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) {
1791
550
        // Shared symbols that this executable preempts are special. The dynamic
1792
550
        // linker has to look them up, so they have to be in the hash table.
1793
550
        if (auto *SS = dyn_cast<SharedSymbol>(S.Sym))
1794
101
          return SS->CopyRelSec == nullptr && 
!SS->NeedsPltAddr81
;
1795
449
        return !S.Sym->isDefined();
1796
449
      });
1797
344
  if (Mid == V.end())
1798
119
    return;
1799
225
1800
225
  // We chose load factor 4 for the on-disk hash table. For each hash
1801
225
  // collision, the dynamic linker will compare a uint32_t hash value.
1802
225
  // Since the integer comparison is quite fast, we believe we can make
1803
225
  // the load factor even larger. 4 is just a conservative choice.
1804
225
  NBuckets = std::max<size_t>((V.end() - Mid) / 4, 1);
1805
225
1806
431
  for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) {
1807
431
    Symbol *B = Ent.Sym;
1808
431
    uint32_t Hash = hashGnu(B->getName());
1809
431
    uint32_t BucketIdx = Hash % NBuckets;
1810
431
    Symbols.push_back({B, Ent.StrTabOffset, Hash, BucketIdx});
1811
431
  }
1812
225
1813
225
  std::stable_sort(
1814
225
      Symbols.begin(), Symbols.end(),
1815
450
      [](const Entry &L, const Entry &R) { return L.BucketIdx < R.BucketIdx; });
1816
225
1817
225
  V.erase(Mid, V.end());
1818
225
  for (const Entry &Ent : Symbols)
1819
431
    V.push_back({Ent.Sym, Ent.StrTabOffset});
1820
225
}
1821
1822
HashTableSection::HashTableSection()
1823
484
    : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") {
1824
484
  this->Entsize = 4;
1825
484
}
1826
1827
453
void HashTableSection::finalizeContents() {
1828
453
  getParent()->Link = InX::DynSymTab->getParent()->SectionIndex;
1829
453
1830
453
  unsigned NumEntries = 2;                       // nbucket and nchain.
1831
453
  NumEntries += InX::DynSymTab->getNumSymbols(); // The chain entries.
1832
453
1833
453
  // Create as many buckets as there are symbols.
1834
453
  NumEntries += InX::DynSymTab->getNumSymbols();
1835
453
  this->Size = NumEntries * 4;
1836
453
}
1837
1838
449
void HashTableSection::writeTo(uint8_t *Buf) {
1839
449
  // See comment in GnuHashTableSection::writeTo.
1840
449
  memset(Buf, 0, Size);
1841
449
1842
449
  unsigned NumSymbols = InX::DynSymTab->getNumSymbols();
1843
449
1844
449
  uint32_t *P = reinterpret_cast<uint32_t *>(Buf);
1845
449
  write32(P++, NumSymbols); // nbucket
1846
449
  write32(P++, NumSymbols); // nchain
1847
449
1848
449
  uint32_t *Buckets = P;
1849
449
  uint32_t *Chains = P + NumSymbols;
1850
449
1851
788
  for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) {
1852
788
    Symbol *Sym = S.Sym;
1853
788
    StringRef Name = Sym->getName();
1854
788
    unsigned I = Sym->DynsymIndex;
1855
788
    uint32_t Hash = hashSysV(Name) % NumSymbols;
1856
788
    Chains[I] = Buckets[Hash];
1857
788
    write32(Buckets + Hash, I);
1858
788
  }
1859
449
}
1860
1861
PltSection::PltSection(bool IsIplt)
1862
    : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"),
1863
1.87k
      HeaderSize(IsIplt ? 0 : Target->PltHeaderSize), IsIplt(IsIplt) {
1864
1.87k
  // The PLT needs to be writable on SPARC as the dynamic linker will
1865
1.87k
  // modify the instructions in the PLT entries.
1866
1.87k
  if (Config->EMachine == EM_SPARCV9)
1867
2
    this->Flags |= SHF_WRITE;
1868
1.87k
}
1869
1870
99
void PltSection::writeTo(uint8_t *Buf) {
1871
99
  // At beginning of PLT but not the IPLT, we have code to call the dynamic
1872
99
  // linker to resolve dynsyms at runtime. Write such code.
1873
99
  if (!IsIplt)
1874
87
    Target->writePltHeader(Buf);
1875
99
  size_t Off = HeaderSize;
1876
99
  // The IPlt is immediately after the Plt, account for this in RelOff
1877
99
  unsigned PltOff = getPltRelocOff();
1878
99
1879
146
  for (auto &I : Entries) {
1880
146
    const Symbol *B = I.first;
1881
146
    unsigned RelOff = I.second + PltOff;
1882
146
    uint64_t Got = B->getGotPltVA();
1883
146
    uint64_t Plt = this->getVA() + Off;
1884
146
    Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
1885
146
    Off += Target->PltEntrySize;
1886
146
  }
1887
99
}
1888
1889
146
template <class ELFT> void PltSection::addEntry(Symbol &Sym) {
1890
146
  Sym.PltIndex = Entries.size();
1891
146
  RelocationBaseSection *PltRelocSection = InX::RelaPlt;
1892
146
  if (IsIplt) {
1893
21
    PltRelocSection = InX::RelaIplt;
1894
21
    Sym.IsInIplt = true;
1895
21
  }
1896
146
  unsigned RelOff =
1897
146
      static_cast<RelocationSection<ELFT> *>(PltRelocSection)->getRelocOffset();
1898
146
  Entries.push_back(std::make_pair(&Sym, RelOff));
1899
146
}
void lld::elf::PltSection::addEntry<llvm::object::ELFType<(llvm::support::endianness)1, false> >(lld::elf::Symbol&)
Line
Count
Source
1889
35
template <class ELFT> void PltSection::addEntry(Symbol &Sym) {
1890
35
  Sym.PltIndex = Entries.size();
1891
35
  RelocationBaseSection *PltRelocSection = InX::RelaPlt;
1892
35
  if (IsIplt) {
1893
10
    PltRelocSection = InX::RelaIplt;
1894
10
    Sym.IsInIplt = true;
1895
10
  }
1896
35
  unsigned RelOff =
1897
35
      static_cast<RelocationSection<ELFT> *>(PltRelocSection)->getRelocOffset();
1898
35
  Entries.push_back(std::make_pair(&Sym, RelOff));
1899
35
}
void lld::elf::PltSection::addEntry<llvm::object::ELFType<(llvm::support::endianness)0, false> >(lld::elf::Symbol&)
Line
Count
Source
1889
3
template <class ELFT> void PltSection::addEntry(Symbol &Sym) {
1890
3
  Sym.PltIndex = Entries.size();
1891
3
  RelocationBaseSection *PltRelocSection = InX::RelaPlt;
1892
3
  if (IsIplt) {
1893
0
    PltRelocSection = InX::RelaIplt;
1894
0
    Sym.IsInIplt = true;
1895
0
  }
1896
3
  unsigned RelOff =
1897
3
      static_cast<RelocationSection<ELFT> *>(PltRelocSection)->getRelocOffset();
1898
3
  Entries.push_back(std::make_pair(&Sym, RelOff));
1899
3
}
void lld::elf::PltSection::addEntry<llvm::object::ELFType<(llvm::support::endianness)1, true> >(lld::elf::Symbol&)
Line
Count
Source
1889
106
template <class ELFT> void PltSection::addEntry(Symbol &Sym) {
1890
106
  Sym.PltIndex = Entries.size();
1891
106
  RelocationBaseSection *PltRelocSection = InX::RelaPlt;
1892
106
  if (IsIplt) {
1893
11
    PltRelocSection = InX::RelaIplt;
1894
11
    Sym.IsInIplt = true;
1895
11
  }
1896
106
  unsigned RelOff =
1897
106
      static_cast<RelocationSection<ELFT> *>(PltRelocSection)->getRelocOffset();
1898
106
  Entries.push_back(std::make_pair(&Sym, RelOff));
1899
106
}
void lld::elf::PltSection::addEntry<llvm::object::ELFType<(llvm::support::endianness)0, true> >(lld::elf::Symbol&)
Line
Count
Source
1889
2
template <class ELFT> void PltSection::addEntry(Symbol &Sym) {
1890
2
  Sym.PltIndex = Entries.size();
1891
2
  RelocationBaseSection *PltRelocSection = InX::RelaPlt;
1892
2
  if (IsIplt) {
1893
0
    PltRelocSection = InX::RelaIplt;
1894
0
    Sym.IsInIplt = true;
1895
0
  }
1896
2
  unsigned RelOff =
1897
2
      static_cast<RelocationSection<ELFT> *>(PltRelocSection)->getRelocOffset();
1898
2
  Entries.push_back(std::make_pair(&Sym, RelOff));
1899
2
}
1900
1901
381
size_t PltSection::getSize() const {
1902
381
  return HeaderSize + Entries.size() * Target->PltEntrySize;
1903
381
}
1904
1905
// Some architectures such as additional symbols in the PLT section. For
1906
// example ARM uses mapping symbols to aid disassembly
1907
99
void PltSection::addSymbols() {
1908
99
  // The PLT may have symbols defined for the Header, the IPLT has no header
1909
99
  if (!IsIplt)
1910
87
    Target->addPltHeaderSymbols(*this);
1911
99
  size_t Off = HeaderSize;
1912
245
  for (size_t I = 0; I < Entries.size(); 
++I146
) {
1913
146
    Target->addPltSymbols(*this, Off);
1914
146
    Off += Target->PltEntrySize;
1915
146
  }
1916
99
}
1917
1918
99
unsigned PltSection::getPltRelocOff() const {
1919
99
  return IsIplt ? 
InX::Plt->getSize()12
:
087
;
1920
99
}
1921
1922
// The string hash function for .gdb_index.
1923
0
static uint32_t computeGdbHash(StringRef S) {
1924
0
  uint32_t H = 0;
1925
0
  for (uint8_t C : S)
1926
0
    H = H * 67 + tolower(C) - 113;
1927
0
  return H;
1928
0
}
1929
1930
4
static std::vector<GdbIndexChunk::CuEntry> readCuList(DWARFContext &Dwarf) {
1931
4
  std::vector<GdbIndexChunk::CuEntry> Ret;
1932
4
  for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units())
1933
3
    Ret.push_back({Cu->getOffset(), Cu->getLength() + 4});
1934
4
  return Ret;
1935
4
}
1936
1937
static std::vector<GdbIndexChunk::AddressEntry>
1938
4
readAddressAreas(DWARFContext &Dwarf, InputSection *Sec) {
1939
4
  std::vector<GdbIndexChunk::AddressEntry> Ret;
1940
4
1941
4
  uint32_t CuIdx = 0;
1942
4
  for (std::unique_ptr<DWARFCompileUnit> &Cu : Dwarf.compile_units()) {
1943
3
    DWARFAddressRangesVector Ranges;
1944
3
    Cu->collectAddressRanges(Ranges);
1945
3
1946
3
    ArrayRef<InputSectionBase *> Sections = Sec->File->getSections();
1947
5
    for (DWARFAddressRange &R : Ranges) {
1948
5
      InputSectionBase *S = Sections[R.SectionIndex];
1949
5
      if (!S || S == &InputSection::Discarded || !S->Live)
1950
0
        continue;
1951
5
      // Range list with zero size has no effect.
1952
5
      if (R.LowPC == R.HighPC)
1953
1
        continue;
1954
4
      auto *IS = cast<InputSection>(S);
1955
4
      uint64_t Offset = IS->getOffsetInFile();
1956
4
      Ret.push_back({IS, R.LowPC - Offset, R.HighPC - Offset, CuIdx});
1957
4
    }
1958
3
    ++CuIdx;
1959
3
  }
1960
4
  return Ret;
1961
4
}
1962
1963
static std::vector<GdbIndexChunk::NameTypeEntry>
1964
4
readPubNamesAndTypes(DWARFContext &Dwarf) {
1965
4
  StringRef Sec1 = Dwarf.getDWARFObj().getGnuPubNamesSection();
1966
4
  StringRef Sec2 = Dwarf.getDWARFObj().getGnuPubTypesSection();
1967
4
1968
4
  std::vector<GdbIndexChunk::NameTypeEntry> Ret;
1969
8
  for (StringRef Sec : {Sec1, Sec2}) {
1970
8
    DWARFDebugPubTable Table(Sec, Config->IsLE, true);
1971
8
    for (const DWARFDebugPubTable::Set &Set : Table.getData()) {
1972
0
      for (const DWARFDebugPubTable::Entry &Ent : Set.Entries) {
1973
0
        CachedHashStringRef S(Ent.Name, computeGdbHash(Ent.Name));
1974
0
        Ret.push_back({S, Ent.Descriptor.toBits()});
1975
0
      }
1976
0
    }
1977
8
  }
1978
4
  return Ret;
1979
4
}
1980
1981
4
static std::vector<InputSection *> getDebugInfoSections() {
1982
4
  std::vector<InputSection *> Ret;
1983
4
  for (InputSectionBase *S : InputSections)
1984
39
    if (InputSection *IS = dyn_cast<InputSection>(S))
1985
39
      if (IS->Name == ".debug_info")
1986
4
        Ret.push_back(IS);
1987
4
  return Ret;
1988
4
}
1989
1990
4
void GdbIndexSection::fixCuIndex() {
1991
4
  uint32_t Idx = 0;
1992
4
  for (GdbIndexChunk &Chunk : Chunks) {
1993
4
    for (GdbIndexChunk::AddressEntry &Ent : Chunk.AddressAreas)
1994
4
      Ent.CuIndex += Idx;
1995
4
    Idx += Chunk.CompilationUnits.size();
1996
4
  }
1997
4
}
1998
1999
4
std::vector<std::vector<uint32_t>> GdbIndexSection::createCuVectors() {
2000
4
  std::vector<std::vector<uint32_t>> Ret;
2001
4
  uint32_t Idx = 0;
2002
4
  uint32_t Off = 0;
2003
4
2004
4
  for (GdbIndexChunk &Chunk : Chunks) {
2005
4
    for (GdbIndexChunk::NameTypeEntry &Ent : Chunk.NamesAndTypes) {
2006
0
      GdbSymbol *&Sym = Symbols[Ent.Name];
2007
0
      if (!Sym) {
2008
0
        Sym = make<GdbSymbol>(GdbSymbol{Ent.Name.hash(), Off, Ret.size()});
2009
0
        Off += Ent.Name.size() + 1;
2010
0
        Ret.push_back({});
2011
0
      }
2012
0
2013
0
      // gcc 5.4.1 produces a buggy .debug_gnu_pubnames that contains
2014
0
      // duplicate entries, so we want to dedup them.
2015
0
      std::vector<uint32_t> &Vec = Ret[Sym->CuVectorIndex];
2016
0
      uint32_t Val = (Ent.Type << 24) | Idx;
2017
0
      if (Vec.empty() || Vec.back() != Val)
2018
0
        Vec.push_back(Val);
2019
0
    }
2020
4
    Idx += Chunk.CompilationUnits.size();
2021
4
  }
2022
4
2023
4
  StringPoolSize = Off;
2024
4
  return Ret;
2025
4
}
2026
2027
4
template <class ELFT> GdbIndexSection *elf::createGdbIndex() {
2028
4
  // Gather debug info to create a .gdb_index section.
2029
4
  std::vector<InputSection *> Sections = getDebugInfoSections();
2030
4
  std::vector<GdbIndexChunk> Chunks(Sections.size());
2031
4
2032
4
  parallelForEachN(0, Chunks.size(), [&](size_t I) {
2033
4
    ObjFile<ELFT> *File = Sections[I]->getFile<ELFT>();
2034
4
    DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(File));
2035
4
2036
4
    Chunks[I].DebugInfoSec = Sections[I];
2037
4
    Chunks[I].CompilationUnits = readCuList(Dwarf);
2038
4
    Chunks[I].AddressAreas = readAddressAreas(Dwarf, Sections[I]);
2039
4
    Chunks[I].NamesAndTypes = readPubNamesAndTypes(Dwarf);
2040
4
  });
lld::elf::GdbIndexSection* lld::elf::createGdbIndex<llvm::object::ELFType<(llvm::support::endianness)1, false> >()::'lambda'(unsigned long)::operator()(unsigned long) const
Line
Count
Source
2032
1
  parallelForEachN(0, Chunks.size(), [&](size_t I) {
2033
1
    ObjFile<ELFT> *File = Sections[I]->getFile<ELFT>();
2034
1
    DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(File));
2035
1
2036
1
    Chunks[I].DebugInfoSec = Sections[I];
2037
1
    Chunks[I].CompilationUnits = readCuList(Dwarf);
2038
1
    Chunks[I].AddressAreas = readAddressAreas(Dwarf, Sections[I]);
2039
1
    Chunks[I].NamesAndTypes = readPubNamesAndTypes(Dwarf);
2040
1
  });
Unexecuted instantiation: lld::elf::GdbIndexSection* lld::elf::createGdbIndex<llvm::object::ELFType<(llvm::support::endianness)0, false> >()::'lambda'(unsigned long)::operator()(unsigned long) const
lld::elf::GdbIndexSection* lld::elf::createGdbIndex<llvm::object::ELFType<(llvm::support::endianness)1, true> >()::'lambda'(unsigned long)::operator()(unsigned long) const
Line
Count
Source
2032
3
  parallelForEachN(0, Chunks.size(), [&](size_t I) {
2033
3
    ObjFile<ELFT> *File = Sections[I]->getFile<ELFT>();
2034
3
    DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(File));
2035
3
2036
3
    Chunks[I].DebugInfoSec = Sections[I];
2037
3
    Chunks[I].CompilationUnits = readCuList(Dwarf);
2038
3
    Chunks[I].AddressAreas = readAddressAreas(Dwarf, Sections[I]);
2039
3
    Chunks[I].NamesAndTypes = readPubNamesAndTypes(Dwarf);
2040
3
  });
Unexecuted instantiation: lld::elf::GdbIndexSection* lld::elf::createGdbIndex<llvm::object::ELFType<(llvm::support::endianness)0, true> >()::'lambda'(unsigned long)::operator()(unsigned long) const
2041
4
2042
4
  // .debug_gnu_pub{names,types} are useless in executables.
2043
4
  // They are present in input object files solely for creating
2044
4
  // a .gdb_index. So we can remove it from the output.
2045
4
  for (InputSectionBase *S : InputSections)
2046
39
    if (S->Name == ".debug_gnu_pubnames" || S->Name == ".debug_gnu_pubtypes")
2047
0
      S->Live = false;
2048
4
2049
4
  // Create a .gdb_index and returns it.
2050
4
  return make<GdbIndexSection>(std::move(Chunks));
2051
4
}
lld::elf::GdbIndexSection* lld::elf::createGdbIndex<llvm::object::ELFType<(llvm::support::endianness)1, false> >()
Line
Count
Source
2027
1
template <class ELFT> GdbIndexSection *elf::createGdbIndex() {
2028
1
  // Gather debug info to create a .gdb_index section.
2029
1
  std::vector<InputSection *> Sections = getDebugInfoSections();
2030
1
  std::vector<GdbIndexChunk> Chunks(Sections.size());
2031
1
2032
1
  parallelForEachN(0, Chunks.size(), [&](size_t I) {
2033
1
    ObjFile<ELFT> *File = Sections[I]->getFile<ELFT>();
2034
1
    DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(File));
2035
1
2036
1
    Chunks[I].DebugInfoSec = Sections[I];
2037
1
    Chunks[I].CompilationUnits = readCuList(Dwarf);
2038
1
    Chunks[I].AddressAreas = readAddressAreas(Dwarf, Sections[I]);
2039
1
    Chunks[I].NamesAndTypes = readPubNamesAndTypes(Dwarf);
2040
1
  });
2041
1
2042
1
  // .debug_gnu_pub{names,types} are useless in executables.
2043
1
  // They are present in input object files solely for creating
2044
1
  // a .gdb_index. So we can remove it from the output.
2045
1
  for (InputSectionBase *S : InputSections)
2046
8
    if (S->Name == ".debug_gnu_pubnames" || S->Name == ".debug_gnu_pubtypes")
2047
0
      S->Live = false;
2048
1
2049
1
  // Create a .gdb_index and returns it.
2050
1
  return make<GdbIndexSection>(std::move(Chunks));
2051
1
}
Unexecuted instantiation: lld::elf::GdbIndexSection* lld::elf::createGdbIndex<llvm::object::ELFType<(llvm::support::endianness)0, false> >()
lld::elf::GdbIndexSection* lld::elf::createGdbIndex<llvm::object::ELFType<(llvm::support::endianness)1, true> >()
Line
Count
Source
2027
3
template <class ELFT> GdbIndexSection *elf::createGdbIndex() {
2028
3
  // Gather debug info to create a .gdb_index section.
2029
3
  std::vector<InputSection *> Sections = getDebugInfoSections();
2030
3
  std::vector<GdbIndexChunk> Chunks(Sections.size());
2031
3
2032
3
  parallelForEachN(0, Chunks.size(), [&](size_t I) {
2033
3
    ObjFile<ELFT> *File = Sections[I]->getFile<ELFT>();
2034
3
    DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(File));
2035
3
2036
3
    Chunks[I].DebugInfoSec = Sections[I];
2037
3
    Chunks[I].CompilationUnits = readCuList(Dwarf);
2038
3
    Chunks[I].AddressAreas = readAddressAreas(Dwarf, Sections[I]);
2039
3
    Chunks[I].NamesAndTypes = readPubNamesAndTypes(Dwarf);
2040
3
  });
2041
3
2042
3
  // .debug_gnu_pub{names,types} are useless in executables.
2043
3
  // They are present in input object files solely for creating
2044
3
  // a .gdb_index. So we can remove it from the output.
2045
3
  for (InputSectionBase *S : InputSections)
2046
31
    if (S->Name == ".debug_gnu_pubnames" || S->Name == ".debug_gnu_pubtypes")
2047
0
      S->Live = false;
2048
3
2049
3
  // Create a .gdb_index and returns it.
2050
3
  return make<GdbIndexSection>(std::move(Chunks));
2051
3
}
Unexecuted instantiation: lld::elf::GdbIndexSection* lld::elf::createGdbIndex<llvm::object::ELFType<(llvm::support::endianness)0, true> >()
2052
2053
4
static size_t getCuSize(ArrayRef<GdbIndexChunk> Arr) {
2054
4
  size_t Ret = 0;
2055
4
  for (const GdbIndexChunk &D : Arr)
2056
4
    Ret += D.CompilationUnits.size();
2057
4
  return Ret;
2058
4
}
2059
2060
4
static size_t getAddressAreaSize(ArrayRef<GdbIndexChunk> Arr) {
2061
4
  size_t Ret = 0;
2062
4
  for (const GdbIndexChunk &D : Arr)
2063
4
    Ret += D.AddressAreas.size();
2064
4
  return Ret;
2065
4
}
2066
2067
4
std::vector<GdbSymbol *> GdbIndexSection::createGdbSymtab() {
2068
4
  uint32_t Size = NextPowerOf2(Symbols.size() * 4 / 3);
2069
4
  if (Size < 1024)
2070
4
    Size = 1024;
2071
4
2072
4
  uint32_t Mask = Size - 1;
2073
4
  std::vector<GdbSymbol *> Ret(Size);
2074
4
2075
4
  for (auto &KV : Symbols) {
2076
0
    GdbSymbol *Sym = KV.second;
2077
0
    uint32_t I = Sym->NameHash & Mask;
2078
0
    uint32_t Step = ((Sym->NameHash * 17) & Mask) | 1;
2079
0
2080
0
    while (Ret[I])
2081
0
      I = (I + Step) & Mask;
2082
0
    Ret[I] = Sym;
2083
0
  }
2084
4
  return Ret;
2085
4
}
2086
2087
GdbIndexSection::GdbIndexSection(std::vector<GdbIndexChunk> &&C)
2088
4
    : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"), Chunks(std::move(C)) {