Coverage Report

Created: 2018-01-17 21:32

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/ELF/Writer.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- Writer.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
#include "Writer.h"
11
#include "AArch64ErrataFix.h"
12
#include "Config.h"
13
#include "Filesystem.h"
14
#include "LinkerScript.h"
15
#include "MapFile.h"
16
#include "OutputSections.h"
17
#include "Relocations.h"
18
#include "Strings.h"
19
#include "SymbolTable.h"
20
#include "Symbols.h"
21
#include "SyntheticSections.h"
22
#include "Target.h"
23
#include "lld/Common/Memory.h"
24
#include "lld/Common/Threads.h"
25
#include "llvm/ADT/StringMap.h"
26
#include "llvm/ADT/StringSwitch.h"
27
#include <climits>
28
29
using namespace llvm;
30
using namespace llvm::ELF;
31
using namespace llvm::object;
32
using namespace llvm::support;
33
using namespace llvm::support::endian;
34
35
using namespace lld;
36
using namespace lld::elf;
37
38
namespace {
39
// The writer writes a SymbolTable result to a file.
40
template <class ELFT> class Writer {
41
public:
42
936
  Writer() : Buffer(errorHandler().OutputBuffer) {}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::Writer()
Line
Count
Source
42
118
  Writer() : Buffer(errorHandler().OutputBuffer) {}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::Writer()
Line
Count
Source
42
52
  Writer() : Buffer(errorHandler().OutputBuffer) {}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::Writer()
Line
Count
Source
42
738
  Writer() : Buffer(errorHandler().OutputBuffer) {}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::Writer()
Line
Count
Source
42
28
  Writer() : Buffer(errorHandler().OutputBuffer) {}
43
  typedef typename ELFT::Shdr Elf_Shdr;
44
  typedef typename ELFT::Ehdr Elf_Ehdr;
45
  typedef typename ELFT::Phdr Elf_Phdr;
46
47
  void run();
48
49
private:
50
  void copyLocalSymbols();
51
  void addSectionSymbols();
52
  void forEachRelSec(std::function<void(InputSectionBase &)> Fn);
53
  void sortSections();
54
  void resolveShfLinkOrder();
55
  void sortInputSections();
56
  void finalizeSections();
57
  void setReservedSymbolSections();
58
59
  std::vector<PhdrEntry *> createPhdrs();
60
  void removeEmptyPTLoad();
61
  void addPtArmExid(std::vector<PhdrEntry *> &Phdrs);
62
  void assignFileOffsets();
63
  void assignFileOffsetsBinary();
64
  void setPhdrs();
65
  void fixSectionAlignments();
66
  void openFile();
67
  void writeTrapInstr();
68
  void writeHeader();
69
  void writeSections();
70
  void writeSectionsBinary();
71
  void writeBuildId();
72
73
  std::unique_ptr<FileOutputBuffer> &Buffer;
74
75
  void addRelIpltSymbols();
76
  void addStartEndSymbols();
77
  void addStartStopSymbols(OutputSection *Sec);
78
  uint64_t getEntryAddr();
79
80
  std::vector<PhdrEntry *> Phdrs;
81
82
  uint64_t FileSize;
83
  uint64_t SectionHeaderOff;
84
85
  bool HasGotBaseSym = false;
86
};
87
} // anonymous namespace
88
89
85.4k
StringRef elf::getOutputSectionName(InputSectionBase *S) {
90
85.4k
  // ".zdebug_" is a prefix for ZLIB-compressed sections.
91
85.4k
  // Because we decompressed input sections, we want to remove 'z'.
92
85.4k
  if (S->Name.startswith(".zdebug_"))
93
1
    return Saver.save("." + S->Name.substr(2));
94
85.4k
95
85.4k
  if (Config->Relocatable)
96
475
    return S->Name;
97
84.9k
98
84.9k
  // This is for --emit-relocs. If .text.foo is emitted as .text.bar, we want
99
84.9k
  // to emit .rela.text.foo as .rela.text.bar for consistency (this is not
100
84.9k
  // technically required, but not doing it is odd). This code guarantees that.
101
84.9k
  if ((S->Type == SHT_REL || 
S->Type == SHT_RELA84.5k
) &&
102
84.9k
      
!isa<SyntheticSection>(S)2.30k
) {
103
8
    OutputSection *Out =
104
8
        cast<InputSection>(S)->getRelocatedSection()->getOutputSection();
105
8
    if (S->Type == SHT_RELA)
106
7
      return Saver.save(".rela" + Out->Name);
107
1
    return Saver.save(".rel" + Out->Name);
108
1
  }
109
84.9k
110
84.9k
  for (StringRef V :
111
84.9k
       {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
112
84.9k
        ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
113
1.23M
        ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."}) {
114
1.23M
    StringRef Prefix = V.drop_back();
115
1.23M
    if (S->Name.startswith(V) || 
S->Name == Prefix1.23M
)
116
3.62k
      return Prefix;
117
1.23M
  }
118
84.9k
119
84.9k
  // CommonSection is identified as "COMMON" in linker scripts.
120
84.9k
  // By default, it should go to .bss section.
121
84.9k
  
if (81.3k
S->Name == "COMMON"81.3k
)
122
53
    return ".bss";
123
81.2k
124
81.2k
  return S->Name;
125
81.2k
}
126
127
936
static bool needsInterpSection() {
128
936
  return !SharedFiles.empty() && 
!Config->DynamicLinker.empty()130
&&
129
936
         
Script->needsInterpSection()5
;
130
936
}
131
132
936
template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
void lld::elf::writeResult<llvm::object::ELFType<(llvm::support::endianness)1, false> >()
Line
Count
Source
132
118
template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
void lld::elf::writeResult<llvm::object::ELFType<(llvm::support::endianness)0, false> >()
Line
Count
Source
132
52
template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
void lld::elf::writeResult<llvm::object::ELFType<(llvm::support::endianness)1, true> >()
Line
Count
Source
132
738
template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
void lld::elf::writeResult<llvm::object::ELFType<(llvm::support::endianness)0, true> >()
Line
Count
Source
132
28
template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
133
134
884
template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
135
4.61k
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
136
4.61k
    if (P->p_type != PT_LOAD)
137
2.50k
      return false;
138
2.10k
    if (!P->FirstSec)
139
12
      return true;
140
2.09k
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
141
2.09k
    return Size == 0;
142
2.09k
  });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::removeEmptyPTLoad()::'lambda'(lld::elf::PhdrEntry const*)::operator()(lld::elf::PhdrEntry const*) const
Line
Count
Source
135
675
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
136
675
    if (P->p_type != PT_LOAD)
137
379
      return false;
138
296
    if (!P->FirstSec)
139
3
      return true;
140
293
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
141
293
    return Size == 0;
142
293
  });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::removeEmptyPTLoad()::'lambda'(lld::elf::PhdrEntry const*)::operator()(lld::elf::PhdrEntry const*) const
Line
Count
Source
135
259
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
136
259
    if (P->p_type != PT_LOAD)
137
125
      return false;
138
134
    if (!P->FirstSec)
139
0
      return true;
140
134
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
141
134
    return Size == 0;
142
134
  });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::removeEmptyPTLoad()::'lambda'(lld::elf::PhdrEntry const*)::operator()(lld::elf::PhdrEntry const*) const
Line
Count
Source
135
3.51k
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
136
3.51k
    if (P->p_type != PT_LOAD)
137
1.92k
      return false;
138
1.59k
    if (!P->FirstSec)
139
9
      return true;
140
1.58k
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
141
1.58k
    return Size == 0;
142
1.58k
  });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::removeEmptyPTLoad()::'lambda'(lld::elf::PhdrEntry const*)::operator()(lld::elf::PhdrEntry const*) const
Line
Count
Source
135
161
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
136
161
    if (P->p_type != PT_LOAD)
137
83
      return false;
138
78
    if (!P->FirstSec)
139
0
      return true;
140
78
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
141
78
    return Size == 0;
142
78
  });
143
884
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::removeEmptyPTLoad()
Line
Count
Source
134
116
template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
135
116
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
136
116
    if (P->p_type != PT_LOAD)
137
116
      return false;
138
116
    if (!P->FirstSec)
139
116
      return true;
140
116
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
141
116
    return Size == 0;
142
116
  });
143
116
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::removeEmptyPTLoad()
Line
Count
Source
134
50
template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
135
50
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
136
50
    if (P->p_type != PT_LOAD)
137
50
      return false;
138
50
    if (!P->FirstSec)
139
50
      return true;
140
50
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
141
50
    return Size == 0;
142
50
  });
143
50
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::removeEmptyPTLoad()
Line
Count
Source
134
691
template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
135
691
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
136
691
    if (P->p_type != PT_LOAD)
137
691
      return false;
138
691
    if (!P->FirstSec)
139
691
      return true;
140
691
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
141
691
    return Size == 0;
142
691
  });
143
691
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::removeEmptyPTLoad()
Line
Count
Source
134
27
template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
135
27
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
136
27
    if (P->p_type != PT_LOAD)
137
27
      return false;
138
27
    if (!P->FirstSec)
139
27
      return true;
140
27
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
141
27
    return Size == 0;
142
27
  });
143
27
}
144
145
907
template <class ELFT> static void combineEhFrameSections() {
146
84.7k
  for (InputSectionBase *&S : InputSections) {
147
84.7k
    EhInputSection *ES = dyn_cast<EhInputSection>(S);
148
84.7k
    if (!ES || 
!ES->Live53
)
149
84.6k
      continue;
150
53
151
53
    InX::EhFrame->addSection<ELFT>(ES);
152
53
    S = nullptr;
153
53
  }
154
907
155
907
  std::vector<InputSectionBase *> &V = InputSections;
156
907
  V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
157
907
}
Writer.cpp:void combineEhFrameSections<llvm::object::ELFType<(llvm::support::endianness)1, false> >()
Line
Count
Source
145
117
template <class ELFT> static void combineEhFrameSections() {
146
2.68k
  for (InputSectionBase *&S : InputSections) {
147
2.68k
    EhInputSection *ES = dyn_cast<EhInputSection>(S);
148
2.68k
    if (!ES || 
!ES->Live2
)
149
2.68k
      continue;
150
2
151
2
    InX::EhFrame->addSection<ELFT>(ES);
152
2
    S = nullptr;
153
2
  }
154
117
155
117
  std::vector<InputSectionBase *> &V = InputSections;
156
117
  V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
157
117
}
Writer.cpp:void combineEhFrameSections<llvm::object::ELFType<(llvm::support::endianness)0, false> >()
Line
Count
Source
145
47
template <class ELFT> static void combineEhFrameSections() {
146
1.28k
  for (InputSectionBase *&S : InputSections) {
147
1.28k
    EhInputSection *ES = dyn_cast<EhInputSection>(S);
148
1.28k
    if (!ES || 
!ES->Live1
)
149
1.28k
      continue;
150
1
151
1
    InX::EhFrame->addSection<ELFT>(ES);
152
1
    S = nullptr;
153
1
  }
154
47
155
47
  std::vector<InputSectionBase *> &V = InputSections;
156
47
  V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
157
47
}
Writer.cpp:void combineEhFrameSections<llvm::object::ELFType<(llvm::support::endianness)1, true> >()
Line
Count
Source
145
715
template <class ELFT> static void combineEhFrameSections() {
146
80.0k
  for (InputSectionBase *&S : InputSections) {
147
80.0k
    EhInputSection *ES = dyn_cast<EhInputSection>(S);
148
80.0k
    if (!ES || 
!ES->Live47
)
149
79.9k
      continue;
150
47
151
47
    InX::EhFrame->addSection<ELFT>(ES);
152
47
    S = nullptr;
153
47
  }
154
715
155
715
  std::vector<InputSectionBase *> &V = InputSections;
156
715
  V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
157
715
}
Writer.cpp:void combineEhFrameSections<llvm::object::ELFType<(llvm::support::endianness)0, true> >()
Line
Count
Source
145
28
template <class ELFT> static void combineEhFrameSections() {
146
715
  for (InputSectionBase *&S : InputSections) {
147
715
    EhInputSection *ES = dyn_cast<EhInputSection>(S);
148
715
    if (!ES || 
!ES->Live3
)
149
712
      continue;
150
3
151
3
    InX::EhFrame->addSection<ELFT>(ES);
152
3
    S = nullptr;
153
3
  }
154
28
155
28
  std::vector<InputSectionBase *> &V = InputSections;
156
28
  V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
157
28
}
158
159
static Defined *addOptionalRegular(StringRef Name, SectionBase *Sec,
160
                                   uint64_t Val, uint8_t StOther = STV_HIDDEN,
161
144k
                                   uint8_t Binding = STB_GLOBAL) {
162
144k
  Symbol *S = Symtab->find(Name);
163
144k
  if (!S || 
S->isDefined()64
)
164
144k
    return nullptr;
165
61
  Symbol *Sym = Symtab->addRegular(Name, StOther, STT_NOTYPE, Val,
166
61
                                   /*Size=*/0, Binding, Sec,
167
61
                                   /*File=*/nullptr);
168
61
  return cast<Defined>(Sym);
169
61
}
170
171
// The linker is expected to define some symbols depending on
172
// the linking result. This function defines such symbols.
173
912
void elf::addReservedSymbols() {
174
912
  if (Config->EMachine == EM_MIPS) {
175
69
    // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
176
69
    // so that it points to an absolute address which by default is relative
177
69
    // to GOT. Default offset is 0x7ff0.
178
69
    // See "Global Data Symbols" in Chapter 6 in the following document:
179
69
    // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
180
69
    ElfSym::MipsGp = Symtab->addAbsolute("_gp", STV_HIDDEN, STB_GLOBAL);
181
69
182
69
    // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
183
69
    // start of function and 'gp' pointer into GOT.
184
69
    if (Symtab->find("_gp_disp"))
185
2
      ElfSym::MipsGpDisp =
186
2
          Symtab->addAbsolute("_gp_disp", STV_HIDDEN, STB_GLOBAL);
187
69
188
69
    // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
189
69
    // pointer. This symbol is used in the code generated by .cpload pseudo-op
190
69
    // in case of using -mno-shared option.
191
69
    // https://sourceware.org/ml/binutils/2004-12/msg00094.html
192
69
    if (Symtab->find("__gnu_local_gp"))
193
0
      ElfSym::MipsLocalGp =
194
0
          Symtab->addAbsolute("__gnu_local_gp", STV_HIDDEN, STB_GLOBAL);
195
69
  }
196
912
197
912
  ElfSym::GlobalOffsetTable = addOptionalRegular(
198
912
      "_GLOBAL_OFFSET_TABLE_", Out::ElfHeader, Target->GotBaseSymOff);
199
912
200
912
  // __ehdr_start is the location of ELF file headers. Note that we define
201
912
  // this symbol unconditionally even when using a linker script, which
202
912
  // differs from the behavior implemented by GNU linker which only define
203
912
  // this symbol if ELF headers are in the memory mapped segment.
204
912
  // __executable_start is not documented, but the expectation of at
205
912
  // least the android libc is that it points to the elf header too.
206
912
  // __dso_handle symbol is passed to cxa_finalize as a marker to identify
207
912
  // each DSO. The address of the symbol doesn't matter as long as they are
208
912
  // different in different DSOs, so we chose the start address of the DSO.
209
912
  for (const char *Name :
210
912
       {"__ehdr_start", "__executable_start", "__dso_handle"})
211
2.73k
    addOptionalRegular(Name, Out::ElfHeader, 0, STV_HIDDEN);
212
912
213
912
  // If linker script do layout we do not need to create any standart symbols.
214
912
  if (Script->HasSectionsCommand)
215
182
    return;
216
730
217
5.11k
  
auto Add = [](StringRef S, int64_t Pos) 730
{
218
5.11k
    return addOptionalRegular(S, Out::ElfHeader, Pos, STV_DEFAULT);
219
5.11k
  };
220
730
221
730
  ElfSym::Bss = Add("__bss_start", 0);
222
730
  ElfSym::End1 = Add("end", -1);
223
730
  ElfSym::End2 = Add("_end", -1);
224
730
  ElfSym::Etext1 = Add("etext", -1);
225
730
  ElfSym::Etext2 = Add("_etext", -1);
226
730
  ElfSym::Edata1 = Add("edata", -1);
227
730
  ElfSym::Edata2 = Add("_edata", -1);
228
730
}
229
230
10.5k
static OutputSection *findSection(StringRef Name) {
231
10.5k
  for (BaseCommand *Base : Script->SectionCommands)
232
936k
    if (auto *Sec = dyn_cast<OutputSection>(Base))
233
935k
      if (Sec->Name == Name)
234
477
        return Sec;
235
10.5k
  
return nullptr10.0k
;
236
10.5k
}
237
238
// Initialize Out members.
239
936
template <class ELFT> static void createSyntheticSections() {
240
936
  // Initialize all pointers with NULL. This is needed because
241
936
  // you can call lld::elf::main more than once as a library.
242
936
  memset(&Out::First, 0, sizeof(Out));
243
936
244
16.1k
  auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
Writer.cpp:void createSyntheticSections<llvm::object::ELFType<(llvm::support::endianness)1, false> >()::'lambda'(lld::elf::InputSectionBase*)::operator()(lld::elf::InputSectionBase*) const
Line
Count
Source
244
2.12k
  auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
Writer.cpp:void createSyntheticSections<llvm::object::ELFType<(llvm::support::endianness)0, false> >()::'lambda'(lld::elf::InputSectionBase*)::operator()(lld::elf::InputSectionBase*) const
Line
Count
Source
244
974
  auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
Writer.cpp:void createSyntheticSections<llvm::object::ELFType<(llvm::support::endianness)1, true> >()::'lambda'(lld::elf::InputSectionBase*)::operator()(lld::elf::InputSectionBase*) const
Line
Count
Source
244
12.5k
  auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
Writer.cpp:void createSyntheticSections<llvm::object::ELFType<(llvm::support::endianness)0, true> >()::'lambda'(lld::elf::InputSectionBase*)::operator()(lld::elf::InputSectionBase*) const
Line
Count
Source
244
534
  auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
245
936
246
936
  InX::DynStrTab = make<StringTableSection>(".dynstr", true);
247
936
  InX::Dynamic = make<DynamicSection<ELFT>>();
248
936
  if (Config->AndroidPackDynRelocs) {
249
2
    InX::RelaDyn = make<AndroidPackedRelocationSection<ELFT>>(
250
2
        Config->IsRela ? 
".rela.dyn"1
:
".rel.dyn"1
);
251
934
  } else {
252
934
    InX::RelaDyn = make<RelocationSection<ELFT>>(
253
934
        Config->IsRela ? 
".rela.dyn"766
:
".rel.dyn"168
, Config->ZCombreloc);
254
934
  }
255
936
  InX::ShStrTab = make<StringTableSection>(".shstrtab", false);
256
936
257
936
  Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
258
936
  Out::ProgramHeaders->Alignment = Config->Wordsize;
259
936
260
936
  if (needsInterpSection()) {
261
4
    InX::Interp = createInterpSection();
262
4
    Add(InX::Interp);
263
932
  } else {
264
932
    InX::Interp = nullptr;
265
932
  }
266
936
267
936
  if (Config->Strip != StripPolicy::All) {
268
933
    InX::StrTab = make<StringTableSection>(".strtab", false);
269
933
    InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab);
270
933
  }
271
936
272
936
  if (Config->BuildId != BuildIdKind::None) {
273
6
    InX::BuildId = make<BuildIdSection>();
274
6
    Add(InX::BuildId);
275
6
  }
276
936
277
936
  InX::Bss = make<BssSection>(".bss", 0, 1);
278
936
  Add(InX::Bss);
279
936
280
936
  // If there is a SECTIONS command and a .data.rel.ro section name use name
281
936
  // .data.rel.ro.bss so that we match in the .data.rel.ro output section.
282
936
  // This makes sure our relro is contiguous.
283
936
  bool HasDataRelRo =
284
936
      Script->HasSectionsCommand && 
findSection(".data.rel.ro")182
;
285
936
  InX::BssRelRo = make<BssSection>(
286
936
      HasDataRelRo ? 
".data.rel.ro.bss"5
:
".bss.rel.ro"931
, 0, 1);
287
936
  Add(InX::BssRelRo);
288
936
289
936
  // Add MIPS-specific sections.
290
936
  if (Config->EMachine == EM_MIPS) {
291
74
    if (!Config->Shared && 
Config->HasDynSymTab44
) {
292
10
      InX::MipsRldMap = make<MipsRldMapSection>();
293
10
      Add(InX::MipsRldMap);
294
10
    }
295
74
    if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
296
73
      Add(Sec);
297
74
    if (auto *Sec = MipsOptionsSection<ELFT>::create())
298
19
      Add(Sec);
299
74
    if (auto *Sec = MipsReginfoSection<ELFT>::create())
300
54
      Add(Sec);
301
74
  }
302
936
303
936
  if (Config->HasDynSymTab) {
304
488
    InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab);
305
488
    Add(InX::DynSymTab);
306
488
307
488
    In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
308
488
    Add(In<ELFT>::VerSym);
309
488
310
488
    if (!Config->VersionDefinitions.empty()) {
311
23
      In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
312
23
      Add(In<ELFT>::VerDef);
313
23
    }
314
488
315
488
    In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
316
488
    Add(In<ELFT>::VerNeed);
317
488
318
488
    if (Config->GnuHash) {
319
375
      InX::GnuHashTab = make<GnuHashTableSection>();
320
375
      Add(InX::GnuHashTab);
321
375
    }
322
488
323
488
    if (Config->SysvHash) {
324
484
      InX::HashTab = make<HashTableSection>();
325
484
      Add(InX::HashTab);
326
484
    }
327
488
328
488
    Add(InX::Dynamic);
329
488
    Add(InX::DynStrTab);
330
488
    Add(InX::RelaDyn);
331
488
  }
332
936
333
936
  // Add .got. MIPS' .got is so different from the other archs,
334
936
  // it has its own class.
335
936
  if (Config->EMachine == EM_MIPS) {
336
74
    InX::MipsGot = make<MipsGotSection>();
337
74
    Add(InX::MipsGot);
338
862
  } else {
339
862
    InX::Got = make<GotSection>();
340
862
    Add(InX::Got);
341
862
  }
342
936
343
936
  InX::GotPlt = make<GotPltSection>();
344
936
  Add(InX::GotPlt);
345
936
  InX::IgotPlt = make<IgotPltSection>();
346
936
  Add(InX::IgotPlt);
347
936
348
936
  if (Config->GdbIndex) {
349
4
    InX::GdbIndex = createGdbIndex<ELFT>();
350
4
    Add(InX::GdbIndex);
351
4
  }
352
936
353
936
  // We always need to add rel[a].plt to output if it has entries.
354
936
  // Even for static linking it can contain R_[*]_IRELATIVE relocations.
355
936
  InX::RelaPlt = make<RelocationSection<ELFT>>(
356
936
      Config->IsRela ? 
".rela.plt"767
:
".rel.plt"169
, false /*Sort*/);
357
936
  Add(InX::RelaPlt);
358
936
359
936
  // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
360
936
  // that the IRelative relocations are processed last by the dynamic loader.
361
936
  // We cannot place the iplt section in .rel.dyn when Android relocation
362
936
  // packing is enabled because that would cause a section type mismatch.
363
936
  // However, because the Android dynamic loader reads .rel.plt after .rel.dyn,
364
936
  // we can get the desired behaviour by placing the iplt section in .rel.plt.
365
936
  InX::RelaIplt = make<RelocationSection<ELFT>>(
366
936
      (Config->EMachine == EM_ARM && 
!Config->AndroidPackDynRelocs58
)
367
936
          ? 
".rel.dyn"57
368
936
          : 
InX::RelaPlt->Name879
,
369
936
      false /*Sort*/);
370
936
  Add(InX::RelaIplt);
371
936
372
936
  InX::Plt = make<PltSection>(false);
373
936
  Add(InX::Plt);
374
936
  InX::Iplt = make<PltSection>(true);
375
936
  Add(InX::Iplt);
376
936
377
936
  if (!Config->Relocatable) {
378
907
    if (Config->EhFrameHdr) {
379
8
      InX::EhFrameHdr = make<EhFrameHeader>();
380
8
      Add(InX::EhFrameHdr);
381
8
    }
382
907
    InX::EhFrame = make<EhFrameSection>();
383
907
    Add(InX::EhFrame);
384
907
  }
385
936
386
936
  if (InX::SymTab)
387
933
    Add(InX::SymTab);
388
936
  Add(InX::ShStrTab);
389
936
  if (InX::StrTab)
390
933
    Add(InX::StrTab);
391
936
392
936
  if (Config->EMachine == EM_ARM && 
!Config->Relocatable58
)
393
57
    // Add a sentinel to terminate .ARM.exidx. It helps an unwinder
394
57
    // to find the exact address range of the last entry.
395
57
    Add(make<ARMExidxSentinelSection>());
396
936
}
Writer.cpp:void createSyntheticSections<llvm::object::ELFType<(llvm::support::endianness)1, false> >()
Line
Count
Source
239
118
template <class ELFT> static void createSyntheticSections() {
240
118
  // Initialize all pointers with NULL. This is needed because
241
118
  // you can call lld::elf::main more than once as a library.
242
118
  memset(&Out::First, 0, sizeof(Out));
243
118
244
118
  auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
245
118
246
118
  InX::DynStrTab = make<StringTableSection>(".dynstr", true);
247
118
  InX::Dynamic = make<DynamicSection<ELFT>>();
248
118
  if (Config->AndroidPackDynRelocs) {
249
1
    InX::RelaDyn = make<AndroidPackedRelocationSection<ELFT>>(
250
1
        Config->IsRela ? 
".rela.dyn"0
: ".rel.dyn");
251
117
  } else {
252
117
    InX::RelaDyn = make<RelocationSection<ELFT>>(
253
117
        Config->IsRela ? 
".rela.dyn"1
:
".rel.dyn"116
, Config->ZCombreloc);
254
117
  }
255
118
  InX::ShStrTab = make<StringTableSection>(".shstrtab", false);
256
118
257
118
  Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
258
118
  Out::ProgramHeaders->Alignment = Config->Wordsize;
259
118
260
118
  if (needsInterpSection()) {
261
1
    InX::Interp = createInterpSection();
262
1
    Add(InX::Interp);
263
117
  } else {
264
117
    InX::Interp = nullptr;
265
117
  }
266
118
267
118
  if (Config->Strip != StripPolicy::All) {
268
118
    InX::StrTab = make<StringTableSection>(".strtab", false);
269
118
    InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab);
270
118
  }
271
118
272
118
  if (Config->BuildId != BuildIdKind::None) {
273
0
    InX::BuildId = make<BuildIdSection>();
274
0
    Add(InX::BuildId);
275
0
  }
276
118
277
118
  InX::Bss = make<BssSection>(".bss", 0, 1);
278
118
  Add(InX::Bss);
279
118
280
118
  // If there is a SECTIONS command and a .data.rel.ro section name use name
281
118
  // .data.rel.ro.bss so that we match in the .data.rel.ro output section.
282
118
  // This makes sure our relro is contiguous.
283
118
  bool HasDataRelRo =
284
118
      Script->HasSectionsCommand && 
findSection(".data.rel.ro")14
;
285
118
  InX::BssRelRo = make<BssSection>(
286
118
      HasDataRelRo ? 
".data.rel.ro.bss"0
: ".bss.rel.ro", 0, 1);
287
118
  Add(InX::BssRelRo);
288
118
289
118
  // Add MIPS-specific sections.
290
118
  if (Config->EMachine == EM_MIPS) {
291
4
    if (!Config->Shared && 
Config->HasDynSymTab3
) {
292
1
      InX::MipsRldMap = make<MipsRldMapSection>();
293
1
      Add(InX::MipsRldMap);
294
1
    }
295
4
    if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
296
4
      Add(Sec);
297
4
    if (auto *Sec = MipsOptionsSection<ELFT>::create())
298
0
      Add(Sec);
299
4
    if (auto *Sec = MipsReginfoSection<ELFT>::create())
300
4
      Add(Sec);
301
4
  }
302
118
303
118
  if (Config->HasDynSymTab) {
304
69
    InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab);
305
69
    Add(InX::DynSymTab);
306
69
307
69
    In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
308
69
    Add(In<ELFT>::VerSym);
309
69
310
69
    if (!Config->VersionDefinitions.empty()) {
311
0
      In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
312
0
      Add(In<ELFT>::VerDef);
313
0
    }
314
69
315
69
    In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
316
69
    Add(In<ELFT>::VerNeed);
317
69
318
69
    if (Config->GnuHash) {
319
46
      InX::GnuHashTab = make<GnuHashTableSection>();
320
46
      Add(InX::GnuHashTab);
321
46
    }
322
69
323
69
    if (Config->SysvHash) {
324
67
      InX::HashTab = make<HashTableSection>();
325
67
      Add(InX::HashTab);
326
67
    }
327
69
328
69
    Add(InX::Dynamic);
329
69
    Add(InX::DynStrTab);
330
69
    Add(InX::RelaDyn);
331
69
  }
332
118
333
118
  // Add .got. MIPS' .got is so different from the other archs,
334
118
  // it has its own class.
335
118
  if (Config->EMachine == EM_MIPS) {
336
4
    InX::MipsGot = make<MipsGotSection>();
337
4
    Add(InX::MipsGot);
338
114
  } else {
339
114
    InX::Got = make<GotSection>();
340
114
    Add(InX::Got);
341
114
  }
342
118
343
118
  InX::GotPlt = make<GotPltSection>();
344
118
  Add(InX::GotPlt);
345
118
  InX::IgotPlt = make<IgotPltSection>();
346
118
  Add(InX::IgotPlt);
347
118
348
118
  if (Config->GdbIndex) {
349
1
    InX::GdbIndex = createGdbIndex<ELFT>();
350
1
    Add(InX::GdbIndex);
351
1
  }
352
118
353
118
  // We always need to add rel[a].plt to output if it has entries.
354
118
  // Even for static linking it can contain R_[*]_IRELATIVE relocations.
355
118
  InX::RelaPlt = make<RelocationSection<ELFT>>(
356
118
      Config->IsRela ? 
".rela.plt"1
:
".rel.plt"117
, false /*Sort*/);
357
118
  Add(InX::RelaPlt);
358
118
359
118
  // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
360
118
  // that the IRelative relocations are processed last by the dynamic loader.
361
118
  // We cannot place the iplt section in .rel.dyn when Android relocation
362
118
  // packing is enabled because that would cause a section type mismatch.
363
118
  // However, because the Android dynamic loader reads .rel.plt after .rel.dyn,
364
118
  // we can get the desired behaviour by placing the iplt section in .rel.plt.
365
118
  InX::RelaIplt = make<RelocationSection<ELFT>>(
366
118
      (Config->EMachine == EM_ARM && 
!Config->AndroidPackDynRelocs58
)
367
118
          ? 
".rel.dyn"57
368
118
          : 
InX::RelaPlt->Name61
,
369
118
      false /*Sort*/);
370
118
  Add(InX::RelaIplt);
371
118
372
118
  InX::Plt = make<PltSection>(false);
373
118
  Add(InX::Plt);
374
118
  InX::Iplt = make<PltSection>(true);
375
118
  Add(InX::Iplt);
376
118
377
118
  if (!Config->Relocatable) {
378
117
    if (Config->EhFrameHdr) {
379
0
      InX::EhFrameHdr = make<EhFrameHeader>();
380
0
      Add(InX::EhFrameHdr);
381
0
    }
382
117
    InX::EhFrame = make<EhFrameSection>();
383
117
    Add(InX::EhFrame);
384
117
  }
385
118
386
118
  if (InX::SymTab)
387
118
    Add(InX::SymTab);
388
118
  Add(InX::ShStrTab);
389
118
  if (InX::StrTab)
390
118
    Add(InX::StrTab);
391
118
392
118
  if (Config->EMachine == EM_ARM && 
!Config->Relocatable58
)
393
57
    // Add a sentinel to terminate .ARM.exidx. It helps an unwinder
394
57
    // to find the exact address range of the last entry.
395
57
    Add(make<ARMExidxSentinelSection>());
396
118
}
Writer.cpp:void createSyntheticSections<llvm::object::ELFType<(llvm::support::endianness)0, false> >()
Line
Count
Source
239
52
template <class ELFT> static void createSyntheticSections() {
240
52
  // Initialize all pointers with NULL. This is needed because
241
52
  // you can call lld::elf::main more than once as a library.
242
52
  memset(&Out::First, 0, sizeof(Out));
243
52
244
52
  auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
245
52
246
52
  InX::DynStrTab = make<StringTableSection>(".dynstr", true);
247
52
  InX::Dynamic = make<DynamicSection<ELFT>>();
248
52
  if (Config->AndroidPackDynRelocs) {
249
0
    InX::RelaDyn = make<AndroidPackedRelocationSection<ELFT>>(
250
0
        Config->IsRela ? ".rela.dyn" : ".rel.dyn");
251
52
  } else {
252
52
    InX::RelaDyn = make<RelocationSection<ELFT>>(
253
52
        Config->IsRela ? 
".rela.dyn"0
: ".rel.dyn", Config->ZCombreloc);
254
52
  }
255
52
  InX::ShStrTab = make<StringTableSection>(".shstrtab", false);
256
52
257
52
  Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
258
52
  Out::ProgramHeaders->Alignment = Config->Wordsize;
259
52
260
52
  if (needsInterpSection()) {
261
0
    InX::Interp = createInterpSection();
262
0
    Add(InX::Interp);
263
52
  } else {
264
52
    InX::Interp = nullptr;
265
52
  }
266
52
267
52
  if (Config->Strip != StripPolicy::All) {
268
52
    InX::StrTab = make<StringTableSection>(".strtab", false);
269
52
    InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab);
270
52
  }
271
52
272
52
  if (Config->BuildId != BuildIdKind::None) {
273
0
    InX::BuildId = make<BuildIdSection>();
274
0
    Add(InX::BuildId);
275
0
  }
276
52
277
52
  InX::Bss = make<BssSection>(".bss", 0, 1);
278
52
  Add(InX::Bss);
279
52
280
52
  // If there is a SECTIONS command and a .data.rel.ro section name use name
281
52
  // .data.rel.ro.bss so that we match in the .data.rel.ro output section.
282
52
  // This makes sure our relro is contiguous.
283
52
  bool HasDataRelRo =
284
52
      Script->HasSectionsCommand && 
findSection(".data.rel.ro")3
;
285
52
  InX::BssRelRo = make<BssSection>(
286
52
      HasDataRelRo ? 
".data.rel.ro.bss"0
: ".bss.rel.ro", 0, 1);
287
52
  Add(InX::BssRelRo);
288
52
289
52
  // Add MIPS-specific sections.
290
52
  if (Config->EMachine == EM_MIPS) {
291
51
    if (!Config->Shared && 
Config->HasDynSymTab30
) {
292
6
      InX::MipsRldMap = make<MipsRldMapSection>();
293
6
      Add(InX::MipsRldMap);
294
6
    }
295
51
    if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
296
50
      Add(Sec);
297
51
    if (auto *Sec = MipsOptionsSection<ELFT>::create())
298
0
      Add(Sec);
299
51
    if (auto *Sec = MipsReginfoSection<ELFT>::create())
300
50
      Add(Sec);
301
51
  }
302
52
303
52
  if (Config->HasDynSymTab) {
304
28
    InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab);
305
28
    Add(InX::DynSymTab);
306
28
307
28
    In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
308
28
    Add(In<ELFT>::VerSym);
309
28
310
28
    if (!Config->VersionDefinitions.empty()) {
311
0
      In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
312
0
      Add(In<ELFT>::VerDef);
313
0
    }
314
28
315
28
    In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
316
28
    Add(In<ELFT>::VerNeed);
317
28
318
28
    if (Config->GnuHash) {
319
0
      InX::GnuHashTab = make<GnuHashTableSection>();
320
0
      Add(InX::GnuHashTab);
321
0
    }
322
28
323
28
    if (Config->SysvHash) {
324
28
      InX::HashTab = make<HashTableSection>();
325
28
      Add(InX::HashTab);
326
28
    }
327
28
328
28
    Add(InX::Dynamic);
329
28
    Add(InX::DynStrTab);
330
28
    Add(InX::RelaDyn);
331
28
  }
332
52
333
52
  // Add .got. MIPS' .got is so different from the other archs,
334
52
  // it has its own class.
335
52
  if (Config->EMachine == EM_MIPS) {
336
51
    InX::MipsGot = make<MipsGotSection>();
337
51
    Add(InX::MipsGot);
338
51
  } else {
339
1
    InX::Got = make<GotSection>();
340
1
    Add(InX::Got);
341
1
  }
342
52
343
52
  InX::GotPlt = make<GotPltSection>();
344
52
  Add(InX::GotPlt);
345
52
  InX::IgotPlt = make<IgotPltSection>();
346
52
  Add(InX::IgotPlt);
347
52
348
52
  if (Config->GdbIndex) {
349
0
    InX::GdbIndex = createGdbIndex<ELFT>();
350
0
    Add(InX::GdbIndex);
351
0
  }
352
52
353
52
  // We always need to add rel[a].plt to output if it has entries.
354
52
  // Even for static linking it can contain R_[*]_IRELATIVE relocations.
355
52
  InX::RelaPlt = make<RelocationSection<ELFT>>(
356
52
      Config->IsRela ? 
".rela.plt"0
: ".rel.plt", false /*Sort*/);
357
52
  Add(InX::RelaPlt);
358
52
359
52
  // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
360
52
  // that the IRelative relocations are processed last by the dynamic loader.
361
52
  // We cannot place the iplt section in .rel.dyn when Android relocation
362
52
  // packing is enabled because that would cause a section type mismatch.
363
52
  // However, because the Android dynamic loader reads .rel.plt after .rel.dyn,
364
52
  // we can get the desired behaviour by placing the iplt section in .rel.plt.
365
52
  InX::RelaIplt = make<RelocationSection<ELFT>>(
366
52
      (Config->EMachine == EM_ARM && 
!Config->AndroidPackDynRelocs0
)
367
52
          ? 
".rel.dyn"0
368
52
          : InX::RelaPlt->Name,
369
52
      false /*Sort*/);
370
52
  Add(InX::RelaIplt);
371
52
372
52
  InX::Plt = make<PltSection>(false);
373
52
  Add(InX::Plt);
374
52
  InX::Iplt = make<PltSection>(true);
375
52
  Add(InX::Iplt);
376
52
377
52
  if (!Config->Relocatable) {
378
47
    if (Config->EhFrameHdr) {
379
1
      InX::EhFrameHdr = make<EhFrameHeader>();
380
1
      Add(InX::EhFrameHdr);
381
1
    }
382
47
    InX::EhFrame = make<EhFrameSection>();
383
47
    Add(InX::EhFrame);
384
47
  }
385
52
386
52
  if (InX::SymTab)
387
52
    Add(InX::SymTab);
388
52
  Add(InX::ShStrTab);
389
52
  if (InX::StrTab)
390
52
    Add(InX::StrTab);
391
52
392
52
  if (Config->EMachine == EM_ARM && 
!Config->Relocatable0
)
393
0
    // Add a sentinel to terminate .ARM.exidx. It helps an unwinder
394
0
    // to find the exact address range of the last entry.
395
0
    Add(make<ARMExidxSentinelSection>());
396
52
}
Writer.cpp:void createSyntheticSections<llvm::object::ELFType<(llvm::support::endianness)1, true> >()
Line
Count
Source
239
738
template <class ELFT> static void createSyntheticSections() {
240
738
  // Initialize all pointers with NULL. This is needed because
241
738
  // you can call lld::elf::main more than once as a library.
242
738
  memset(&Out::First, 0, sizeof(Out));
243
738
244
738
  auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
245
738
246
738
  InX::DynStrTab = make<StringTableSection>(".dynstr", true);
247
738
  InX::Dynamic = make<DynamicSection<ELFT>>();
248
738
  if (Config->AndroidPackDynRelocs) {
249
1
    InX::RelaDyn = make<AndroidPackedRelocationSection<ELFT>>(
250
1
        Config->IsRela ? ".rela.dyn" : 
".rel.dyn"0
);
251
737
  } else {
252
737
    InX::RelaDyn = make<RelocationSection<ELFT>>(
253
737
        Config->IsRela ? ".rela.dyn" : 
".rel.dyn"0
, Config->ZCombreloc);
254
737
  }
255
738
  InX::ShStrTab = make<StringTableSection>(".shstrtab", false);
256
738
257
738
  Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
258
738
  Out::ProgramHeaders->Alignment = Config->Wordsize;
259
738
260
738
  if (needsInterpSection()) {
261
2
    InX::Interp = createInterpSection();
262
2
    Add(InX::Interp);
263
736
  } else {
264
736
    InX::Interp = nullptr;
265
736
  }
266
738
267
738
  if (Config->Strip != StripPolicy::All) {
268
735
    InX::StrTab = make<StringTableSection>(".strtab", false);
269
735
    InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab);
270
735
  }
271
738
272
738
  if (Config->BuildId != BuildIdKind::None) {
273
6
    InX::BuildId = make<BuildIdSection>();
274
6
    Add(InX::BuildId);
275
6
  }
276
738
277
738
  InX::Bss = make<BssSection>(".bss", 0, 1);
278
738
  Add(InX::Bss);
279
738
280
738
  // If there is a SECTIONS command and a .data.rel.ro section name use name
281
738
  // .data.rel.ro.bss so that we match in the .data.rel.ro output section.
282
738
  // This makes sure our relro is contiguous.
283
738
  bool HasDataRelRo =
284
738
      Script->HasSectionsCommand && 
findSection(".data.rel.ro")163
;
285
738
  InX::BssRelRo = make<BssSection>(
286
738
      HasDataRelRo ? 
".data.rel.ro.bss"5
:
".bss.rel.ro"733
, 0, 1);
287
738
  Add(InX::BssRelRo);
288
738
289
738
  // Add MIPS-specific sections.
290
738
  if (Config->EMachine == EM_MIPS) {
291
0
    if (!Config->Shared && Config->HasDynSymTab) {
292
0
      InX::MipsRldMap = make<MipsRldMapSection>();
293
0
      Add(InX::MipsRldMap);
294
0
    }
295
0
    if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
296
0
      Add(Sec);
297
0
    if (auto *Sec = MipsOptionsSection<ELFT>::create())
298
0
      Add(Sec);
299
0
    if (auto *Sec = MipsReginfoSection<ELFT>::create())
300
0
      Add(Sec);
301
0
  }
302
738
303
738
  if (Config->HasDynSymTab) {
304
374
    InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab);
305
374
    Add(InX::DynSymTab);
306
374
307
374
    In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
308
374
    Add(In<ELFT>::VerSym);
309
374
310
374
    if (!Config->VersionDefinitions.empty()) {
311
23
      In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
312
23
      Add(In<ELFT>::VerDef);
313
23
    }
314
374
315
374
    In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
316
374
    Add(In<ELFT>::VerNeed);
317
374
318
374
    if (Config->GnuHash) {
319
323
      InX::GnuHashTab = make<GnuHashTableSection>();
320
323
      Add(InX::GnuHashTab);
321
323
    }
322
374
323
374
    if (Config->SysvHash) {
324
372
      InX::HashTab = make<HashTableSection>();
325
372
      Add(InX::HashTab);
326
372
    }
327
374
328
374
    Add(InX::Dynamic);
329
374
    Add(InX::DynStrTab);
330
374
    Add(InX::RelaDyn);
331
374
  }
332
738
333
738
  // Add .got. MIPS' .got is so different from the other archs,
334
738
  // it has its own class.
335
738
  if (Config->EMachine == EM_MIPS) {
336
0
    InX::MipsGot = make<MipsGotSection>();
337
0
    Add(InX::MipsGot);
338
738
  } else {
339
738
    InX::Got = make<GotSection>();
340
738
    Add(InX::Got);
341
738
  }
342
738
343
738
  InX::GotPlt = make<GotPltSection>();
344
738
  Add(InX::GotPlt);
345
738
  InX::IgotPlt = make<IgotPltSection>();
346
738
  Add(InX::IgotPlt);
347
738
348
738
  if (Config->GdbIndex) {
349
3
    InX::GdbIndex = createGdbIndex<ELFT>();
350
3
    Add(InX::GdbIndex);
351
3
  }
352
738
353
738
  // We always need to add rel[a].plt to output if it has entries.
354
738
  // Even for static linking it can contain R_[*]_IRELATIVE relocations.
355
738
  InX::RelaPlt = make<RelocationSection<ELFT>>(
356
738
      Config->IsRela ? ".rela.plt" : 
".rel.plt"0
, false /*Sort*/);
357
738
  Add(InX::RelaPlt);
358
738
359
738
  // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
360
738
  // that the IRelative relocations are processed last by the dynamic loader.
361
738
  // We cannot place the iplt section in .rel.dyn when Android relocation
362
738
  // packing is enabled because that would cause a section type mismatch.
363
738
  // However, because the Android dynamic loader reads .rel.plt after .rel.dyn,
364
738
  // we can get the desired behaviour by placing the iplt section in .rel.plt.
365
738
  InX::RelaIplt = make<RelocationSection<ELFT>>(
366
738
      (Config->EMachine == EM_ARM && 
!Config->AndroidPackDynRelocs0
)
367
738
          ? 
".rel.dyn"0
368
738
          : InX::RelaPlt->Name,
369
738
      false /*Sort*/);
370
738
  Add(InX::RelaIplt);
371
738
372
738
  InX::Plt = make<PltSection>(false);
373
738
  Add(InX::Plt);
374
738
  InX::Iplt = make<PltSection>(true);
375
738
  Add(InX::Iplt);
376
738
377
738
  if (!Config->Relocatable) {
378
715
    if (Config->EhFrameHdr) {
379
4
      InX::EhFrameHdr = make<EhFrameHeader>();
380
4
      Add(InX::EhFrameHdr);
381
4
    }
382
715
    InX::EhFrame = make<EhFrameSection>();
383
715
    Add(InX::EhFrame);
384
715
  }
385
738
386
738
  if (InX::SymTab)
387
735
    Add(InX::SymTab);
388
738
  Add(InX::ShStrTab);
389
738
  if (InX::StrTab)
390
735
    Add(InX::StrTab);
391
738
392
738
  if (Config->EMachine == EM_ARM && 
!Config->Relocatable0
)
393
0
    // Add a sentinel to terminate .ARM.exidx. It helps an unwinder
394
0
    // to find the exact address range of the last entry.
395
0
    Add(make<ARMExidxSentinelSection>());
396
738
}
Writer.cpp:void createSyntheticSections<llvm::object::ELFType<(llvm::support::endianness)0, true> >()
Line
Count
Source
239
28
template <class ELFT> static void createSyntheticSections() {
240
28
  // Initialize all pointers with NULL. This is needed because
241
28
  // you can call lld::elf::main more than once as a library.
242
28
  memset(&Out::First, 0, sizeof(Out));
243
28
244
28
  auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
245
28
246
28
  InX::DynStrTab = make<StringTableSection>(".dynstr", true);
247
28
  InX::Dynamic = make<DynamicSection<ELFT>>();
248
28
  if (Config->AndroidPackDynRelocs) {
249
0
    InX::RelaDyn = make<AndroidPackedRelocationSection<ELFT>>(
250
0
        Config->IsRela ? ".rela.dyn" : ".rel.dyn");
251
28
  } else {
252
28
    InX::RelaDyn = make<RelocationSection<ELFT>>(
253
28
        Config->IsRela ? ".rela.dyn" : 
".rel.dyn"0
, Config->ZCombreloc);
254
28
  }
255
28
  InX::ShStrTab = make<StringTableSection>(".shstrtab", false);
256
28
257
28
  Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
258
28
  Out::ProgramHeaders->Alignment = Config->Wordsize;
259
28
260
28
  if (needsInterpSection()) {
261
1
    InX::Interp = createInterpSection();
262
1
    Add(InX::Interp);
263
27
  } else {
264
27
    InX::Interp = nullptr;
265
27
  }
266
28
267
28
  if (Config->Strip != StripPolicy::All) {
268
28
    InX::StrTab = make<StringTableSection>(".strtab", false);
269
28
    InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab);
270
28
  }
271
28
272
28
  if (Config->BuildId != BuildIdKind::None) {
273
0
    InX::BuildId = make<BuildIdSection>();
274
0
    Add(InX::BuildId);
275
0
  }
276
28
277
28
  InX::Bss = make<BssSection>(".bss", 0, 1);
278
28
  Add(InX::Bss);
279
28
280
28
  // If there is a SECTIONS command and a .data.rel.ro section name use name
281
28
  // .data.rel.ro.bss so that we match in the .data.rel.ro output section.
282
28
  // This makes sure our relro is contiguous.
283
28
  bool HasDataRelRo =
284
28
      Script->HasSectionsCommand && 
findSection(".data.rel.ro")2
;
285
28
  InX::BssRelRo = make<BssSection>(
286
28
      HasDataRelRo ? 
".data.rel.ro.bss"0
: ".bss.rel.ro", 0, 1);
287
28
  Add(InX::BssRelRo);
288
28
289
28
  // Add MIPS-specific sections.
290
28
  if (Config->EMachine == EM_MIPS) {
291
19
    if (!Config->Shared && 
Config->HasDynSymTab11
) {
292
3
      InX::MipsRldMap = make<MipsRldMapSection>();
293
3
      Add(InX::MipsRldMap);
294
3
    }
295
19
    if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
296
19
      Add(Sec);
297
19
    if (auto *Sec = MipsOptionsSection<ELFT>::create())
298
19
      Add(Sec);
299
19
    if (auto *Sec = MipsReginfoSection<ELFT>::create())
300
0
      Add(Sec);
301
19
  }
302
28
303
28
  if (Config->HasDynSymTab) {
304
17
    InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab);
305
17
    Add(InX::DynSymTab);
306
17
307
17
    In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
308
17
    Add(In<ELFT>::VerSym);
309
17
310
17
    if (!Config->VersionDefinitions.empty()) {
311
0
      In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
312
0
      Add(In<ELFT>::VerDef);
313
0
    }
314
17
315
17
    In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
316
17
    Add(In<ELFT>::VerNeed);
317
17
318
17
    if (Config->GnuHash) {
319
6
      InX::GnuHashTab = make<GnuHashTableSection>();
320
6
      Add(InX::GnuHashTab);
321
6
    }
322
17
323
17
    if (Config->SysvHash) {
324
17
      InX::HashTab = make<HashTableSection>();
325
17
      Add(InX::HashTab);
326
17
    }
327
17
328
17
    Add(InX::Dynamic);
329
17
    Add(InX::DynStrTab);
330
17
    Add(InX::RelaDyn);
331
17
  }
332
28
333
28
  // Add .got. MIPS' .got is so different from the other archs,
334
28
  // it has its own class.
335
28
  if (Config->EMachine == EM_MIPS) {
336
19
    InX::MipsGot = make<MipsGotSection>();
337
19
    Add(InX::MipsGot);
338
19
  } else {
339
9
    InX::Got = make<GotSection>();
340
9
    Add(InX::Got);
341
9
  }
342
28
343
28
  InX::GotPlt = make<GotPltSection>();
344
28
  Add(InX::GotPlt);
345
28
  InX::IgotPlt = make<IgotPltSection>();
346
28
  Add(InX::IgotPlt);
347
28
348
28
  if (Config->GdbIndex) {
349
0
    InX::GdbIndex = createGdbIndex<ELFT>();
350
0
    Add(InX::GdbIndex);
351
0
  }
352
28
353
28
  // We always need to add rel[a].plt to output if it has entries.
354
28
  // Even for static linking it can contain R_[*]_IRELATIVE relocations.
355
28
  InX::RelaPlt = make<RelocationSection<ELFT>>(
356
28
      Config->IsRela ? ".rela.plt" : 
".rel.plt"0
, false /*Sort*/);
357
28
  Add(InX::RelaPlt);
358
28
359
28
  // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
360
28
  // that the IRelative relocations are processed last by the dynamic loader.
361
28
  // We cannot place the iplt section in .rel.dyn when Android relocation
362
28
  // packing is enabled because that would cause a section type mismatch.
363
28
  // However, because the Android dynamic loader reads .rel.plt after .rel.dyn,
364
28
  // we can get the desired behaviour by placing the iplt section in .rel.plt.
365
28
  InX::RelaIplt = make<RelocationSection<ELFT>>(
366
28
      (Config->EMachine == EM_ARM && 
!Config->AndroidPackDynRelocs0
)
367
28
          ? 
".rel.dyn"0
368
28
          : InX::RelaPlt->Name,
369
28
      false /*Sort*/);
370
28
  Add(InX::RelaIplt);
371
28
372
28
  InX::Plt = make<PltSection>(false);
373
28
  Add(InX::Plt);
374
28
  InX::Iplt = make<PltSection>(true);
375
28
  Add(InX::Iplt);
376
28
377
28
  if (!Config->Relocatable) {
378
28
    if (Config->EhFrameHdr) {
379
3
      InX::EhFrameHdr = make<EhFrameHeader>();
380
3
      Add(InX::EhFrameHdr);
381
3
    }
382
28
    InX::EhFrame = make<EhFrameSection>();
383
28
    Add(InX::EhFrame);
384
28
  }
385
28
386
28
  if (InX::SymTab)
387
28
    Add(InX::SymTab);
388
28
  Add(InX::ShStrTab);
389
28
  if (InX::StrTab)
390
28
    Add(InX::StrTab);
391
28
392
28
  if (Config->EMachine == EM_ARM && 
!Config->Relocatable0
)
393
0
    // Add a sentinel to terminate .ARM.exidx. It helps an unwinder
394
0
    // to find the exact address range of the last entry.
395
0
    Add(make<ARMExidxSentinelSection>());
396
28
}
397
398
// The main function of the writer.
399
936
template <class ELFT> void Writer<ELFT>::run() {
400
936
  // Create linker-synthesized sections such as .got or .plt.
401
936
  // Such sections are of type input section.
402
936
  createSyntheticSections<ELFT>();
403
936
404
936
  if (!Config->Relocatable)
405
907
    combineEhFrameSections<ELFT>();
406
936
407
936
  // We want to process linker script commands. When SECTIONS command
408
936
  // is given we let it create sections.
409
936
  Script->processSectionCommands();
410
936
411
936
  // Linker scripts controls how input sections are assigned to output sections.
412
936
  // Input sections that were not handled by scripts are called "orphans", and
413
936
  // they are assigned to output sections by the default rule. Process that.
414
936
  Script->addOrphanSections();
415
936
416
936
  if (Config->Discard != DiscardPolicy::All)
417
934
    copyLocalSymbols();
418
936
419
936
  if (Config->CopyRelocs)
420
36
    addSectionSymbols();
421
936
422
936
  // Now that we have a complete set of output sections. This function
423
936
  // completes section contents. For example, we need to add strings
424
936
  // to the string table, and add entries to .got and .plt.
425
936
  // finalizeSections does that.
426
936
  finalizeSections();
427
936
  if (errorCount())
428
52
    return;
429
884
430
884
  Script->assignAddresses();
431
884
432
884
  // If -compressed-debug-sections is specified, we need to compress
433
884
  // .debug_* sections. Do it right now because it changes the size of
434
884
  // output sections.
435
884
  for (OutputSection *Sec : OutputSections)
436
73.3k
    Sec->maybeCompress<ELFT>();
437
884
438
884
  Script->allocateHeaders(Phdrs);
439
884
440
884
  // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
441
884
  // 0 sized region. This has to be done late since only after assignAddresses
442
884
  // we know the size of the sections.
443
884
  removeEmptyPTLoad();
444
884
445
884
  if (!Config->OFormatBinary)
446
882
    assignFileOffsets();
447
2
  else
448
2
    assignFileOffsetsBinary();
449
884
450
884
  setPhdrs();
451
884
452
884
  if (Config->Relocatable) {
453
28
    for (OutputSection *Sec : OutputSections)
454
173
      Sec->Addr = 0;
455
28
  }
456
884
457
884
  // It does not make sense try to open the file if we have error already.
458
884
  if (errorCount())
459
5
    return;
460
879
  // Write the result down to a file.
461
879
  openFile();
462
879
  if (errorCount())
463
0
    return;
464
879
465
879
  if (!Config->OFormatBinary) {
466
877
    writeTrapInstr();
467
877
    writeHeader();
468
877
    writeSections();
469
877
  } else {
470
2
    writeSectionsBinary();
471
2
  }
472
879
473
879
  // Backfill .note.gnu.build-id section content. This is done at last
474
879
  // because the content is usually a hash value of the entire output file.
475
879
  writeBuildId();
476
879
  if (errorCount())
477
16
    return;
478
863
479
863
  // Handle -Map option.
480
863
  writeMapFile();
481
863
  if (errorCount())
482
0
    return;
483
863
484
863
  if (auto E = Buffer->commit())
485
0
    error("failed to write to the output file: " + toString(std::move(E)));
486
863
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::run()
Line
Count
Source
399
118
template <class ELFT> void Writer<ELFT>::run() {
400
118
  // Create linker-synthesized sections such as .got or .plt.
401
118
  // Such sections are of type input section.
402
118
  createSyntheticSections<ELFT>();
403
118
404
118
  if (!Config->Relocatable)
405
117
    combineEhFrameSections<ELFT>();
406
118
407
118
  // We want to process linker script commands. When SECTIONS command
408
118
  // is given we let it create sections.
409
118
  Script->processSectionCommands();
410
118
411
118
  // Linker scripts controls how input sections are assigned to output sections.
412
118
  // Input sections that were not handled by scripts are called "orphans", and
413
118
  // they are assigned to output sections by the default rule. Process that.
414
118
  Script->addOrphanSections();
415
118
416
118
  if (Config->Discard != DiscardPolicy::All)
417
118
    copyLocalSymbols();
418
118
419
118
  if (Config->CopyRelocs)
420
3
    addSectionSymbols();
421
118
422
118
  // Now that we have a complete set of output sections. This function
423
118
  // completes section contents. For example, we need to add strings
424
118
  // to the string table, and add entries to .got and .plt.
425
118
  // finalizeSections does that.
426
118
  finalizeSections();
427
118
  if (errorCount())
428
2
    return;
429
116
430
116
  Script->assignAddresses();
431
116
432
116
  // If -compressed-debug-sections is specified, we need to compress
433
116
  // .debug_* sections. Do it right now because it changes the size of
434
116
  // output sections.
435
116
  for (OutputSection *Sec : OutputSections)
436
1.14k
    Sec->maybeCompress<ELFT>();
437
116
438
116
  Script->allocateHeaders(Phdrs);
439
116
440
116
  // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
441
116
  // 0 sized region. This has to be done late since only after assignAddresses
442
116
  // we know the size of the sections.
443
116
  removeEmptyPTLoad();
444
116
445
116
  if (!Config->OFormatBinary)
446
116
    assignFileOffsets();
447
0
  else
448
0
    assignFileOffsetsBinary();
449
116
450
116
  setPhdrs();
451
116
452
116
  if (Config->Relocatable) {
453
1
    for (OutputSection *Sec : OutputSections)
454
6
      Sec->Addr = 0;
455
1
  }
456
116
457
116
  // It does not make sense try to open the file if we have error already.
458
116
  if (errorCount())
459
0
    return;
460
116
  // Write the result down to a file.
461
116
  openFile();
462
116
  if (errorCount())
463
0
    return;
464
116
465
116
  if (!Config->OFormatBinary) {
466
116
    writeTrapInstr();
467
116
    writeHeader();
468
116
    writeSections();
469
116
  } else {
470
0
    writeSectionsBinary();
471
0
  }
472
116
473
116
  // Backfill .note.gnu.build-id section content. This is done at last
474
116
  // because the content is usually a hash value of the entire output file.
475
116
  writeBuildId();
476
116
  if (errorCount())
477
1
    return;
478
115
479
115
  // Handle -Map option.
480
115
  writeMapFile();
481
115
  if (errorCount())
482
0
    return;
483
115
484
115
  if (auto E = Buffer->commit())
485
0
    error("failed to write to the output file: " + toString(std::move(E)));
486
115
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::run()
Line
Count
Source
399
52
template <class ELFT> void Writer<ELFT>::run() {
400
52
  // Create linker-synthesized sections such as .got or .plt.
401
52
  // Such sections are of type input section.
402
52
  createSyntheticSections<ELFT>();
403
52
404
52
  if (!Config->Relocatable)
405
47
    combineEhFrameSections<ELFT>();
406
52
407
52
  // We want to process linker script commands. When SECTIONS command
408
52
  // is given we let it create sections.
409
52
  Script->processSectionCommands();
410
52
411
52
  // Linker scripts controls how input sections are assigned to output sections.
412
52
  // Input sections that were not handled by scripts are called "orphans", and
413
52
  // they are assigned to output sections by the default rule. Process that.
414
52
  Script->addOrphanSections();
415
52
416
52
  if (Config->Discard != DiscardPolicy::All)
417
51
    copyLocalSymbols();
418
52
419
52
  if (Config->CopyRelocs)
420
5
    addSectionSymbols();
421
52
422
52
  // Now that we have a complete set of output sections. This function
423
52
  // completes section contents. For example, we need to add strings
424
52
  // to the string table, and add entries to .got and .plt.
425
52
  // finalizeSections does that.
426
52
  finalizeSections();
427
52
  if (errorCount())
428
2
    return;
429
50
430
50
  Script->assignAddresses();
431
50
432
50
  // If -compressed-debug-sections is specified, we need to compress
433
50
  // .debug_* sections. Do it right now because it changes the size of
434
50
  // output sections.
435
50
  for (OutputSection *Sec : OutputSections)
436
627
    Sec->maybeCompress<ELFT>();
437
50
438
50
  Script->allocateHeaders(Phdrs);
439
50
440
50
  // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
441
50
  // 0 sized region. This has to be done late since only after assignAddresses
442
50
  // we know the size of the sections.
443
50
  removeEmptyPTLoad();
444
50
445
50
  if (!Config->OFormatBinary)
446
50
    assignFileOffsets();
447
0
  else
448
0
    assignFileOffsetsBinary();
449
50
450
50
  setPhdrs();
451
50
452
50
  if (Config->Relocatable) {
453
4
    for (OutputSection *Sec : OutputSections)
454
37
      Sec->Addr = 0;
455
4
  }
456
50
457
50
  // It does not make sense try to open the file if we have error already.
458
50
  if (errorCount())
459
0
    return;
460
50
  // Write the result down to a file.
461
50
  openFile();
462
50
  if (errorCount())
463
0
    return;
464
50
465
50
  if (!Config->OFormatBinary) {
466
50
    writeTrapInstr();
467
50
    writeHeader();
468
50
    writeSections();
469
50
  } else {
470
0
    writeSectionsBinary();
471
0
  }
472
50
473
50
  // Backfill .note.gnu.build-id section content. This is done at last
474
50
  // because the content is usually a hash value of the entire output file.
475
50
  writeBuildId();
476
50
  if (errorCount())
477
0
    return;
478
50
479
50
  // Handle -Map option.
480
50
  writeMapFile();
481
50
  if (errorCount())
482
0
    return;
483
50
484
50
  if (auto E = Buffer->commit())
485
0
    error("failed to write to the output file: " + toString(std::move(E)));
486
50
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::run()
Line
Count
Source
399
738
template <class ELFT> void Writer<ELFT>::run() {
400
738
  // Create linker-synthesized sections such as .got or .plt.
401
738
  // Such sections are of type input section.
402
738
  createSyntheticSections<ELFT>();
403
738
404
738
  if (!Config->Relocatable)
405
715
    combineEhFrameSections<ELFT>();
406
738
407
738
  // We want to process linker script commands. When SECTIONS command
408
738
  // is given we let it create sections.
409
738
  Script->processSectionCommands();
410
738
411
738
  // Linker scripts controls how input sections are assigned to output sections.
412
738
  // Input sections that were not handled by scripts are called "orphans", and
413
738
  // they are assigned to output sections by the default rule. Process that.
414
738
  Script->addOrphanSections();
415
738
416
738
  if (Config->Discard != DiscardPolicy::All)
417
737
    copyLocalSymbols();
418
738
419
738
  if (Config->CopyRelocs)
420
28
    addSectionSymbols();
421
738
422
738
  // Now that we have a complete set of output sections. This function
423
738
  // completes section contents. For example, we need to add strings
424
738
  // to the string table, and add entries to .got and .plt.
425
738
  // finalizeSections does that.
426
738
  finalizeSections();
427
738
  if (errorCount())
428
47
    return;
429
691
430
691
  Script->assignAddresses();
431
691
432
691
  // If -compressed-debug-sections is specified, we need to compress
433
691
  // .debug_* sections. Do it right now because it changes the size of
434
691
  // output sections.
435
691
  for (OutputSection *Sec : OutputSections)
436
71.2k
    Sec->maybeCompress<ELFT>();
437
691
438
691
  Script->allocateHeaders(Phdrs);
439
691
440
691
  // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
441
691
  // 0 sized region. This has to be done late since only after assignAddresses
442
691
  // we know the size of the sections.
443
691
  removeEmptyPTLoad();
444
691
445
691
  if (!Config->OFormatBinary)
446
689
    assignFileOffsets();
447
2
  else
448
2
    assignFileOffsetsBinary();
449
691
450
691
  setPhdrs();
451
691
452
691
  if (Config->Relocatable) {
453
23
    for (OutputSection *Sec : OutputSections)
454
130
      Sec->Addr = 0;
455
23
  }
456
691
457
691
  // It does not make sense try to open the file if we have error already.
458
691
  if (errorCount())
459
5
    return;
460
686
  // Write the result down to a file.
461
686
  openFile();
462
686
  if (errorCount())
463
0
    return;
464
686
465
686
  if (!Config->OFormatBinary) {
466
684
    writeTrapInstr();
467
684
    writeHeader();
468
684
    writeSections();
469
684
  } else {
470
2
    writeSectionsBinary();
471
2
  }
472
686
473
686
  // Backfill .note.gnu.build-id section content. This is done at last
474
686
  // because the content is usually a hash value of the entire output file.
475
686
  writeBuildId();
476
686
  if (errorCount())
477
13
    return;
478
673
479
673
  // Handle -Map option.
480
673
  writeMapFile();
481
673
  if (errorCount())
482
0
    return;
483
673
484
673
  if (auto E = Buffer->commit())
485
0
    error("failed to write to the output file: " + toString(std::move(E)));
486
673
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::run()
Line
Count
Source
399
28
template <class ELFT> void Writer<ELFT>::run() {
400
28
  // Create linker-synthesized sections such as .got or .plt.
401
28
  // Such sections are of type input section.
402
28
  createSyntheticSections<ELFT>();
403
28
404
28
  if (!Config->Relocatable)
405
28
    combineEhFrameSections<ELFT>();
406
28
407
28
  // We want to process linker script commands. When SECTIONS command
408
28
  // is given we let it create sections.
409
28
  Script->processSectionCommands();
410
28
411
28
  // Linker scripts controls how input sections are assigned to output sections.
412
28
  // Input sections that were not handled by scripts are called "orphans", and
413
28
  // they are assigned to output sections by the default rule. Process that.
414
28
  Script->addOrphanSections();
415
28
416
28
  if (Config->Discard != DiscardPolicy::All)
417
28
    copyLocalSymbols();
418
28
419
28
  if (Config->CopyRelocs)
420
0
    addSectionSymbols();
421
28
422
28
  // Now that we have a complete set of output sections. This function
423
28
  // completes section contents. For example, we need to add strings
424
28
  // to the string table, and add entries to .got and .plt.
425
28
  // finalizeSections does that.
426
28
  finalizeSections();
427
28
  if (errorCount())
428
1
    return;
429
27
430
27
  Script->assignAddresses();
431
27
432
27
  // If -compressed-debug-sections is specified, we need to compress
433
27
  // .debug_* sections. Do it right now because it changes the size of
434
27
  // output sections.
435
27
  for (OutputSection *Sec : OutputSections)
436
345
    Sec->maybeCompress<ELFT>();
437
27
438
27
  Script->allocateHeaders(Phdrs);
439
27
440
27
  // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
441
27
  // 0 sized region. This has to be done late since only after assignAddresses
442
27
  // we know the size of the sections.
443
27
  removeEmptyPTLoad();
444
27
445
27
  if (!Config->OFormatBinary)
446
27
    assignFileOffsets();
447
0
  else
448
0
    assignFileOffsetsBinary();
449
27
450
27
  setPhdrs();
451
27
452
27
  if (Config->Relocatable) {
453
0
    for (OutputSection *Sec : OutputSections)
454
0
      Sec->Addr = 0;
455
0
  }
456
27
457
27
  // It does not make sense try to open the file if we have error already.
458
27
  if (errorCount())
459
0
    return;
460
27
  // Write the result down to a file.
461
27
  openFile();
462
27
  if (errorCount())
463
0
    return;
464
27
465
27
  if (!Config->OFormatBinary) {
466
27
    writeTrapInstr();
467
27
    writeHeader();
468
27
    writeSections();
469
27
  } else {
470
0
    writeSectionsBinary();
471
0
  }
472
27
473
27
  // Backfill .note.gnu.build-id section content. This is done at last
474
27
  // because the content is usually a hash value of the entire output file.
475
27
  writeBuildId();
476
27
  if (errorCount())
477
2
    return;
478
25
479
25
  // Handle -Map option.
480
25
  writeMapFile();
481
25
  if (errorCount())
482
0
    return;
483
25
484
25
  if (auto E = Buffer->commit())
485
0
    error("failed to write to the output file: " + toString(std::move(E)));
486
25
}
487
488
static bool shouldKeepInSymtab(SectionBase *Sec, StringRef SymName,
489
867
                               const Symbol &B) {
490
867
  if (B.isFile() || 
B.isSection()790
)
491
309
    return false;
492
558
493
558
  // If sym references a section in a discarded group, don't keep it.
494
558
  if (Sec == &InputSection::Discarded)
495
0
    return false;
496
558
497
558
  if (Config->Discard == DiscardPolicy::None)
498
17
    return true;
499
541
500
541
  // In ELF assembly .L symbols are normally discarded by the assembler.
501
541
  // If the assembler fails to do so, the linker discards them if
502
541
  // * --discard-locals is used.
503
541
  // * The symbol is in a SHF_MERGE section, which is normally the reason for
504
541
  //   the assembler keeping the .L symbol.
505
541
  if (!SymName.startswith(".L") && 
!SymName.empty()533
)
506
531
    return true;
507
10
508
10
  if (Config->Discard == DiscardPolicy::Locals)
509
2
    return false;
510
8
511
8
  return !Sec || 
!(Sec->Flags & SHF_MERGE)7
;
512
8
}
513
514
13.8k
static bool includeInSymtab(const Symbol &B) {
515
13.8k
  if (!B.isLocal() && 
!B.IsUsedInRegularObj12.8k
)
516
179
    return false;
517
13.6k
518
13.6k
  if (auto *D = dyn_cast<Defined>(&B)) {
519
13.3k
    // Always include absolute symbols.
520
13.3k
    SectionBase *Sec = D->Section;
521
13.3k
    if (!Sec)
522
270
      return true;
523
13.0k
    Sec = Sec->Repl;
524
13.0k
    // Exclude symbols pointing to garbage-collected sections.
525
13.0k
    if (isa<InputSectionBase>(Sec) && 
!Sec->Live12.9k
)
526
60
      return false;
527
12.9k
    if (auto *S = dyn_cast<MergeInputSection>(Sec))
528
39
      if (!S->getSectionPiece(D->Value)->Live)
529
4
        return false;
530
12.9k
    return true;
531
12.9k
  }
532
325
  return B.Used;
533
325
}
534
535
// Local symbols are not in the linker's symbol table. This function scans
536
// each object file's symbol table to copy local symbols to the output.
537
934
template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
538
934
  if (!InX::SymTab)
539
3
    return;
540
1.12k
  
for (InputFile *File : ObjectFiles)931
{
541
1.12k
    ObjFile<ELFT> *F = cast<ObjFile<ELFT>>(File);
542
1.12k
    for (Symbol *B : F->getLocalSymbols()) {
543
924
      if (!B->isLocal())
544
0
        fatal(toString(F) +
545
0
              ": broken object: getLocalSymbols returns a non-local symbol");
546
924
      auto *DR = dyn_cast<Defined>(B);
547
924
548
924
      // No reason to keep local undefined symbol in symtab.
549
924
      if (!DR)
550
5
        continue;
551
919
      if (!includeInSymtab(*B))
552
52
        continue;
553
867
554
867
      SectionBase *Sec = DR->Section;
555
867
      if (!shouldKeepInSymtab(Sec, B->getName(), *B))
556
318
        continue;
557
549
      InX::SymTab->addSymbol(B);
558
549
    }
559
1.12k
  }
560
931
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::copyLocalSymbols()
Line
Count
Source
537
118
template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
538
118
  if (!InX::SymTab)
539
0
    return;
540
130
  
for (InputFile *File : ObjectFiles)118
{
541
130
    ObjFile<ELFT> *F = cast<ObjFile<ELFT>>(File);
542
332
    for (Symbol *B : F->getLocalSymbols()) {
543
332
      if (!B->isLocal())
544
0
        fatal(toString(F) +
545
0
              ": broken object: getLocalSymbols returns a non-local symbol");
546
332
      auto *DR = dyn_cast<Defined>(B);
547
332
548
332
      // No reason to keep local undefined symbol in symtab.
549
332
      if (!DR)
550
0
        continue;
551
332
      if (!includeInSymtab(*B))
552
7
        continue;
553
325
554
325
      SectionBase *Sec = DR->Section;
555
325
      if (!shouldKeepInSymtab(Sec, B->getName(), *B))
556
60
        continue;
557
265
      InX::SymTab->addSymbol(B);
558
265
    }
559
130
  }
560
118
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::copyLocalSymbols()
Line
Count
Source
537
51
template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
538
51
  if (!InX::SymTab)
539
0
    return;
540
70
  
for (InputFile *File : ObjectFiles)51
{
541
70
    ObjFile<ELFT> *F = cast<ObjFile<ELFT>>(File);
542
70
    for (Symbol *B : F->getLocalSymbols()) {
543
62
      if (!B->isLocal())
544
0
        fatal(toString(F) +
545
0
              ": broken object: getLocalSymbols returns a non-local symbol");
546
62
      auto *DR = dyn_cast<Defined>(B);
547
62
548
62
      // No reason to keep local undefined symbol in symtab.
549
62
      if (!DR)
550
0
        continue;
551
62
      if (!includeInSymtab(*B))
552
0
        continue;
553
62
554
62
      SectionBase *Sec = DR->Section;
555
62
      if (!shouldKeepInSymtab(Sec, B->getName(), *B))
556
28
        continue;
557
34
      InX::SymTab->addSymbol(B);
558
34
    }
559
70
  }
560
51
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::copyLocalSymbols()
Line
Count
Source
537
737
template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
538
737
  if (!InX::SymTab)
539
3
    return;
540
893
  
for (InputFile *File : ObjectFiles)734
{
541
893
    ObjFile<ELFT> *F = cast<ObjFile<ELFT>>(File);
542
893
    for (Symbol *B : F->getLocalSymbols()) {
543
512
      if (!B->isLocal())
544
0
        fatal(toString(F) +
545
0
              ": broken object: getLocalSymbols returns a non-local symbol");
546
512
      auto *DR = dyn_cast<Defined>(B);
547
512
548
512
      // No reason to keep local undefined symbol in symtab.
549
512
      if (!DR)
550
5
        continue;
551
507
      if (!includeInSymtab(*B))
552
45
        continue;
553
462
554
462
      SectionBase *Sec = DR->Section;
555
462
      if (!shouldKeepInSymtab(Sec, B->getName(), *B))
556
220
        continue;
557
242
      InX::SymTab->addSymbol(B);
558
242
    }
559
893
  }
560
734
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::copyLocalSymbols()
Line
Count
Source
537
28
template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
538
28
  if (!InX::SymTab)
539
0
    return;
540
33
  
for (InputFile *File : ObjectFiles)28
{
541
33
    ObjFile<ELFT> *F = cast<ObjFile<ELFT>>(File);
542
33
    for (Symbol *B : F->getLocalSymbols()) {
543
18
      if (!B->isLocal())
544
0
        fatal(toString(F) +
545
0
              ": broken object: getLocalSymbols returns a non-local symbol");
546
18
      auto *DR = dyn_cast<Defined>(B);
547
18
548
18
      // No reason to keep local undefined symbol in symtab.
549
18
      if (!DR)
550
0
        continue;
551
18
      if (!includeInSymtab(*B))
552
0
        continue;
553
18
554
18
      SectionBase *Sec = DR->Section;
555
18
      if (!shouldKeepInSymtab(Sec, B->getName(), *B))
556
10
        continue;
557
8
      InX::SymTab->addSymbol(B);
558
8
    }
559
33
  }
560
28
}
561
562
36
template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
563
36
  // Create a section symbol for each output section so that we can represent
564
36
  // relocations that point to the section. If we know that no relocation is
565
36
  // referring to a section (that happens if the section is a synthetic one), we
566
36
  // don't create a section symbol for that section.
567
473
  for (BaseCommand *Base : Script->SectionCommands) {
568
473
    auto *Sec = dyn_cast<OutputSection>(Base);
569
473
    if (!Sec)
570
0
      continue;
571
473
    auto I = llvm::find_if(Sec->SectionCommands, [](BaseCommand *Base) {
572
473
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
573
472
        return !ISD->Sections.empty();
574
1
      return false;
575
1
    });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addSectionSymbols()::'lambda'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
571
50
    auto I = llvm::find_if(Sec->SectionCommands, [](BaseCommand *Base) {
572
50
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
573
49
        return !ISD->Sections.empty();
574
1
      return false;
575
1
    });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addSectionSymbols()::'lambda'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
571
73
    auto I = llvm::find_if(Sec->SectionCommands, [](BaseCommand *Base) {
572
73
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
573
73
        return !ISD->Sections.empty();
574
0
      return false;
575
0
    });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addSectionSymbols()::'lambda'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
571
350
    auto I = llvm::find_if(Sec->SectionCommands, [](BaseCommand *Base) {
572
350
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
573
350
        return !ISD->Sections.empty();
574
0
      return false;
575
0
    });
Unexecuted instantiation: Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addSectionSymbols()::'lambda'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
576
473
    if (I == Sec->SectionCommands.end())
577
1
      continue;
578
472
    InputSection *IS = cast<InputSectionDescription>(*I)->Sections[0];
579
472
580
472
    // Relocations are not using REL[A] section symbols.
581
472
    if (IS->Type == SHT_REL || 
IS->Type == SHT_RELA456
)
582
61
      continue;
583
411
584
411
    // Unlike other synthetic sections, mergeable output sections contain data
585
411
    // copied from input sections, and there may be a relocation pointing to its
586
411
    // contents if -r or -emit-reloc are given.
587
411
    if (isa<SyntheticSection>(IS) && 
!(IS->Flags & SHF_MERGE)341
)
588
329
      continue;
589
82
590
82
    auto *Sym =
591
82
        make<Defined>(IS->File, "", STB_LOCAL, /*StOther=*/0, STT_SECTION,
592
82
                      /*Value=*/0, /*Size=*/0, IS);
593
82
    InX::SymTab->addSymbol(Sym);
594
82
  }
595
36
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addSectionSymbols()
Line
Count
Source
562
3
template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
563
3
  // Create a section symbol for each output section so that we can represent
564
3
  // relocations that point to the section. If we know that no relocation is
565
3
  // referring to a section (that happens if the section is a synthetic one), we
566
3
  // don't create a section symbol for that section.
567
50
  for (BaseCommand *Base : Script->SectionCommands) {
568
50
    auto *Sec = dyn_cast<OutputSection>(Base);
569
50
    if (!Sec)
570
0
      continue;
571
50
    auto I = llvm::find_if(Sec->SectionCommands, [](BaseCommand *Base) {
572
50
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
573
50
        return !ISD->Sections.empty();
574
50
      return false;
575
50
    });
576
50
    if (I == Sec->SectionCommands.end())
577
1
      continue;
578
49
    InputSection *IS = cast<InputSectionDescription>(*I)->Sections[0];
579
49
580
49
    // Relocations are not using REL[A] section symbols.
581
49
    if (IS->Type == SHT_REL || 
IS->Type == SHT_RELA42
)
582
7
      continue;
583
42
584
42
    // Unlike other synthetic sections, mergeable output sections contain data
585
42
    // copied from input sections, and there may be a relocation pointing to its
586
42
    // contents if -r or -emit-reloc are given.
587
42
    if (isa<SyntheticSection>(IS) && 
!(IS->Flags & SHF_MERGE)37
)
588
34
      continue;
589
8
590
8
    auto *Sym =
591
8
        make<Defined>(IS->File, "", STB_LOCAL, /*StOther=*/0, STT_SECTION,
592
8
                      /*Value=*/0, /*Size=*/0, IS);
593
8
    InX::SymTab->addSymbol(Sym);
594
8
  }
595
3
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addSectionSymbols()
Line
Count
Source
562
5
template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
563
5
  // Create a section symbol for each output section so that we can represent
564
5
  // relocations that point to the section. If we know that no relocation is
565
5
  // referring to a section (that happens if the section is a synthetic one), we
566
5
  // don't create a section symbol for that section.
567
73
  for (BaseCommand *Base : Script->SectionCommands) {
568
73
    auto *Sec = dyn_cast<OutputSection>(Base);
569
73
    if (!Sec)
570
0
      continue;
571
73
    auto I = llvm::find_if(Sec->SectionCommands, [](BaseCommand *Base) {
572
73
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
573
73
        return !ISD->Sections.empty();
574
73
      return false;
575
73
    });
576
73
    if (I == Sec->SectionCommands.end())
577
0
      continue;
578
73
    InputSection *IS = cast<InputSectionDescription>(*I)->Sections[0];
579
73
580
73
    // Relocations are not using REL[A] section symbols.
581
73
    if (IS->Type == SHT_REL || 
IS->Type == SHT_RELA64
)
582
9
      continue;
583
64
584
64
    // Unlike other synthetic sections, mergeable output sections contain data
585
64
    // copied from input sections, and there may be a relocation pointing to its
586
64
    // contents if -r or -emit-reloc are given.
587
64
    if (isa<SyntheticSection>(IS) && 
!(IS->Flags & SHF_MERGE)45
)
588
45
      continue;
589
19
590
19
    auto *Sym =
591
19
        make<Defined>(IS->File, "", STB_LOCAL, /*StOther=*/0, STT_SECTION,
592
19
                      /*Value=*/0, /*Size=*/0, IS);
593
19
    InX::SymTab->addSymbol(Sym);
594
19
  }
595
5
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addSectionSymbols()
Line
Count
Source
562
28
template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
563
28
  // Create a section symbol for each output section so that we can represent
564
28
  // relocations that point to the section. If we know that no relocation is
565
28
  // referring to a section (that happens if the section is a synthetic one), we
566
28
  // don't create a section symbol for that section.
567
350
  for (BaseCommand *Base : Script->SectionCommands) {
568
350
    auto *Sec = dyn_cast<OutputSection>(Base);
569
350
    if (!Sec)
570
0
      continue;
571
350
    auto I = llvm::find_if(Sec->SectionCommands, [](BaseCommand *Base) {
572
350
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
573
350
        return !ISD->Sections.empty();
574
350
      return false;
575
350
    });
576
350
    if (I == Sec->SectionCommands.end())
577
0
      continue;
578
350
    InputSection *IS = cast<InputSectionDescription>(*I)->Sections[0];
579
350
580
350
    // Relocations are not using REL[A] section symbols.
581
350
    if (IS->Type == SHT_REL || IS->Type == SHT_RELA)
582
45
      continue;
583
305
584
305
    // Unlike other synthetic sections, mergeable output sections contain data
585
305
    // copied from input sections, and there may be a relocation pointing to its
586
305
    // contents if -r or -emit-reloc are given.
587
305
    if (isa<SyntheticSection>(IS) && 
!(IS->Flags & SHF_MERGE)259
)
588
250
      continue;
589
55
590
55
    auto *Sym =
591
55
        make<Defined>(IS->File, "", STB_LOCAL, /*StOther=*/0, STT_SECTION,
592
55
                      /*Value=*/0, /*Size=*/0, IS);
593
55
    InX::SymTab->addSymbol(Sym);
594
55
  }
595
28
}
Unexecuted instantiation: Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addSectionSymbols()
596
597
// Today's loaders have a feature to make segments read-only after
598
// processing dynamic relocations to enhance security. PT_GNU_RELRO
599
// is defined for that.
600
//
601
// This function returns true if a section needs to be put into a
602
// PT_GNU_RELRO segment.
603
15.6k
static bool isRelroSection(const OutputSection *Sec) {
604
15.6k
  if (!Config->ZRelro)
605
121
    return false;
606
15.5k
607
15.5k
  uint64_t Flags = Sec->Flags;
608
15.5k
609
15.5k
  // Non-allocatable or non-writable sections don't need RELRO because
610
15.5k
  // they are not writable or not even mapped to memory in the first place.
611
15.5k
  // RELRO is for sections that are essentially read-only but need to
612
15.5k
  // be writable only at process startup to allow dynamic linker to
613
15.5k
  // apply relocations.
614
15.5k
  if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
615
10.3k
    return false;
616
5.12k
617
5.12k
  // Once initialized, TLS data segments are used as data templates
618
5.12k
  // for a thread-local storage. For each new thread, runtime
619
5.12k
  // allocates memory for a TLS and copy templates there. No thread
620
5.12k
  // are supposed to use templates directly. Thus, it can be in RELRO.
621
5.12k
  if (Flags & SHF_TLS)
622
72
    return true;
623
5.05k
624
5.05k
  // .init_array, .preinit_array and .fini_array contain pointers to
625
5.05k
  // functions that are executed on process startup or exit. These
626
5.05k
  // pointers are set by the static linker, and they are not expected
627
5.05k
  // to change at runtime. But if you are an attacker, you could do
628
5.05k
  // interesting things by manipulating pointers in .fini_array, for
629
5.05k
  // example. So they are put into RELRO.
630
5.05k
  uint32_t Type = Sec->Type;
631
5.05k
  if (Type == SHT_INIT_ARRAY || 
Type == SHT_FINI_ARRAY5.04k
||
632
5.05k
      
Type == SHT_PREINIT_ARRAY5.03k
)
633
32
    return true;
634
5.02k
635
5.02k
  // .got contains pointers to external symbols. They are resolved by
636
5.02k
  // the dynamic linker when a module is loaded into memory, and after
637
5.02k
  // that they are not expected to change. So, it can be in RELRO.
638
5.02k
  if (InX::Got && 
Sec == InX::Got->getParent()4.46k
)
639
842
    return true;
640
4.18k
641
4.18k
  // .got.plt contains pointers to external function symbols. They are
642
4.18k
  // by default resolved lazily, so we usually cannot put it into RELRO.
643
4.18k
  // However, if "-z now" is given, the lazy symbol resolution is
644
4.18k
  // disabled, which enables us to put it into RELRO.
645
4.18k
  if (Sec == InX::GotPlt->getParent())
646
945
    return Config->ZNow;
647
3.23k
648
3.23k
  // .dynamic section contains data for the dynamic linker, and
649
3.23k
  // there's no need to write to it at runtime, so it's better to put
650
3.23k
  // it into RELRO.
651
3.23k
  if (Sec == InX::Dynamic->getParent())
652
819
    return true;
653
2.41k
654
2.41k
  // Sections with some special names are put into RELRO. This is a
655
2.41k
  // bit unfortunate because section names shouldn't be significant in
656
2.41k
  // ELF in spirit. But in reality many linker features depend on
657
2.41k
  // magic section names.
658
2.41k
  StringRef S = Sec->Name;
659
2.41k
  return S == ".data.rel.ro" || 
S == ".bss.rel.ro"2.40k
||
S == ".ctors"1.55k
||
660
2.41k
         
S == ".dtors"1.55k
||
S == ".jcr"1.54k
||
S == ".eh_frame"1.53k
||
661
2.41k
         
S == ".openbsd.randomdata"1.53k
;
662
2.41k
}
663
664
// We compute a rank for each section. The rank indicates where the
665
// section should be placed in the file.  Instead of using simple
666
// numbers (0,1,2...), we use a series of flags. One for each decision
667
// point when placing the section.
668
// Using flags has two key properties:
669
// * It is easy to check if a give branch was taken.
670
// * It is easy two see how similar two ranks are (see getRankProximity).
671
enum RankFlags {
672
  RF_NOT_ADDR_SET = 1 << 16,
673
  RF_NOT_INTERP = 1 << 15,
674
  RF_NOT_ALLOC = 1 << 14,
675
  RF_WRITE = 1 << 13,
676
  RF_EXEC_WRITE = 1 << 12,
677
  RF_EXEC = 1 << 11,
678
  RF_NON_TLS_BSS = 1 << 10,
679
  RF_NON_TLS_BSS_RO = 1 << 9,
680
  RF_NOT_TLS = 1 << 8,
681
  RF_BSS = 1 << 7,
682
  RF_PPC_NOT_TOCBSS = 1 << 6,
683
  RF_PPC_OPD = 1 << 5,
684
  RF_PPC_TOCL = 1 << 4,
685
  RF_PPC_TOC = 1 << 3,
686
  RF_PPC_BRANCH_LT = 1 << 2,
687
  RF_MIPS_GPREL = 1 << 1,
688
  RF_MIPS_NOT_GOT = 1 << 0
689
};
690
691
80.0k
static unsigned getSectionRank(const OutputSection *Sec) {
692
80.0k
  unsigned Rank = 0;
693
80.0k
694
80.0k
  // We want to put section specified by -T option first, so we
695
80.0k
  // can start assigning VA starting from them later.
696
80.0k
  if (Config->SectionStartMap.count(Sec->Name))
697
14
    return Rank;
698
80.0k
  Rank |= RF_NOT_ADDR_SET;
699
80.0k
700
80.0k
  // Put .interp first because some loaders want to see that section
701
80.0k
  // on the first page of the executable file when loaded into memory.
702
80.0k
  if (Sec->Name == ".interp")
703
4
    return Rank;
704
79.9k
  Rank |= RF_NOT_INTERP;
705
79.9k
706
79.9k
  // Allocatable sections go first to reduce the total PT_LOAD size and
707
79.9k
  // so debug info doesn't change addresses in actual code.
708
79.9k
  if (!(Sec->Flags & SHF_ALLOC))
709
68.7k
    return Rank | RF_NOT_ALLOC;
710
11.2k
711
11.2k
  // Sort sections based on their access permission in the following
712
11.2k
  // order: R, RX, RWX, RW.  This order is based on the following
713
11.2k
  // considerations:
714
11.2k
  // * Read-only sections come first such that they go in the
715
11.2k
  //   PT_LOAD covering the program headers at the start of the file.
716
11.2k
  // * Read-only, executable sections come next, unless the
717
11.2k
  //   -no-rosegment option is used.
718
11.2k
  // * Writable, executable sections follow such that .plt on
719
11.2k
  //   architectures where it needs to be writable will be placed
720
11.2k
  //   between .text and .data.
721
11.2k
  // * Writable sections come last, such that .bss lands at the very
722
11.2k
  //   end of the last PT_LOAD.
723
11.2k
  bool IsExec = Sec->Flags & SHF_EXECINSTR;
724
11.2k
  bool IsWrite = Sec->Flags & SHF_WRITE;
725
11.2k
726
11.2k
  if (IsExec) {
727
1.82k
    if (IsWrite)
728
13
      Rank |= RF_EXEC_WRITE;
729
1.81k
    else if (!Config->SingleRoRx)
730
1.40k
      Rank |= RF_EXEC;
731
9.39k
  } else {
732
9.39k
    if (IsWrite)
733
4.13k
      Rank |= RF_WRITE;
734
9.39k
  }
735
11.2k
736
11.2k
  // If we got here we know that both A and B are in the same PT_LOAD.
737
11.2k
738
11.2k
  bool IsTls = Sec->Flags & SHF_TLS;
739
11.2k
  bool IsNoBits = Sec->Type == SHT_NOBITS;
740
11.2k
741
11.2k
  // The first requirement we have is to put (non-TLS) nobits sections last. The
742
11.2k
  // reason is that the only thing the dynamic linker will see about them is a
743
11.2k
  // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
744
11.2k
  // PT_LOAD, so that has to correspond to the nobits sections.
745
11.2k
  bool IsNonTlsNoBits = IsNoBits && 
!IsTls1.74k
;
746
11.2k
  if (IsNonTlsNoBits)
747
1.71k
    Rank |= RF_NON_TLS_BSS;
748
11.2k
749
11.2k
  // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
750
11.2k
  // sections after r/w ones, so that the RelRo sections are contiguous.
751
11.2k
  bool IsRelRo = isRelroSection(Sec);
752
11.2k
  if (IsNonTlsNoBits && 
!IsRelRo1.71k
)
753
870
    Rank |= RF_NON_TLS_BSS_RO;
754
11.2k
  if (!IsNonTlsNoBits && 
IsRelRo9.50k
)
755
1.28k
    Rank |= RF_NON_TLS_BSS_RO;
756
11.2k
757
11.2k
  // The TLS initialization block needs to be a single contiguous block in a R/W
758
11.2k
  // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
759
11.2k
  // sections. The TLS NOBITS sections are placed here as they don't take up
760
11.2k
  // virtual address space in the PT_LOAD.
761
11.2k
  if (!IsTls)
762
11.1k
    Rank |= RF_NOT_TLS;
763
11.2k
764
11.2k
  // Within the TLS initialization block, the non-nobits sections need to appear
765
11.2k
  // first.
766
11.2k
  if (IsNoBits)
767
1.74k
    Rank |= RF_BSS;
768
11.2k
769
11.2k
  // Some architectures have additional ordering restrictions for sections
770
11.2k
  // within the same PT_LOAD.
771
11.2k
  if (Config->EMachine == EM_PPC64) {
772
132
    // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections
773
132
    // that we would like to make sure appear is a specific order to maximize
774
132
    // their coverage by a single signed 16-bit offset from the TOC base
775
132
    // pointer. Conversely, the special .tocbss section should be first among
776
132
    // all SHT_NOBITS sections. This will put it next to the loaded special
777
132
    // PPC64 sections (and, thus, within reach of the TOC base pointer).
778
132
    StringRef Name = Sec->Name;
779
132
    if (Name != ".tocbss")
780
132
      Rank |= RF_PPC_NOT_TOCBSS;
781
132
782
132
    if (Name == ".opd")
783
3
      Rank |= RF_PPC_OPD;
784
132
785
132
    if (Name == ".toc1")
786
0
      Rank |= RF_PPC_TOCL;
787
132
788
132
    if (Name == ".toc")
789
2
      Rank |= RF_PPC_TOC;
790
132
791
132
    if (Name == ".branch_lt")
792
0
      Rank |= RF_PPC_BRANCH_LT;
793
132
  }
794
11.2k
  if (Config->EMachine == EM_MIPS) {
795
1.03k
    // All sections with SHF_MIPS_GPREL flag should be grouped together
796
1.03k
    // because data in these sections is addressable with a gp relative address.
797
1.03k
    if (Sec->Flags & SHF_MIPS_GPREL)
798
67
      Rank |= RF_MIPS_GPREL;
799
1.03k
800
1.03k
    if (Sec->Name != ".got")
801
971
      Rank |= RF_MIPS_NOT_GOT;
802
1.03k
  }
803
11.2k
804
11.2k
  return Rank;
805
11.2k
}
806
807
446k
static bool compareSections(const BaseCommand *ACmd, const BaseCommand *BCmd) {
808
446k
  const OutputSection *A = cast<OutputSection>(ACmd);
809
446k
  const OutputSection *B = cast<OutputSection>(BCmd);
810
446k
  if (A->SortRank != B->SortRank)
811
47.5k
    return A->SortRank < B->SortRank;
812
398k
  if (!(A->SortRank & RF_NOT_ADDR_SET))
813
6
    return Config->SectionStartMap.lookup(A->Name) <
814
6
           Config->SectionStartMap.lookup(B->Name);
815
398k
  return false;
816
398k
}
817
818
8.05k
void PhdrEntry::add(OutputSection *Sec) {
819
8.05k
  LastSec = Sec;
820
8.05k
  if (!FirstSec)
821
3.92k
    FirstSec = Sec;
822
8.05k
  p_align = std::max(p_align, Sec->Alignment);
823
8.05k
  if (p_type == PT_LOAD)
824
6.14k
    Sec->PtLoad = this;
825
8.05k
}
826
827
// The beginning and the ending of .rel[a].plt section are marked
828
// with __rel[a]_iplt_{start,end} symbols if it is a statically linked
829
// executable. The runtime needs these symbols in order to resolve
830
// all IRELATIVE relocs on startup. For dynamic executables, we don't
831
// need these symbols, since IRELATIVE relocs are resolved through GOT
832
// and PLT. For details, see http://www.airs.com/blog/archives/403.
833
936
template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
834
936
  if (!Config->Static)
835
924
    return;
836
12
  StringRef S = Config->IsRela ? 
"__rela_iplt_start"8
:
"__rel_iplt_start"4
;
837
12
  addOptionalRegular(S, InX::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
838
12
839
12
  S = Config->IsRela ? 
"__rela_iplt_end"8
:
"__rel_iplt_end"4
;
840
12
  addOptionalRegular(S, InX::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
841
12
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addRelIpltSymbols()
Line
Count
Source
833
118
template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
834
118
  if (!Config->Static)
835
115
    return;
836
3
  StringRef S = Config->IsRela ? 
"__rela_iplt_start"0
: "__rel_iplt_start";
837
3
  addOptionalRegular(S, InX::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
838
3
839
3
  S = Config->IsRela ? 
"__rela_iplt_end"0
: "__rel_iplt_end";
840
3
  addOptionalRegular(S, InX::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
841
3
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addRelIpltSymbols()
Line
Count
Source
833
52
template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
834
52
  if (!Config->Static)
835
51
    return;
836
1
  StringRef S = Config->IsRela ? 
"__rela_iplt_start"0
: "__rel_iplt_start";
837
1
  addOptionalRegular(S, InX::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
838
1
839
1
  S = Config->IsRela ? 
"__rela_iplt_end"0
: "__rel_iplt_end";
840
1
  addOptionalRegular(S, InX::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
841
1
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addRelIpltSymbols()
Line
Count
Source
833
738
template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
834
738
  if (!Config->Static)
835
730
    return;
836
8
  StringRef S = Config->IsRela ? "__rela_iplt_start" : 
"__rel_iplt_start"0
;
837
8
  addOptionalRegular(S, InX::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
838
8
839
8
  S = Config->IsRela ? "__rela_iplt_end" : 
"__rel_iplt_end"0
;
840
8
  addOptionalRegular(S, InX::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
841
8
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addRelIpltSymbols()
Line
Count
Source
833
28
template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
834
28
  if (!Config->Static)
835
28
    return;
836
0
  StringRef S = Config->IsRela ? "__rela_iplt_start" : "__rel_iplt_start";
837
0
  addOptionalRegular(S, InX::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
838
0
839
0
  S = Config->IsRela ? "__rela_iplt_end" : "__rel_iplt_end";
840
0
  addOptionalRegular(S, InX::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
841
0
}
842
843
template <class ELFT>
844
907
void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
845
907
  // Scan all relocations. Each relocation goes through a series
846
907
  // of tests to determine if it needs special treatment, such as
847
907
  // creating GOT, PLT, copy relocations, etc.
848
907
  // Note that relocations for non-alloc sections are directly
849
907
  // processed by InputSection::relocateNonAlloc.
850
907
  for (InputSectionBase *IS : InputSections)
851
84.6k
    if (IS->Live && 
isa<InputSection>(IS)84.4k
&&
(IS->Flags & SHF_ALLOC)84.4k
)
852
15.4k
      Fn(*IS);
853
907
  for (EhInputSection *ES : InX::EhFrame->Sections)
854
53
    Fn(*ES);
855
907
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::forEachRelSec(std::__1::function<void (lld::elf::InputSectionBase&)>)
Line
Count
Source
844
117
void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
845
117
  // Scan all relocations. Each relocation goes through a series
846
117
  // of tests to determine if it needs special treatment, such as
847
117
  // creating GOT, PLT, copy relocations, etc.
848
117
  // Note that relocations for non-alloc sections are directly
849
117
  // processed by InputSection::relocateNonAlloc.
850
117
  for (InputSectionBase *IS : InputSections)
851
2.68k
    if (IS->Live && 
isa<InputSection>(IS)2.66k
&&
(IS->Flags & SHF_ALLOC)2.66k
)
852
2.18k
      Fn(*IS);
853
117
  for (EhInputSection *ES : InX::EhFrame->Sections)
854
2
    Fn(*ES);
855
117
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::forEachRelSec(std::__1::function<void (lld::elf::InputSectionBase&)>)
Line
Count
Source
844
47
void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
845
47
  // Scan all relocations. Each relocation goes through a series
846
47
  // of tests to determine if it needs special treatment, such as
847
47
  // creating GOT, PLT, copy relocations, etc.
848
47
  // Note that relocations for non-alloc sections are directly
849
47
  // processed by InputSection::relocateNonAlloc.
850
47
  for (InputSectionBase *IS : InputSections)
851
1.28k
    if (IS->Live && 
isa<InputSection>(IS)1.16k
&&
(IS->Flags & SHF_ALLOC)1.16k
)
852
970
      Fn(*IS);
853
47
  for (EhInputSection *ES : InX::EhFrame->Sections)
854
1
    Fn(*ES);
855
47
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::forEachRelSec(std::__1::function<void (lld::elf::InputSectionBase&)>)
Line
Count
Source
844
715
void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
845
715
  // Scan all relocations. Each relocation goes through a series
846
715
  // of tests to determine if it needs special treatment, such as
847
715
  // creating GOT, PLT, copy relocations, etc.
848
715
  // Note that relocations for non-alloc sections are directly
849
715
  // processed by InputSection::relocateNonAlloc.
850
715
  for (InputSectionBase *IS : InputSections)
851
79.9k
    if (IS->Live && 
isa<InputSection>(IS)79.9k
&&
(IS->Flags & SHF_ALLOC)79.9k
)
852
11.7k
      Fn(*IS);
853
715
  for (EhInputSection *ES : InX::EhFrame->Sections)
854
47
    Fn(*ES);
855
715
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::forEachRelSec(std::__1::function<void (lld::elf::InputSectionBase&)>)
Line
Count
Source
844
28
void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
845
28
  // Scan all relocations. Each relocation goes through a series
846
28
  // of tests to determine if it needs special treatment, such as
847
28
  // creating GOT, PLT, copy relocations, etc.
848
28
  // Note that relocations for non-alloc sections are directly
849
28
  // processed by InputSection::relocateNonAlloc.
850
28
  for (InputSectionBase *IS : InputSections)
851
712
    if (IS->Live && 
isa<InputSection>(IS)663
&&
(IS->Flags & SHF_ALLOC)663
)
852
551
      Fn(*IS);
853
28
  for (EhInputSection *ES : InX::EhFrame->Sections)
854
3
    Fn(*ES);
855
28
}
856
857
// This function generates assignments for predefined symbols (e.g. _end or
858
// _etext) and inserts them into the commands sequence to be processed at the
859
// appropriate time. This ensures that the value is going to be correct by the
860
// time any references to these symbols are processed and is equivalent to
861
// defining these symbols explicitly in the linker script.
862
887
template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
863
887
  if (ElfSym::GlobalOffsetTable) {
864
7
    // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
865
7
    // be at some offset from the base of the .got section, usually 0 or the end
866
7
    // of the .got
867
7
    InputSection *GotSection = InX::MipsGot ? 
cast<InputSection>(InX::MipsGot)1
868
7
                                            : 
cast<InputSection>(InX::Got)6
;
869
7
    ElfSym::GlobalOffsetTable->Section = GotSection;
870
7
  }
871
887
872
887
  PhdrEntry *Last = nullptr;
873
887
  PhdrEntry *LastRO = nullptr;
874
887
875
4.76k
  for (PhdrEntry *P : Phdrs) {
876
4.76k
    if (P->p_type != PT_LOAD)
877
2.65k
      continue;
878
2.10k
    Last = P;
879
2.10k
    if (!(P->p_flags & PF_W))
880
1.51k
      LastRO = P;
881
2.10k
  }
882
887
883
887
  if (LastRO) {
884
846
    // _etext is the first location after the last read-only loadable segment.
885
846
    if (ElfSym::Etext1)
886
0
      ElfSym::Etext1->Section = LastRO->LastSec;
887
846
    if (ElfSym::Etext2)
888
1
      ElfSym::Etext2->Section = LastRO->LastSec;
889
846
  }
890
887
891
887
  if (Last) {
892
855
    // _edata points to the end of the last mapped initialized section.
893
855
    OutputSection *Edata = nullptr;
894
4.47k
    for (OutputSection *OS : OutputSections) {
895
4.47k
      if (OS->Type != SHT_NOBITS)
896
4.31k
        Edata = OS;
897
4.47k
      if (OS == Last->LastSec)
898
853
        break;
899
4.47k
    }
900
855
901
855
    if (ElfSym::Edata1)
902
0
      ElfSym::Edata1->Section = Edata;
903
855
    if (ElfSym::Edata2)
904
1
      ElfSym::Edata2->Section = Edata;
905
855
906
855
    // _end is the first location after the uninitialized data region.
907
855
    if (ElfSym::End1)
908
2
      ElfSym::End1->Section = Last->LastSec;
909
855
    if (ElfSym::End2)
910
6
      ElfSym::End2->Section = Last->LastSec;
911
855
  }
912
887
913
887
  if (ElfSym::Bss)
914
0
    ElfSym::Bss->Section = findSection(".bss");
915
887
916
887
  // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
917
887
  // be equal to the _gp symbol's value.
918
887
  if (ElfSym::MipsGp) {
919
67
    // Find GP-relative section with the lowest address
920
67
    // and use this address to calculate default _gp value.
921
535
    for (OutputSection *OS : OutputSections) {
922
535
      if (OS->Flags & SHF_MIPS_GPREL) {
923
67
        ElfSym::MipsGp->Section = OS;
924
67
        ElfSym::MipsGp->Value = 0x7ff0;
925
67
        break;
926
67
      }
927
535
    }
928
67
  }
929
887
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::setReservedSymbolSections()
Line
Count
Source
862
116
template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
863
116
  if (ElfSym::GlobalOffsetTable) {
864
3
    // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
865
3
    // be at some offset from the base of the .got section, usually 0 or the end
866
3
    // of the .got
867
3
    InputSection *GotSection = InX::MipsGot ? 
cast<InputSection>(InX::MipsGot)0
868
3
                                            : cast<InputSection>(InX::Got);
869
3
    ElfSym::GlobalOffsetTable->Section = GotSection;
870
3
  }
871
116
872
116
  PhdrEntry *Last = nullptr;
873
116
  PhdrEntry *LastRO = nullptr;
874
116
875
686
  for (PhdrEntry *P : Phdrs) {
876
686
    if (P->p_type != PT_LOAD)
877
390
      continue;
878
296
    Last = P;
879
296
    if (!(P->p_flags & PF_W))
880
210
      LastRO = P;
881
296
  }
882
116
883
116
  if (LastRO) {
884
112
    // _etext is the first location after the last read-only loadable segment.
885
112
    if (ElfSym::Etext1)
886
0
      ElfSym::Etext1->Section = LastRO->LastSec;
887
112
    if (ElfSym::Etext2)
888
0
      ElfSym::Etext2->Section = LastRO->LastSec;
889
112
  }
890
116
891
116
  if (Last) {
892
114
    // _edata points to the end of the last mapped initialized section.
893
114
    OutputSection *Edata = nullptr;
894
673
    for (OutputSection *OS : OutputSections) {
895
673
      if (OS->Type != SHT_NOBITS)
896
646
        Edata = OS;
897
673
      if (OS == Last->LastSec)
898
113
        break;
899
673
    }
900
114
901
114
    if (ElfSym::Edata1)
902
0
      ElfSym::Edata1->Section = Edata;
903
114
    if (ElfSym::Edata2)
904
0
      ElfSym::Edata2->Section = Edata;
905
114
906
114
    // _end is the first location after the uninitialized data region.
907
114
    if (ElfSym::End1)
908
0
      ElfSym::End1->Section = Last->LastSec;
909
114
    if (ElfSym::End2)
910
0
      ElfSym::End2->Section = Last->LastSec;
911
114
  }
912
116
913
116
  if (ElfSym::Bss)
914
0
    ElfSym::Bss->Section = findSection(".bss");
915
116
916
116
  // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
917
116
  // be equal to the _gp symbol's value.
918
116
  if (ElfSym::MipsGp) {
919
4
    // Find GP-relative section with the lowest address
920
4
    // and use this address to calculate default _gp value.
921
33
    for (OutputSection *OS : OutputSections) {
922
33
      if (OS->Flags & SHF_MIPS_GPREL) {
923
4
        ElfSym::MipsGp->Section = OS;
924
4
        ElfSym::MipsGp->Value = 0x7ff0;
925
4
        break;
926
4
      }
927
33
    }
928
4
  }
929
116
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::setReservedSymbolSections()
Line
Count
Source
862
50
template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
863
50
  if (ElfSym::GlobalOffsetTable) {
864
0
    // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
865
0
    // be at some offset from the base of the .got section, usually 0 or the end
866
0
    // of the .got
867
0
    InputSection *GotSection = InX::MipsGot ? cast<InputSection>(InX::MipsGot)
868
0
                                            : cast<InputSection>(InX::Got);
869
0
    ElfSym::GlobalOffsetTable->Section = GotSection;
870
0
  }
871
50
872
50
  PhdrEntry *Last = nullptr;
873
50
  PhdrEntry *LastRO = nullptr;
874
50
875
262
  for (PhdrEntry *P : Phdrs) {
876
262
    if (P->p_type != PT_LOAD)
877
128
      continue;
878
134
    Last = P;
879
134
    if (!(P->p_flags & PF_W))
880
88
      LastRO = P;
881
134
  }
882
50
883
50
  if (LastRO) {
884
46
    // _etext is the first location after the last read-only loadable segment.
885
46
    if (ElfSym::Etext1)
886
0
      ElfSym::Etext1->Section = LastRO->LastSec;
887
46
    if (ElfSym::Etext2)
888
0
      ElfSym::Etext2->Section = LastRO->LastSec;
889
46
  }
890
50
891
50
  if (Last) {
892
46
    // _edata points to the end of the last mapped initialized section.
893
46
    OutputSection *Edata = nullptr;
894
405
    for (OutputSection *OS : OutputSections) {
895
405
      if (OS->Type != SHT_NOBITS)
896
361
        Edata = OS;
897
405
      if (OS == Last->LastSec)
898
46
        break;
899
405
    }
900
46
901
46
    if (ElfSym::Edata1)
902
0
      ElfSym::Edata1->Section = Edata;
903
46
    if (ElfSym::Edata2)
904
0
      ElfSym::Edata2->Section = Edata;
905
46
906
46
    // _end is the first location after the uninitialized data region.
907
46
    if (ElfSym::End1)
908
0
      ElfSym::End1->Section = Last->LastSec;
909
46
    if (ElfSym::End2)
910
0
      ElfSym::End2->Section = Last->LastSec;
911
46
  }
912
50
913
50
  if (ElfSym::Bss)
914
0
    ElfSym::Bss->Section = findSection(".bss");
915
50
916
50
  // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
917
50
  // be equal to the _gp symbol's value.
918
50
  if (ElfSym::MipsGp) {
919
45
    // Find GP-relative section with the lowest address
920
45
    // and use this address to calculate default _gp value.
921
353
    for (OutputSection *OS : OutputSections) {
922
353
      if (OS->Flags & SHF_MIPS_GPREL) {
923
45
        ElfSym::MipsGp->Section = OS;
924
45
        ElfSym::MipsGp->Value = 0x7ff0;
925
45
        break;
926
45
      }
927
353
    }
928
45
  }
929
50
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::setReservedSymbolSections()
Line
Count
Source
862
694
template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
863
694
  if (ElfSym::GlobalOffsetTable) {
864
3
    // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
865
3
    // be at some offset from the base of the .got section, usually 0 or the end
866
3
    // of the .got
867
3
    InputSection *GotSection = InX::MipsGot ? 
cast<InputSection>(InX::MipsGot)0
868
3
                                            : cast<InputSection>(InX::Got);
869
3
    ElfSym::GlobalOffsetTable->Section = GotSection;
870
3
  }
871
694
872
694
  PhdrEntry *Last = nullptr;
873
694
  PhdrEntry *LastRO = nullptr;
874
694
875
3.65k
  for (PhdrEntry *P : Phdrs) {
876
3.65k
    if (P->p_type != PT_LOAD)
877
2.05k
      continue;
878
1.60k
    Last = P;
879
1.60k
    if (!(P->p_flags & PF_W))
880
1.16k
      LastRO = P;
881
1.60k
  }
882
694
883
694
  if (LastRO) {
884
661
    // _etext is the first location after the last read-only loadable segment.
885
661
    if (ElfSym::Etext1)
886
0
      ElfSym::Etext1->Section = LastRO->LastSec;
887
661
    if (ElfSym::Etext2)
888
1
      ElfSym::Etext2->Section = LastRO->LastSec;
889
661
  }
890
694
891
694
  if (Last) {
892
668
    // _edata points to the end of the last mapped initialized section.
893
668
    OutputSection *Edata = nullptr;
894
3.16k
    for (OutputSection *OS : OutputSections) {
895
3.16k
      if (OS->Type != SHT_NOBITS)
896
3.09k
        Edata = OS;
897
3.16k
      if (OS == Last->LastSec)
898
667
        break;
899
3.16k
    }
900
668
901
668
    if (ElfSym::Edata1)
902
0
      ElfSym::Edata1->Section = Edata;
903
668
    if (ElfSym::Edata2)
904
1
      ElfSym::Edata2->Section = Edata;
905
668
906
668
    // _end is the first location after the uninitialized data region.
907
668
    if (ElfSym::End1)
908
2
      ElfSym::End1->Section = Last->LastSec;
909
668
    if (ElfSym::End2)
910
6
      ElfSym::End2->Section = Last->LastSec;
911
668
  }
912
694
913
694
  if (ElfSym::Bss)
914
0
    ElfSym::Bss->Section = findSection(".bss");
915
694
916
694
  // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
917
694
  // be equal to the _gp symbol's value.
918
694
  if (ElfSym::MipsGp) {
919
0
    // Find GP-relative section with the lowest address
920
0
    // and use this address to calculate default _gp value.
921
0
    for (OutputSection *OS : OutputSections) {
922
0
      if (OS->Flags & SHF_MIPS_GPREL) {
923
0
        ElfSym::MipsGp->Section = OS;
924
0
        ElfSym::MipsGp->Value = 0x7ff0;
925
0
        break;
926
0
      }
927
0
    }
928
0
  }
929
694
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::setReservedSymbolSections()
Line
Count
Source
862
27
template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
863
27
  if (ElfSym::GlobalOffsetTable) {
864
1
    // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
865
1
    // be at some offset from the base of the .got section, usually 0 or the end
866
1
    // of the .got
867
1
    InputSection *GotSection = InX::MipsGot ? cast<InputSection>(InX::MipsGot)
868
1
                                            : 
cast<InputSection>(InX::Got)0
;
869
1
    ElfSym::GlobalOffsetTable->Section = GotSection;
870
1
  }
871
27
872
27
  PhdrEntry *Last = nullptr;
873
27
  PhdrEntry *LastRO = nullptr;
874
27
875
163
  for (PhdrEntry *P : Phdrs) {
876
163
    if (P->p_type != PT_LOAD)
877
85
      continue;
878
78
    Last = P;
879
78
    if (!(P->p_flags & PF_W))
880
52
      LastRO = P;
881
78
  }
882
27
883
27
  if (LastRO) {
884
27
    // _etext is the first location after the last read-only loadable segment.
885
27
    if (ElfSym::Etext1)
886
0
      ElfSym::Etext1->Section = LastRO->LastSec;
887
27
    if (ElfSym::Etext2)
888
0
      ElfSym::Etext2->Section = LastRO->LastSec;
889
27
  }
890
27
891
27
  if (Last) {
892
27
    // _edata points to the end of the last mapped initialized section.
893
27
    OutputSection *Edata = nullptr;
894
237
    for (OutputSection *OS : OutputSections) {
895
237
      if (OS->Type != SHT_NOBITS)
896
220
        Edata = OS;
897
237
      if (OS == Last->LastSec)
898
27
        break;
899
237
    }
900
27
901
27
    if (ElfSym::Edata1)
902
0
      ElfSym::Edata1->Section = Edata;
903
27
    if (ElfSym::Edata2)
904
0
      ElfSym::Edata2->Section = Edata;
905
27
906
27
    // _end is the first location after the uninitialized data region.
907
27
    if (ElfSym::End1)
908
0
      ElfSym::End1->Section = Last->LastSec;
909
27
    if (ElfSym::End2)
910
0
      ElfSym::End2->Section = Last->LastSec;
911
27
  }
912
27
913
27
  if (ElfSym::Bss)
914
0
    ElfSym::Bss->Section = findSection(".bss");
915
27
916
27
  // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
917
27
  // be equal to the _gp symbol's value.
918
27
  if (ElfSym::MipsGp) {
919
18
    // Find GP-relative section with the lowest address
920
18
    // and use this address to calculate default _gp value.
921
149
    for (OutputSection *OS : OutputSections) {
922
149
      if (OS->Flags & SHF_MIPS_GPREL) {
923
18
        ElfSym::MipsGp->Section = OS;
924
18
        ElfSym::MipsGp->Value = 0x7ff0;
925
18
        break;
926
18
      }
927
149
    }
928
18
  }
929
27
}
930
931
// We want to find how similar two ranks are.
932
// The more branches in getSectionRank that match, the more similar they are.
933
// Since each branch corresponds to a bit flag, we can just use
934
// countLeadingZeros.
935
13.5k
static int getRankProximityAux(OutputSection *A, OutputSection *B) {
936
13.5k
  return countLeadingZeros(A->SortRank ^ B->SortRank);
937
13.5k
}
938
939
18.9k
static int getRankProximity(OutputSection *A, BaseCommand *B) {
940
18.9k
  if (auto *Sec = dyn_cast<OutputSection>(B))
941
18.6k
    if (Sec->Live)
942
13.5k
      return getRankProximityAux(A, Sec);
943
5.40k
  return -1;
944
5.40k
}
945
946
// When placing orphan sections, we want to place them after symbol assignments
947
// so that an orphan after
948
//   begin_foo = .;
949
//   foo : { *(foo) }
950
//   end_foo = .;
951
// doesn't break the intended meaning of the begin/end symbols.
952
// We don't want to go over sections since findOrphanPos is the
953
// one in charge of deciding the order of the sections.
954
// We don't want to go over changes to '.', since doing so in
955
//  rx_sec : { *(rx_sec) }
956
//  . = ALIGN(0x1000);
957
//  /* The RW PT_LOAD starts here*/
958
//  rw_sec : { *(rw_sec) }
959
// would mean that the RW PT_LOAD would become unaligned.
960
315
static bool shouldSkip(BaseCommand *Cmd) {
961
315
  if (isa<OutputSection>(Cmd))
962
219
    return false;
963
96
  if (auto *Assign = dyn_cast<SymbolAssignment>(Cmd))
964
95
    return Assign->Name != ".";
965
1
  return true;
966
1
}
967
968
// We want to place orphan sections so that they share as much
969
// characteristics with their neighbors as possible. For example, if
970
// both are rw, or both are tls.
971
template <typename ELFT>
972
static std::vector<BaseCommand *>::iterator
973
findOrphanPos(std::vector<BaseCommand *>::iterator B,
974
1.04k
              std::vector<BaseCommand *>::iterator E) {
975
1.04k
  OutputSection *Sec = cast<OutputSection>(*E);
976
1.04k
977
1.04k
  // Find the first element that has as close a rank as possible.
978
7.71k
  auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
979
7.71k
    return getRankProximity(Sec, A) < getRankProximity(Sec, B);
980
7.71k
  });
Writer.cpp:std::__1::__wrap_iter<lld::elf::BaseCommand**> findOrphanPos<llvm::object::ELFType<(llvm::support::endianness)1, false> >(std::__1::__wrap_iter<lld::elf::BaseCommand**>, std::__1::__wrap_iter<lld::elf::BaseCommand**>)::'lambda'(lld::elf::BaseCommand*, lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*, lld::elf::BaseCommand*) const
Line
Count
Source
978
821
  auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
979
821
    return getRankProximity(Sec, A) < getRankProximity(Sec, B);
980
821
  });
Writer.cpp:std::__1::__wrap_iter<lld::elf::BaseCommand**> findOrphanPos<llvm::object::ELFType<(llvm::support::endianness)0, false> >(std::__1::__wrap_iter<lld::elf::BaseCommand**>, std::__1::__wrap_iter<lld::elf::BaseCommand**>)::'lambda'(lld::elf::BaseCommand*, lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*, lld::elf::BaseCommand*) const
Line
Count
Source
978
158
  auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
979
158
    return getRankProximity(Sec, A) < getRankProximity(Sec, B);
980
158
  });
Writer.cpp:std::__1::__wrap_iter<lld::elf::BaseCommand**> findOrphanPos<llvm::object::ELFType<(llvm::support::endianness)1, true> >(std::__1::__wrap_iter<lld::elf::BaseCommand**>, std::__1::__wrap_iter<lld::elf::BaseCommand**>)::'lambda'(lld::elf::BaseCommand*, lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*, lld::elf::BaseCommand*) const
Line
Count
Source
978
6.59k
  auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
979
6.59k
    return getRankProximity(Sec, A) < getRankProximity(Sec, B);
980
6.59k
  });
Writer.cpp:std::__1::__wrap_iter<lld::elf::BaseCommand**> findOrphanPos<llvm::object::ELFType<(llvm::support::endianness)0, true> >(std::__1::__wrap_iter<lld::elf::BaseCommand**>, std::__1::__wrap_iter<lld::elf::BaseCommand**>)::'lambda'(lld::elf::BaseCommand*, lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*, lld::elf::BaseCommand*) const
Line
Count
Source
978
137
  auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
979
137
    return getRankProximity(Sec, A) < getRankProximity(Sec, B);
980
137
  });
981
1.04k
  if (I == E)
982
25
    return E;
983
1.02k
984
1.02k
  // Consider all existing sections with the same proximity.
985
1.02k
  int Proximity = getRankProximity(Sec, *I);
986
7.37k
  for (; I != E; 
++I6.35k
) {
987
6.46k
    auto *CurSec = dyn_cast<OutputSection>(*I);
988
6.46k
    if (!CurSec || 
!CurSec->Live6.29k
)
989
3.99k
      continue;
990
2.47k
    if (getRankProximity(Sec, CurSec) != Proximity ||
991
2.47k
        
Sec->SortRank < CurSec->SortRank2.40k
)
992
106
      break;
993
2.47k
  }
994
1.02k
995
7.77k
  auto IsLiveSection = [](BaseCommand *Cmd) {
996
7.77k
    auto *OS = dyn_cast<OutputSection>(Cmd);
997
7.77k
    return OS && 
OS->Live7.58k
;
998
7.77k
  };
Writer.cpp:std::__1::__wrap_iter<lld::elf::BaseCommand**> findOrphanPos<llvm::object::ELFType<(llvm::support::endianness)1, false> >(std::__1::__wrap_iter<lld::elf::BaseCommand**>, std::__1::__wrap_iter<lld::elf::BaseCommand**>)::'lambda'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
995
691
  auto IsLiveSection = [](BaseCommand *Cmd) {
996
691
    auto *OS = dyn_cast<OutputSection>(Cmd);
997
691
    return OS && OS->Live;
998
691
  };
Writer.cpp:std::__1::__wrap_iter<lld::elf::BaseCommand**> findOrphanPos<llvm::object::ELFType<(llvm::support::endianness)0, false> >(std::__1::__wrap_iter<lld::elf::BaseCommand**>, std::__1::__wrap_iter<lld::elf::BaseCommand**>)::'lambda'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
995
42
  auto IsLiveSection = [](BaseCommand *Cmd) {
996
42
    auto *OS = dyn_cast<OutputSection>(Cmd);
997
42
    return OS && OS->Live;
998
42
  };
Writer.cpp:std::__1::__wrap_iter<lld::elf::BaseCommand**> findOrphanPos<llvm::object::ELFType<(llvm::support::endianness)1, true> >(std::__1::__wrap_iter<lld::elf::BaseCommand**>, std::__1::__wrap_iter<lld::elf::BaseCommand**>)::'lambda'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
995
7.01k
  auto IsLiveSection = [](BaseCommand *Cmd) {
996
7.01k
    auto *OS = dyn_cast<OutputSection>(Cmd);
997
7.01k
    return OS && 
OS->Live6.81k
;
998
7.01k
  };
Writer.cpp:std::__1::__wrap_iter<lld::elf::BaseCommand**> findOrphanPos<llvm::object::ELFType<(llvm::support::endianness)0, true> >(std::__1::__wrap_iter<lld::elf::BaseCommand**>, std::__1::__wrap_iter<lld::elf::BaseCommand**>)::'lambda'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
995
31
  auto IsLiveSection = [](BaseCommand *Cmd) {
996
31
    auto *OS = dyn_cast<OutputSection>(Cmd);
997
31
    return OS && OS->Live;
998
31
  };
999
1.02k
1000
1.02k
  auto J = std::find_if(llvm::make_reverse_iterator(I),
1001
1.02k
                        llvm::make_reverse_iterator(B), IsLiveSection);
1002
1.02k
  I = J.base();
1003
1.02k
1004
1.02k
  // As a special case, if the orphan section is the last section, put
1005
1.02k
  // it at the very end, past any other commands.
1006
1.02k
  // This matches bfd's behavior and is convenient when the linker script fully
1007
1.02k
  // specifies the start of the file, but doesn't care about the end (the non
1008
1.02k
  // alloc sections for example).
1009
1.02k
  auto NextSec = std::find_if(I, E, IsLiveSection);
1010
1.02k
  if (NextSec == E)
1011
914
    return E;
1012
106
1013
109
  
while (106
I != E && shouldSkip(*I))
1014
3
    ++I;
1015
106
  return I;
1016
106
}
Writer.cpp:std::__1::__wrap_iter<lld::elf::BaseCommand**> findOrphanPos<llvm::object::ELFType<(llvm::support::endianness)1, false> >(std::__1::__wrap_iter<lld::elf::BaseCommand**>, std::__1::__wrap_iter<lld::elf::BaseCommand**>)
Line
Count
Source
974
81
              std::vector<BaseCommand *>::iterator E) {
975
81
  OutputSection *Sec = cast<OutputSection>(*E);
976
81
977
81
  // Find the first element that has as close a rank as possible.
978
81
  auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
979
81
    return getRankProximity(Sec, A) < getRankProximity(Sec, B);
980
81
  });
981
81
  if (I == E)
982
0
    return E;
983
81
984
81
  // Consider all existing sections with the same proximity.
985
81
  int Proximity = getRankProximity(Sec, *I);
986
764
  for (; I != E; 
++I683
) {
987
686
    auto *CurSec = dyn_cast<OutputSection>(*I);
988
686
    if (!CurSec || !CurSec->Live)
989
380
      continue;
990
306
    if (getRankProximity(Sec, CurSec) != Proximity ||
991
306
        
Sec->SortRank < CurSec->SortRank304
)
992
3
      break;
993
306
  }
994
81
995
81
  auto IsLiveSection = [](BaseCommand *Cmd) {
996
81
    auto *OS = dyn_cast<OutputSection>(Cmd);
997
81
    return OS && OS->Live;
998
81
  };
999
81
1000
81
  auto J = std::find_if(llvm::make_reverse_iterator(I),
1001
81
                        llvm::make_reverse_iterator(B), IsLiveSection);
1002
81
  I = J.base();
1003
81
1004
81
  // As a special case, if the orphan section is the last section, put
1005
81
  // it at the very end, past any other commands.
1006
81
  // This matches bfd's behavior and is convenient when the linker script fully
1007
81
  // specifies the start of the file, but doesn't care about the end (the non
1008
81
  // alloc sections for example).
1009
81
  auto NextSec = std::find_if(I, E, IsLiveSection);
1010
81
  if (NextSec == E)
1011
78
    return E;
1012
3
1013
3
  while (I != E && shouldSkip(*I))
1014
0
    ++I;
1015
3
  return I;
1016
3
}
Writer.cpp:std::__1::__wrap_iter<lld::elf::BaseCommand**> findOrphanPos<llvm::object::ELFType<(llvm::support::endianness)0, false> >(std::__1::__wrap_iter<lld::elf::BaseCommand**>, std::__1::__wrap_iter<lld::elf::BaseCommand**>)
Line
Count
Source
974
18
              std::vector<BaseCommand *>::iterator E) {
975
18
  OutputSection *Sec = cast<OutputSection>(*E);
976
18
977
18
  // Find the first element that has as close a rank as possible.
978
18
  auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
979
18
    return getRankProximity(Sec, A) < getRankProximity(Sec, B);
980
18
  });
981
18
  if (I == E)
982
0
    return E;
983
18
984
18
  // Consider all existing sections with the same proximity.
985
18
  int Proximity = getRankProximity(Sec, *I);
986
102
  for (; I != E; 
++I84
) {
987
85
    auto *CurSec = dyn_cast<OutputSection>(*I);
988
85
    if (!CurSec || !CurSec->Live)
989
36
      continue;
990
49
    if (getRankProximity(Sec, CurSec) != Proximity ||
991
49
        Sec->SortRank < CurSec->SortRank)
992
1
      break;
993
49
  }
994
18
995
18
  auto IsLiveSection = [](BaseCommand *Cmd) {
996
18
    auto *OS = dyn_cast<OutputSection>(Cmd);
997
18
    return OS && OS->Live;
998
18
  };
999
18
1000
18
  auto J = std::find_if(llvm::make_reverse_iterator(I),
1001
18
                        llvm::make_reverse_iterator(B), IsLiveSection);
1002
18
  I = J.base();
1003
18
1004
18
  // As a special case, if the orphan section is the last section, put
1005
18
  // it at the very end, past any other commands.
1006
18
  // This matches bfd's behavior and is convenient when the linker script fully
1007
18
  // specifies the start of the file, but doesn't care about the end (the non
1008
18
  // alloc sections for example).
1009
18
  auto NextSec = std::find_if(I, E, IsLiveSection);
1010
18
  if (NextSec == E)
1011
17
    return E;
1012
1
1013
1
  while (I != E && shouldSkip(*I))
1014
0
    ++I;
1015
1
  return I;
1016
1
}
Writer.cpp:std::__1::__wrap_iter<lld::elf::BaseCommand**> findOrphanPos<llvm::object::ELFType<(llvm::support::endianness)1, true> >(std::__1::__wrap_iter<lld::elf::BaseCommand**>, std::__1::__wrap_iter<lld::elf::BaseCommand**>)
Line
Count
Source
974
935
              std::vector<BaseCommand *>::iterator E) {
975
935
  OutputSection *Sec = cast<OutputSection>(*E);
976
935
977
935
  // Find the first element that has as close a rank as possible.
978
935
  auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
979
935
    return getRankProximity(Sec, A) < getRankProximity(Sec, B);
980
935
  });
981
935
  if (I == E)
982
25
    return E;
983
910
984
910
  // Consider all existing sections with the same proximity.
985
910
  int Proximity = getRankProximity(Sec, *I);
986
6.43k
  for (; I != E; 
++I5.52k
) {
987
5.62k
    auto *CurSec = dyn_cast<OutputSection>(*I);
988
5.62k
    if (!CurSec || 
!CurSec->Live5.46k
)
989
3.54k
      continue;
990
2.08k
    if (getRankProximity(Sec, CurSec) != Proximity ||
991
2.08k
        
Sec->SortRank < CurSec->SortRank2.01k
)
992
99
      break;
993
2.08k
  }
994
910
995
910
  auto IsLiveSection = [](BaseCommand *Cmd) {
996
910
    auto *OS = dyn_cast<OutputSection>(Cmd);
997
910
    return OS && OS->Live;
998
910
  };
999
910
1000
910
  auto J = std::find_if(llvm::make_reverse_iterator(I),
1001
910
                        llvm::make_reverse_iterator(B), IsLiveSection);
1002
910
  I = J.base();
1003
910
1004
910
  // As a special case, if the orphan section is the last section, put
1005
910
  // it at the very end, past any other commands.
1006
910
  // This matches bfd's behavior and is convenient when the linker script fully
1007
910
  // specifies the start of the file, but doesn't care about the end (the non
1008
910
  // alloc sections for example).
1009
910
  auto NextSec = std::find_if(I, E, IsLiveSection);
1010
910
  if (NextSec == E)
1011
811
    return E;
1012
99
1013
102
  
while (99
I != E && shouldSkip(*I))
1014
3
    ++I;
1015
99
  return I;
1016
99
}
Writer.cpp:std::__1::__wrap_iter<lld::elf::BaseCommand**> findOrphanPos<llvm::object::ELFType<(llvm::support::endianness)0, true> >(std::__1::__wrap_iter<lld::elf::BaseCommand**>, std::__1::__wrap_iter<lld::elf::BaseCommand**>)
Line
Count
Source
974
11
              std::vector<BaseCommand *>::iterator E) {
975
11
  OutputSection *Sec = cast<OutputSection>(*E);
976
11
977
11
  // Find the first element that has as close a rank as possible.
978
11
  auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
979
11
    return getRankProximity(Sec, A) < getRankProximity(Sec, B);
980
11
  });
981
11
  if (I == E)
982
0
    return E;
983
11
984
11
  // Consider all existing sections with the same proximity.
985
11
  int Proximity = getRankProximity(Sec, *I);
986
73
  for (; I != E; 
++I62
) {
987
65
    auto *CurSec = dyn_cast<OutputSection>(*I);
988
65
    if (!CurSec || !CurSec->Live)
989
32
      continue;
990
33
    if (getRankProximity(Sec, CurSec) != Proximity ||
991
33
        
Sec->SortRank < CurSec->SortRank32
)
992
3
      break;
993
33
  }
994
11
995
11
  auto IsLiveSection = [](BaseCommand *Cmd) {
996
11
    auto *OS = dyn_cast<OutputSection>(Cmd);
997
11
    return OS && OS->Live;
998
11
  };
999
11
1000
11
  auto J = std::find_if(llvm::make_reverse_iterator(I),
1001
11
                        llvm::make_reverse_iterator(B), IsLiveSection);
1002
11
  I = J.base();
1003
11
1004
11
  // As a special case, if the orphan section is the last section, put
1005
11
  // it at the very end, past any other commands.
1006
11
  // This matches bfd's behavior and is convenient when the linker script fully
1007
11
  // specifies the start of the file, but doesn't care about the end (the non
1008
11
  // alloc sections for example).
1009
11
  auto NextSec = std::find_if(I, E, IsLiveSection);
1010
11
  if (NextSec == E)
1011
8
    return E;
1012
3
1013
3
  while (I != E && shouldSkip(*I))
1014
0
    ++I;
1015
3
  return I;
1016
3
}
1017
1018
// If no layout was provided by linker script, we want to apply default
1019
// sorting for special input sections and handle --symbol-ordering-file.
1020
681
template <class ELFT> void Writer<ELFT>::sortInputSections() {
1021
681
  assert(!Script->HasSectionsCommand);
1022
681
1023
681
  // Sort input sections by priority using the list provided
1024
681
  // by --symbol-ordering-file.
1025
681
  DenseMap<SectionBase *, int> Order = buildSectionOrder();
1026
681
  if (!Order.empty())
1027
2
    for (BaseCommand *Base : Script->SectionCommands)
1028
24
      if (auto *Sec = dyn_cast<OutputSection>(Base))
1029
24
        if (Sec->Live)
1030
13
          
Sec->sort([&](InputSectionBase *S) 10
{ return Order.lookup(S); });
Unexecuted instantiation: Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::sortInputSections()::'lambda'(lld::elf::InputSectionBase*)::operator()(lld::elf::InputSectionBase*) const
Unexecuted instantiation: Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::sortInputSections()::'lambda'(lld::elf::InputSectionBase*)::operator()(lld::elf::InputSectionBase*) const
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::sortInputSections()::'lambda'(lld::elf::InputSectionBase*)::operator()(lld::elf::InputSectionBase*) const
Line
Count
Source
1030
13
          Sec->sort([&](InputSectionBase *S) { return Order.lookup(S); });
Unexecuted instantiation: Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::sortInputSections()::'lambda'(lld::elf::InputSectionBase*)::operator()(lld::elf::InputSectionBase*) const
1031
681
1032
681
  // Sort input sections by section name suffixes for
1033
681
  // __attribute__((init_priority(N))).
1034
681
  if (OutputSection *Sec = findSection(".init_array"))
1035
4
    Sec->sortInitFini();
1036
681
  if (OutputSection *Sec = findSection(".fini_array"))
1037
3
    Sec->sortInitFini();
1038
681
1039
681
  // Sort input sections by the special rule for .ctors and .dtors.
1040
681
  if (OutputSection *Sec = findSection(".ctors"))
1041
3
    Sec->sortCtorsDtors();
1042
681
  if (OutputSection *Sec = findSection(".dtors"))
1043
3
    Sec->sortCtorsDtors();
1044
681
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::sortInputSections()
Line
Count
Source
1020
101
template <class ELFT> void Writer<ELFT>::sortInputSections() {
1021
101
  assert(!Script->HasSectionsCommand);
1022
101
1023
101
  // Sort input sections by priority using the list provided
1024
101
  // by --symbol-ordering-file.
1025
101
  DenseMap<SectionBase *, int> Order = buildSectionOrder();
1026
101
  if (!Order.empty())
1027
0
    for (BaseCommand *Base : Script->SectionCommands)
1028
0
      if (auto *Sec = dyn_cast<OutputSection>(Base))
1029
0
        if (Sec->Live)
1030
0
          Sec->sort([&](InputSectionBase *S) { return Order.lookup(S); });
1031
101
1032
101
  // Sort input sections by section name suffixes for
1033
101
  // __attribute__((init_priority(N))).
1034
101
  if (OutputSection *Sec = findSection(".init_array"))
1035
0
    Sec->sortInitFini();
1036
101
  if (OutputSection *Sec = findSection(".fini_array"))
1037
0
    Sec->sortInitFini();
1038
101
1039
101
  // Sort input sections by the special rule for .ctors and .dtors.
1040
101
  if (OutputSection *Sec = findSection(".ctors"))
1041
0
    Sec->sortCtorsDtors();
1042
101
  if (OutputSection *Sec = findSection(".dtors"))
1043
0
    Sec->sortCtorsDtors();
1044
101
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::sortInputSections()
Line
Count
Source
1020
43
template <class ELFT> void Writer<ELFT>::sortInputSections() {
1021
43
  assert(!Script->HasSectionsCommand);
1022
43
1023
43
  // Sort input sections by priority using the list provided
1024
43
  // by --symbol-ordering-file.
1025
43
  DenseMap<SectionBase *, int> Order = buildSectionOrder();
1026
43
  if (!Order.empty())
1027
0
    for (BaseCommand *Base : Script->SectionCommands)
1028
0
      if (auto *Sec = dyn_cast<OutputSection>(Base))
1029
0
        if (Sec->Live)
1030
0
          Sec->sort([&](InputSectionBase *S) { return Order.lookup(S); });
1031
43
1032
43
  // Sort input sections by section name suffixes for
1033
43
  // __attribute__((init_priority(N))).
1034
43
  if (OutputSection *Sec = findSection(".init_array"))
1035
0
    Sec->sortInitFini();
1036
43
  if (OutputSection *Sec = findSection(".fini_array"))
1037
0
    Sec->sortInitFini();
1038
43
1039
43
  // Sort input sections by the special rule for .ctors and .dtors.
1040
43
  if (OutputSection *Sec = findSection(".ctors"))
1041
0
    Sec->sortCtorsDtors();
1042
43
  if (OutputSection *Sec = findSection(".dtors"))
1043
0
    Sec->sortCtorsDtors();
1044
43
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::sortInputSections()
Line
Count
Source
1020
512
template <class ELFT> void Writer<ELFT>::sortInputSections() {
1021
512
  assert(!Script->HasSectionsCommand);
1022
512
1023
512
  // Sort input sections by priority using the list provided
1024
512
  // by --symbol-ordering-file.
1025
512
  DenseMap<SectionBase *, int> Order = buildSectionOrder();
1026
512
  if (!Order.empty())
1027
2
    for (BaseCommand *Base : Script->SectionCommands)
1028
24
      if (auto *Sec = dyn_cast<OutputSection>(Base))
1029
24
        if (Sec->Live)
1030
10
          Sec->sort([&](InputSectionBase *S) { return Order.lookup(S); });
1031
512
1032
512
  // Sort input sections by section name suffixes for
1033
512
  // __attribute__((init_priority(N))).
1034
512
  if (OutputSection *Sec = findSection(".init_array"))
1035
4
    Sec->sortInitFini();
1036
512
  if (OutputSection *Sec = findSection(".fini_array"))
1037
3
    Sec->sortInitFini();
1038
512
1039
512
  // Sort input sections by the special rule for .ctors and .dtors.
1040
512
  if (OutputSection *Sec = findSection(".ctors"))
1041
3
    Sec->sortCtorsDtors();
1042
512
  if (OutputSection *Sec = findSection(".dtors"))
1043
3
    Sec->sortCtorsDtors();
1044
512
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::sortInputSections()
Line
Count
Source
1020
25
template <class ELFT> void Writer<ELFT>::sortInputSections() {
1021
25
  assert(!Script->HasSectionsCommand);
1022
25
1023
25
  // Sort input sections by priority using the list provided
1024
25
  // by --symbol-ordering-file.
1025
25
  DenseMap<SectionBase *, int> Order = buildSectionOrder();
1026
25
  if (!Order.empty())
1027
0
    for (BaseCommand *Base : Script->SectionCommands)
1028
0
      if (auto *Sec = dyn_cast<OutputSection>(Base))
1029
0
        if (Sec->Live)
1030
0
          Sec->sort([&](InputSectionBase *S) { return Order.lookup(S); });
1031
25
1032
25
  // Sort input sections by section name suffixes for
1033
25
  // __attribute__((init_priority(N))).
1034
25
  if (OutputSection *Sec = findSection(".init_array"))
1035
0
    Sec->sortInitFini();
1036
25
  if (OutputSection *Sec = findSection(".fini_array"))
1037
0
    Sec->sortInitFini();
1038
25
1039
25
  // Sort input sections by the special rule for .ctors and .dtors.
1040
25
  if (OutputSection *Sec = findSection(".ctors"))
1041
0
    Sec->sortCtorsDtors();
1042
25
  if (OutputSection *Sec = findSection(".dtors"))
1043
0
    Sec->sortCtorsDtors();
1044
25
}
1045
1046
887
template <class ELFT> void Writer<ELFT>::sortSections() {
1047
887
  Script->adjustSectionsBeforeSorting();
1048
887
1049
887
  // Don't sort if using -r. It is not necessary and we want to preserve the
1050
887
  // relative order for SHF_LINK_ORDER sections.
1051
887
  if (Config->Relocatable)
1052
28
    return;
1053
859
1054
859
  for (BaseCommand *Base : Script->SectionCommands)
1055
80.1k
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1056
80.0k
      Sec->SortRank = getSectionRank(Sec);
1057
859
1058
859
  if (!Script->HasSectionsCommand) {
1059
681
    sortInputSections();
1060
681
1061
681
    // We know that all the OutputSections are contiguous in this case.
1062
681
    auto E = Script->SectionCommands.end();
1063
681
    auto I = Script->SectionCommands.begin();
1064
1.37k
    auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::sortSections()::'lambda'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1064
202
    auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::sortSections()::'lambda'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1064
86
    auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::sortSections()::'lambda'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1064
1.03k
    auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::sortSections()::'lambda'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1064
50
    auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
1065
681
    I = std::find_if(I, E, IsSection);
1066
681
    E = std::find_if(llvm::make_reverse_iterator(E),
1067
681
                     llvm::make_reverse_iterator(I), IsSection)
1068
681
            .base();
1069
681
    std::stable_sort(I, E, compareSections);
1070
681
    return;
1071
681
  }
1072
178
1073
178
  // Orphan sections are sections present in the input files which are
1074
178
  // not explicitly placed into the output file by the linker script.
1075
178
  //
1076
178
  // The sections in the linker script are already in the correct
1077
178
  // order. We have to figuere out where to insert the orphan
1078
178
  // sections.
1079
178
  //
1080
178
  // The order of the sections in the script is arbitrary and may not agree with
1081
178
  // compareSections. This means that we cannot easily define a strict weak
1082
178
  // ordering. To see why, consider a comparison of a section in the script and
1083
178
  // one not in the script. We have a two simple options:
1084
178
  // * Make them equivalent (a is not less than b, and b is not less than a).
1085
178
  //   The problem is then that equivalence has to be transitive and we can
1086
178
  //   have sections a, b and c with only b in a script and a less than c
1087
178
  //   which breaks this property.
1088
178
  // * Use compareSectionsNonScript. Given that the script order doesn't have
1089
178
  //   to match, we can end up with sections a, b, c, d where b and c are in the
1090
178
  //   script and c is compareSectionsNonScript less than b. In which case d
1091
178
  //   can be equivalent to c, a to b and d < a. As a concrete example:
1092
178
  //   .a (rx) # not in script
1093
178
  //   .b (rx) # in script
1094
178
  //   .c (ro) # in script
1095
178
  //   .d (ro) # not in script
1096
178
  //
1097
178
  // The way we define an order then is:
1098
178
  // *  Sort only the orphan sections. They are in the end right now.
1099
178
  // *  Move each orphan section to its preferred position. We try
1100
178
  //    to put each section in the last position where it it can share
1101
178
  //    a PT_LOAD.
1102
178
  //
1103
178
  // There is some ambiguity as to where exactly a new entry should be
1104
178
  // inserted, because Commands contains not only output section
1105
178
  // commands but also other types of commands such as symbol assignment
1106
178
  // expressions. There's no correct answer here due to the lack of the
1107
178
  // formal specification of the linker script. We use heuristics to
1108
178
  // determine whether a new output command should be added before or
1109
178
  // after another commands. For the details, look at shouldSkip
1110
178
  // function.
1111
178
1112
178
  auto I = Script->SectionCommands.begin();
1113
178
  auto E = Script->SectionCommands.end();
1114
611
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1115
611
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1116
474
      return Sec->Live && 
Sec->SectionIndex == INT_MAX448
;
1117
137
    return false;
1118
137
  });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::sortSections()::'lambda0'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1114
67
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1115
67
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1116
59
      return Sec->Live && 
Sec->SectionIndex == INT_MAX56
;
1117
8
    return false;
1118
8
  });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::sortSections()::'lambda0'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1114
6
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1115
6
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1116
6
      return Sec->Live && Sec->SectionIndex == INT_MAX;
1117
0
    return false;
1118
0
  });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::sortSections()::'lambda0'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1114
532
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1115
532
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1116
404
      return Sec->Live && 
Sec->SectionIndex == INT_MAX381
;
1117
128
    return false;
1118
128
  });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::sortSections()::'lambda0'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1114
6
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1115
6
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1116
5
      return Sec->Live && Sec->SectionIndex == INT_MAX;
1117
1
    return false;
1118
1
  });
1119
178
1120
178
  // Sort the orphan sections.
1121
178
  std::stable_sort(NonScriptI, E, compareSections);
1122
178
1123
178
  // As a horrible special case, skip the first . assignment if it is before any
1124
178
  // section. We do this because it is common to set a load address by starting
1125
178
  // the script with ". = 0xabcd" and the expectation is that every section is
1126
178
  // after that.
1127
178
  auto FirstSectionOrDotAssignment =
1128
206
      std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::sortSections()::'lambda1'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1128
14
      std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::sortSections()::'lambda1'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1128
3
      std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::sortSections()::'lambda1'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1128
187
      std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::sortSections()::'lambda1'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1128
2
      std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1129
178
  if (FirstSectionOrDotAssignment != E &&
1130
178
      isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1131
55
    ++FirstSectionOrDotAssignment;
1132
178
  I = FirstSectionOrDotAssignment;
1133
178
1134
1.22k
  while (NonScriptI != E) {
1135
1.04k
    auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1136
1.04k
    OutputSection *Orphan = cast<OutputSection>(*NonScriptI);
1137
1.04k
1138
1.04k
    // As an optimization, find all sections with the same sort rank
1139
1.04k
    // and insert them with one rotate.
1140
1.04k
    unsigned Rank = Orphan->SortRank;
1141
2.29k
    auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1142
2.29k
      return cast<OutputSection>(Cmd)->SortRank != Rank;
1143
2.29k
    });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::sortSections()::'lambda2'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1141
207
    auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1142
207
      return cast<OutputSection>(Cmd)->SortRank != Rank;
1143
207
    });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::sortSections()::'lambda2'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1141
47
    auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1142
47
      return cast<OutputSection>(Cmd)->SortRank != Rank;
1143
47
    });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::sortSections()::'lambda2'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1141
2.00k
    auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1142
2.00k
      return cast<OutputSection>(Cmd)->SortRank != Rank;
1143
2.00k
    });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::sortSections()::'lambda2'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1141
39
    auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1142
39
      return cast<OutputSection>(Cmd)->SortRank != Rank;
1143
39
    });
1144
1.04k
    std::rotate(Pos, NonScriptI, End);
1145
1.04k
    NonScriptI = End;
1146
1.04k
  }
1147
178
1148
178
  Script->adjustSectionsAfterSorting();
1149
178
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::sortSections()
Line
Count
Source
1046
116
template <class ELFT> void Writer<ELFT>::sortSections() {
1047
116
  Script->adjustSectionsBeforeSorting();
1048
116
1049
116
  // Don't sort if using -r. It is not necessary and we want to preserve the
1050
116
  // relative order for SHF_LINK_ORDER sections.
1051
116
  if (Config->Relocatable)
1052
1
    return;
1053
115
1054
115
  for (BaseCommand *Base : Script->SectionCommands)
1055
2.10k
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1056
2.09k
      Sec->SortRank = getSectionRank(Sec);
1057
115
1058
115
  if (!Script->HasSectionsCommand) {
1059
101
    sortInputSections();
1060
101
1061
101
    // We know that all the OutputSections are contiguous in this case.
1062
101
    auto E = Script->SectionCommands.end();
1063
101
    auto I = Script->SectionCommands.begin();
1064
101
    auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
1065
101
    I = std::find_if(I, E, IsSection);
1066
101
    E = std::find_if(llvm::make_reverse_iterator(E),
1067
101
                     llvm::make_reverse_iterator(I), IsSection)
1068
101
            .base();
1069
101
    std::stable_sort(I, E, compareSections);
1070
101
    return;
1071
101
  }
1072
14
1073
14
  // Orphan sections are sections present in the input files which are
1074
14
  // not explicitly placed into the output file by the linker script.
1075
14
  //
1076
14
  // The sections in the linker script are already in the correct
1077
14
  // order. We have to figuere out where to insert the orphan
1078
14
  // sections.
1079
14
  //
1080
14
  // The order of the sections in the script is arbitrary and may not agree with
1081
14
  // compareSections. This means that we cannot easily define a strict weak
1082
14
  // ordering. To see why, consider a comparison of a section in the script and
1083
14
  // one not in the script. We have a two simple options:
1084
14
  // * Make them equivalent (a is not less than b, and b is not less than a).
1085
14
  //   The problem is then that equivalence has to be transitive and we can
1086
14
  //   have sections a, b and c with only b in a script and a less than c
1087
14
  //   which breaks this property.
1088
14
  // * Use compareSectionsNonScript. Given that the script order doesn't have
1089
14
  //   to match, we can end up with sections a, b, c, d where b and c are in the
1090
14
  //   script and c is compareSectionsNonScript less than b. In which case d
1091
14
  //   can be equivalent to c, a to b and d < a. As a concrete example:
1092
14
  //   .a (rx) # not in script
1093
14
  //   .b (rx) # in script
1094
14
  //   .c (ro) # in script
1095
14
  //   .d (ro) # not in script
1096
14
  //
1097
14
  // The way we define an order then is:
1098
14
  // *  Sort only the orphan sections. They are in the end right now.
1099
14
  // *  Move each orphan section to its preferred position. We try
1100
14
  //    to put each section in the last position where it it can share
1101
14
  //    a PT_LOAD.
1102
14
  //
1103
14
  // There is some ambiguity as to where exactly a new entry should be
1104
14
  // inserted, because Commands contains not only output section
1105
14
  // commands but also other types of commands such as symbol assignment
1106
14
  // expressions. There's no correct answer here due to the lack of the
1107
14
  // formal specification of the linker script. We use heuristics to
1108
14
  // determine whether a new output command should be added before or
1109
14
  // after another commands. For the details, look at shouldSkip
1110
14
  // function.
1111
14
1112
14
  auto I = Script->SectionCommands.begin();
1113
14
  auto E = Script->SectionCommands.end();
1114
14
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1115
14
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1116
14
      return Sec->Live && Sec->SectionIndex == INT_MAX;
1117
14
    return false;
1118
14
  });
1119
14
1120
14
  // Sort the orphan sections.
1121
14
  std::stable_sort(NonScriptI, E, compareSections);
1122
14
1123
14
  // As a horrible special case, skip the first . assignment if it is before any
1124
14
  // section. We do this because it is common to set a load address by starting
1125
14
  // the script with ". = 0xabcd" and the expectation is that every section is
1126
14
  // after that.
1127
14
  auto FirstSectionOrDotAssignment =
1128
14
      std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1129
14
  if (FirstSectionOrDotAssignment != E &&
1130
14
      isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1131
8
    ++FirstSectionOrDotAssignment;
1132
14
  I = FirstSectionOrDotAssignment;
1133
14
1134
95
  while (NonScriptI != E) {
1135
81
    auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1136
81
    OutputSection *Orphan = cast<OutputSection>(*NonScriptI);
1137
81
1138
81
    // As an optimization, find all sections with the same sort rank
1139
81
    // and insert them with one rotate.
1140
81
    unsigned Rank = Orphan->SortRank;
1141
81
    auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1142
81
      return cast<OutputSection>(Cmd)->SortRank != Rank;
1143
81
    });
1144
81
    std::rotate(Pos, NonScriptI, End);
1145
81
    NonScriptI = End;
1146
81
  }
1147
14
1148
14
  Script->adjustSectionsAfterSorting();
1149
14
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::sortSections()
Line
Count
Source
1046
50
template <class ELFT> void Writer<ELFT>::sortSections() {
1047
50
  Script->adjustSectionsBeforeSorting();
1048
50
1049
50
  // Don't sort if using -r. It is not necessary and we want to preserve the
1050
50
  // relative order for SHF_LINK_ORDER sections.
1051
50
  if (Config->Relocatable)
1052
4
    return;
1053
46
1054
46
  for (BaseCommand *Base : Script->SectionCommands)
1055
896
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1056
896
      Sec->SortRank = getSectionRank(Sec);
1057
46
1058
46
  if (!Script->HasSectionsCommand) {
1059
43
    sortInputSections();
1060
43
1061
43
    // We know that all the OutputSections are contiguous in this case.
1062
43
    auto E = Script->SectionCommands.end();
1063
43
    auto I = Script->SectionCommands.begin();
1064
43
    auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
1065
43
    I = std::find_if(I, E, IsSection);
1066
43
    E = std::find_if(llvm::make_reverse_iterator(E),
1067
43
                     llvm::make_reverse_iterator(I), IsSection)
1068
43
            .base();
1069
43
    std::stable_sort(I, E, compareSections);
1070
43
    return;
1071
43
  }
1072
3
1073
3
  // Orphan sections are sections present in the input files which are
1074
3
  // not explicitly placed into the output file by the linker script.
1075
3
  //
1076
3
  // The sections in the linker script are already in the correct
1077
3
  // order. We have to figuere out where to insert the orphan
1078
3
  // sections.
1079
3
  //
1080
3
  // The order of the sections in the script is arbitrary and may not agree with
1081
3
  // compareSections. This means that we cannot easily define a strict weak
1082
3
  // ordering. To see why, consider a comparison of a section in the script and
1083
3
  // one not in the script. We have a two simple options:
1084
3
  // * Make them equivalent (a is not less than b, and b is not less than a).
1085
3
  //   The problem is then that equivalence has to be transitive and we can
1086
3
  //   have sections a, b and c with only b in a script and a less than c
1087
3
  //   which breaks this property.
1088
3
  // * Use compareSectionsNonScript. Given that the script order doesn't have
1089
3
  //   to match, we can end up with sections a, b, c, d where b and c are in the
1090
3
  //   script and c is compareSectionsNonScript less than b. In which case d
1091
3
  //   can be equivalent to c, a to b and d < a. As a concrete example:
1092
3
  //   .a (rx) # not in script
1093
3
  //   .b (rx) # in script
1094
3
  //   .c (ro) # in script
1095
3
  //   .d (ro) # not in script
1096
3
  //
1097
3
  // The way we define an order then is:
1098
3
  // *  Sort only the orphan sections. They are in the end right now.
1099
3
  // *  Move each orphan section to its preferred position. We try
1100
3
  //    to put each section in the last position where it it can share
1101
3
  //    a PT_LOAD.
1102
3
  //
1103
3
  // There is some ambiguity as to where exactly a new entry should be
1104
3
  // inserted, because Commands contains not only output section
1105
3
  // commands but also other types of commands such as symbol assignment
1106
3
  // expressions. There's no correct answer here due to the lack of the
1107
3
  // formal specification of the linker script. We use heuristics to
1108
3
  // determine whether a new output command should be added before or
1109
3
  // after another commands. For the details, look at shouldSkip
1110
3
  // function.
1111
3
1112
3
  auto I = Script->SectionCommands.begin();
1113
3
  auto E = Script->SectionCommands.end();
1114
3
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1115
3
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1116
3
      return Sec->Live && Sec->SectionIndex == INT_MAX;
1117
3
    return false;
1118
3
  });
1119
3
1120
3
  // Sort the orphan sections.
1121
3
  std::stable_sort(NonScriptI, E, compareSections);
1122
3
1123
3
  // As a horrible special case, skip the first . assignment if it is before any
1124
3
  // section. We do this because it is common to set a load address by starting
1125
3
  // the script with ". = 0xabcd" and the expectation is that every section is
1126
3
  // after that.
1127
3
  auto FirstSectionOrDotAssignment =
1128
3
      std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1129
3
  if (FirstSectionOrDotAssignment != E &&
1130
3
      isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1131
0
    ++FirstSectionOrDotAssignment;
1132
3
  I = FirstSectionOrDotAssignment;
1133
3
1134
21
  while (NonScriptI != E) {
1135
18
    auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1136
18
    OutputSection *Orphan = cast<OutputSection>(*NonScriptI);
1137
18
1138
18
    // As an optimization, find all sections with the same sort rank
1139
18
    // and insert them with one rotate.
1140
18
    unsigned Rank = Orphan->SortRank;
1141
18
    auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1142
18
      return cast<OutputSection>(Cmd)->SortRank != Rank;
1143
18
    });
1144
18
    std::rotate(Pos, NonScriptI, End);
1145
18
    NonScriptI = End;
1146
18
  }
1147
3
1148
3
  Script->adjustSectionsAfterSorting();
1149
3
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::sortSections()
Line
Count
Source
1046
694
template <class ELFT> void Writer<ELFT>::sortSections() {
1047
694
  Script->adjustSectionsBeforeSorting();
1048
694
1049
694
  // Don't sort if using -r. It is not necessary and we want to preserve the
1050
694
  // relative order for SHF_LINK_ORDER sections.
1051
694
  if (Config->Relocatable)
1052
23
    return;
1053
671
1054
671
  for (BaseCommand *Base : Script->SectionCommands)
1055
76.6k
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1056
76.4k
      Sec->SortRank = getSectionRank(Sec);
1057
671
1058
671
  if (!Script->HasSectionsCommand) {
1059
512
    sortInputSections();
1060
512
1061
512
    // We know that all the OutputSections are contiguous in this case.
1062
512
    auto E = Script->SectionCommands.end();
1063
512
    auto I = Script->SectionCommands.begin();
1064
512
    auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
1065
512
    I = std::find_if(I, E, IsSection);
1066
512
    E = std::find_if(llvm::make_reverse_iterator(E),
1067
512
                     llvm::make_reverse_iterator(I), IsSection)
1068
512
            .base();
1069
512
    std::stable_sort(I, E, compareSections);
1070
512
    return;
1071
512
  }
1072
159
1073
159
  // Orphan sections are sections present in the input files which are
1074
159
  // not explicitly placed into the output file by the linker script.
1075
159
  //
1076
159
  // The sections in the linker script are already in the correct
1077
159
  // order. We have to figuere out where to insert the orphan
1078
159
  // sections.
1079
159
  //
1080
159
  // The order of the sections in the script is arbitrary and may not agree with
1081
159
  // compareSections. This means that we cannot easily define a strict weak
1082
159
  // ordering. To see why, consider a comparison of a section in the script and
1083
159
  // one not in the script. We have a two simple options:
1084
159
  // * Make them equivalent (a is not less than b, and b is not less than a).
1085
159
  //   The problem is then that equivalence has to be transitive and we can
1086
159
  //   have sections a, b and c with only b in a script and a less than c
1087
159
  //   which breaks this property.
1088
159
  // * Use compareSectionsNonScript. Given that the script order doesn't have
1089
159
  //   to match, we can end up with sections a, b, c, d where b and c are in the
1090
159
  //   script and c is compareSectionsNonScript less than b. In which case d
1091
159
  //   can be equivalent to c, a to b and d < a. As a concrete example:
1092
159
  //   .a (rx) # not in script
1093
159
  //   .b (rx) # in script
1094
159
  //   .c (ro) # in script
1095
159
  //   .d (ro) # not in script
1096
159
  //
1097
159
  // The way we define an order then is:
1098
159
  // *  Sort only the orphan sections. They are in the end right now.
1099
159
  // *  Move each orphan section to its preferred position. We try
1100
159
  //    to put each section in the last position where it it can share
1101
159
  //    a PT_LOAD.
1102
159
  //
1103
159
  // There is some ambiguity as to where exactly a new entry should be
1104
159
  // inserted, because Commands contains not only output section
1105
159
  // commands but also other types of commands such as symbol assignment
1106
159
  // expressions. There's no correct answer here due to the lack of the
1107
159
  // formal specification of the linker script. We use heuristics to
1108
159
  // determine whether a new output command should be added before or
1109
159
  // after another commands. For the details, look at shouldSkip
1110
159
  // function.
1111
159
1112
159
  auto I = Script->SectionCommands.begin();
1113
159
  auto E = Script->SectionCommands.end();
1114
159
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1115
159
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1116
159
      return Sec->Live && Sec->SectionIndex == INT_MAX;
1117
159
    return false;
1118
159
  });
1119
159
1120
159
  // Sort the orphan sections.
1121
159
  std::stable_sort(NonScriptI, E, compareSections);
1122
159
1123
159
  // As a horrible special case, skip the first . assignment if it is before any
1124
159
  // section. We do this because it is common to set a load address by starting
1125
159
  // the script with ". = 0xabcd" and the expectation is that every section is
1126
159
  // after that.
1127
159
  auto FirstSectionOrDotAssignment =
1128
159
      std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1129
159
  if (FirstSectionOrDotAssignment != E &&
1130
159
      isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1131
46
    ++FirstSectionOrDotAssignment;
1132
159
  I = FirstSectionOrDotAssignment;
1133
159
1134
1.09k
  while (NonScriptI != E) {
1135
935
    auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1136
935
    OutputSection *Orphan = cast<OutputSection>(*NonScriptI);
1137
935
1138
935
    // As an optimization, find all sections with the same sort rank
1139
935
    // and insert them with one rotate.
1140
935
    unsigned Rank = Orphan->SortRank;
1141
935
    auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1142
935
      return cast<OutputSection>(Cmd)->SortRank != Rank;
1143
935
    });
1144
935
    std::rotate(Pos, NonScriptI, End);
1145
935
    NonScriptI = End;
1146
935
  }
1147
159
1148
159
  Script->adjustSectionsAfterSorting();
1149
159
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::sortSections()
Line
Count
Source
1046
27
template <class ELFT> void Writer<ELFT>::sortSections() {
1047
27
  Script->adjustSectionsBeforeSorting();
1048
27
1049
27
  // Don't sort if using -r. It is not necessary and we want to preserve the
1050
27
  // relative order for SHF_LINK_ORDER sections.
1051
27
  if (Config->Relocatable)
1052
0
    return;
1053
27
1054
27
  for (BaseCommand *Base : Script->SectionCommands)
1055
533
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1056
532
      Sec->SortRank = getSectionRank(Sec);
1057
27
1058
27
  if (!Script->HasSectionsCommand) {
1059
25
    sortInputSections();
1060
25
1061
25
    // We know that all the OutputSections are contiguous in this case.
1062
25
    auto E = Script->SectionCommands.end();
1063
25
    auto I = Script->SectionCommands.begin();
1064
25
    auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
1065
25
    I = std::find_if(I, E, IsSection);
1066
25
    E = std::find_if(llvm::make_reverse_iterator(E),
1067
25
                     llvm::make_reverse_iterator(I), IsSection)
1068
25
            .base();
1069
25
    std::stable_sort(I, E, compareSections);
1070
25
    return;
1071
25
  }
1072
2
1073
2
  // Orphan sections are sections present in the input files which are
1074
2
  // not explicitly placed into the output file by the linker script.
1075
2
  //
1076
2
  // The sections in the linker script are already in the correct
1077
2
  // order. We have to figuere out where to insert the orphan
1078
2
  // sections.
1079
2
  //
1080
2
  // The order of the sections in the script is arbitrary and may not agree with
1081
2
  // compareSections. This means that we cannot easily define a strict weak
1082
2
  // ordering. To see why, consider a comparison of a section in the script and
1083
2
  // one not in the script. We have a two simple options:
1084
2
  // * Make them equivalent (a is not less than b, and b is not less than a).
1085
2
  //   The problem is then that equivalence has to be transitive and we can
1086
2
  //   have sections a, b and c with only b in a script and a less than c
1087
2
  //   which breaks this property.
1088
2
  // * Use compareSectionsNonScript. Given that the script order doesn't have
1089
2
  //   to match, we can end up with sections a, b, c, d where b and c are in the
1090
2
  //   script and c is compareSectionsNonScript less than b. In which case d
1091
2
  //   can be equivalent to c, a to b and d < a. As a concrete example:
1092
2
  //   .a (rx) # not in script
1093
2
  //   .b (rx) # in script
1094
2
  //   .c (ro) # in script
1095
2
  //   .d (ro) # not in script
1096
2
  //
1097
2
  // The way we define an order then is:
1098
2
  // *  Sort only the orphan sections. They are in the end right now.
1099
2
  // *  Move each orphan section to its preferred position. We try
1100
2
  //    to put each section in the last position where it it can share
1101
2
  //    a PT_LOAD.
1102
2
  //
1103
2
  // There is some ambiguity as to where exactly a new entry should be
1104
2
  // inserted, because Commands contains not only output section
1105
2
  // commands but also other types of commands such as symbol assignment
1106
2
  // expressions. There's no correct answer here due to the lack of the
1107
2
  // formal specification of the linker script. We use heuristics to
1108
2
  // determine whether a new output command should be added before or
1109
2
  // after another commands. For the details, look at shouldSkip
1110
2
  // function.
1111
2
1112
2
  auto I = Script->SectionCommands.begin();
1113
2
  auto E = Script->SectionCommands.end();
1114
2
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1115
2
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1116
2
      return Sec->Live && Sec->SectionIndex == INT_MAX;
1117
2
    return false;
1118
2
  });
1119
2
1120
2
  // Sort the orphan sections.
1121
2
  std::stable_sort(NonScriptI, E, compareSections);
1122
2
1123
2
  // As a horrible special case, skip the first . assignment if it is before any
1124
2
  // section. We do this because it is common to set a load address by starting
1125
2
  // the script with ". = 0xabcd" and the expectation is that every section is
1126
2
  // after that.
1127
2
  auto FirstSectionOrDotAssignment =
1128
2
      std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1129
2
  if (FirstSectionOrDotAssignment != E &&
1130
2
      isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1131
1
    ++FirstSectionOrDotAssignment;
1132
2
  I = FirstSectionOrDotAssignment;
1133
2
1134
13
  while (NonScriptI != E) {
1135
11
    auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1136
11
    OutputSection *Orphan = cast<OutputSection>(*NonScriptI);
1137
11
1138
11
    // As an optimization, find all sections with the same sort rank
1139
11
    // and insert them with one rotate.
1140
11
    unsigned Rank = Orphan->SortRank;
1141
11
    auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1142
11
      return cast<OutputSection>(Cmd)->SortRank != Rank;
1143
11
    });
1144
11
    std::rotate(Pos, NonScriptI, End);
1145
11
    NonScriptI = End;
1146
11
  }
1147
2
1148
2
  Script->adjustSectionsAfterSorting();
1149
2
}
1150
1151
45
static bool compareByFilePosition(InputSection *A, InputSection *B) {
1152
45
  // Synthetic, i. e. a sentinel section, should go last.
1153
45
  if (A->kind() == InputSectionBase::Synthetic ||
1154
45
      
B->kind() == InputSectionBase::Synthetic35
)
1155
15
    return A->kind() != InputSectionBase::Synthetic;
1156
30
  InputSection *LA = A->getLinkOrderDep();
1157
30
  InputSection *LB = B->getLinkOrderDep();
1158
30
  OutputSection *AOut = LA->getParent();
1159
30
  OutputSection *BOut = LB->getParent();
1160
30
  if (AOut != BOut)
1161
9
    return AOut->SectionIndex < BOut->SectionIndex;
1162
21
  return LA->OutSecOff < LB->OutSecOff;
1163
21
}
1164
1165
// This function is used by the --merge-exidx-entries to detect duplicate
1166
// .ARM.exidx sections. It is Arm only.
1167
//
1168
// The .ARM.exidx section is of the form:
1169
// | PREL31 offset to function | Unwind instructions for function |
1170
// where the unwind instructions are either a small number of unwind
1171
// instructions inlined into the table entry, the special CANT_UNWIND value of
1172
// 0x1 or a PREL31 offset into a .ARM.extab Section that contains unwind
1173
// instructions.
1174
//
1175
// We return true if all the unwind instructions in the .ARM.exidx entries of
1176
// Cur can be merged into the last entry of Prev.
1177
8
static bool isDuplicateArmExidxSec(InputSection *Prev, InputSection *Cur) {
1178
8
1179
8
  // References to .ARM.Extab Sections have bit 31 clear and are not the
1180
8
  // special EXIDX_CANTUNWIND bit-pattern.
1181
17
  auto IsExtabRef = [](uint32_t Unwind) {
1182
17
    return (Unwind & 0x80000000) == 0 && 
Unwind != 0x110
;
1183
17
  };
1184
8
1185
8
  struct ExidxEntry {
1186
8
    ulittle32_t Fn;
1187
8
    ulittle32_t Unwind;
1188
8
  };
1189
8
1190
8
  // Get the last table Entry from the previous .ARM.exidx section.
1191
8
  const ExidxEntry &PrevEntry = *reinterpret_cast<const ExidxEntry *>(
1192
8
      Prev->Data.data() + Prev->getSize() - sizeof(ExidxEntry));
1193
8
  if (IsExtabRef(PrevEntry.Unwind))
1194
1
    return false;
1195
7
1196
7
  // We consider the unwind instructions of an .ARM.exidx table entry
1197
7
  // a duplicate if the previous unwind instructions if:
1198
7
  // - Both are the special EXIDX_CANTUNWIND.
1199
7
  // - Both are the same inline unwind instructions.
1200
7
  // We do not attempt to follow and check links into .ARM.extab tables as
1201
7
  // consecutive identical entries are rare and the effort to check that they
1202
7
  // are identical is high.
1203
7
1204
7
  if (isa<SyntheticSection>(Cur))
1205
0
    // Exidx sentinel section has implicit EXIDX_CANTUNWIND;
1206
0
    return PrevEntry.Unwind == 0x1;
1207
7
1208
7
  ArrayRef<const ExidxEntry> Entries(
1209
7
      reinterpret_cast<const ExidxEntry *>(Cur->Data.data()),
1210
7
      Cur->getSize() / sizeof(ExidxEntry));
1211
7
  for (const ExidxEntry &Entry : Entries)
1212
9
    if (IsExtabRef(Entry.Unwind) || 
Entry.Unwind != PrevEntry.Unwind6
)
1213
4
      return false;
1214
7
  // All table entries in this .ARM.exidx Section can be merged into the
1215
7
  // previous Section.
1216
7
  
return true3
;
1217
7
}
1218
1219
887
template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
1220
73.4k
  for (OutputSection *Sec : OutputSections) {
1221
73.4k
    if (!(Sec->Flags & SHF_LINK_ORDER))
1222
73.4k
      continue;
1223
14
1224
14
    // Link order may be distributed across several InputSectionDescriptions
1225
14
    // but sort must consider them all at once.
1226
14
    std::vector<InputSection **> ScriptSections;
1227
14
    std::vector<InputSection *> Sections;
1228
14
    for (BaseCommand *Base : Sec->SectionCommands) {
1229
14
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base)) {
1230
48
        for (InputSection *&IS : ISD->Sections) {
1231
48
          ScriptSections.push_back(&IS);
1232
48
          Sections.push_back(IS);
1233
48
        }
1234
14
      }
1235
14
    }
1236
14
    std::stable_sort(Sections.begin(), Sections.end(), compareByFilePosition);
1237
14
1238
14
    if (!Config->Relocatable && 
Config->EMachine == EM_ARM13
&&
1239
14
        
Sec->Type == SHT_ARM_EXIDX11
) {
1240
11
1241
11
      if (!Sections.empty() && isa<ARMExidxSentinelSection>(Sections.back())) {
1242
10
        assert(Sections.size() >= 2 &&
1243
10
               "We should create a sentinel section only if there are "
1244
10
               "alive regular exidx sections.");
1245
10
        // The last executable section is required to fill the sentinel.
1246
10
        // Remember it here so that we don't have to find it again.
1247
10
        auto *Sentinel = cast<ARMExidxSentinelSection>(Sections.back());
1248
10
        Sentinel->Highest = Sections[Sections.size() - 2]->getLinkOrderDep();
1249
10
      }
1250
11
1251
11
      if (Config->MergeArmExidx) {
1252
8
        // The EHABI for the Arm Architecture permits consecutive identical
1253
8
        // table entries to be merged. We use a simple implementation that
1254
8
        // removes a .ARM.exidx Input Section if it can be merged into the
1255
8
        // previous one. This does not require any rewriting of InputSection
1256
8
        // contents but misses opportunities for fine grained deduplication
1257
8
        // where only a subset of the InputSection contents can be merged.
1258
8
        int Cur = 1;
1259
8
        int Prev = 0;
1260
8
        // The last one is a sentinel entry which should not be removed.
1261
8
        int N = Sections.size() - 1;
1262
16
        while (Cur < N) {
1263
8
          if (isDuplicateArmExidxSec(Sections[Prev], Sections[Cur]))
1264
3
            Sections[Cur] = nullptr;
1265
5
          else
1266
5
            Prev = Cur;
1267
8
          ++Cur;
1268
8
        }
1269
8
      }
1270
11
    }
1271
14
1272
62
    for (int I = 0, N = Sections.size(); I < N; 
++I48
)
1273
48
      *ScriptSections[I] = Sections[I];
1274
14
1275
14
    // Remove the Sections we marked as duplicate earlier.
1276
14
    for (BaseCommand *Base : Sec->SectionCommands)
1277
14
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
1278
14
        ISD->Sections.erase(
1279
14
            std::remove(ISD->Sections.begin(), ISD->Sections.end(), nullptr),
1280
14
            ISD->Sections.end());
1281
14
  }
1282
887
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::resolveShfLinkOrder()
Line
Count
Source
1219
116
template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
1220
1.14k
  for (OutputSection *Sec : OutputSections) {
1221
1.14k
    if (!(Sec->Flags & SHF_LINK_ORDER))
1222
1.13k
      continue;
1223
12
1224
12
    // Link order may be distributed across several InputSectionDescriptions
1225
12
    // but sort must consider them all at once.
1226
12
    std::vector<InputSection **> ScriptSections;
1227
12
    std::vector<InputSection *> Sections;
1228
12
    for (BaseCommand *Base : Sec->SectionCommands) {
1229
12
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base)) {
1230
45
        for (InputSection *&IS : ISD->Sections) {
1231
45
          ScriptSections.push_back(&IS);
1232
45
          Sections.push_back(IS);
1233
45
        }
1234
12
      }
1235
12
    }
1236
12
    std::stable_sort(Sections.begin(), Sections.end(), compareByFilePosition);
1237
12
1238
12
    if (!Config->Relocatable && 
Config->EMachine == EM_ARM11
&&
1239
12
        
Sec->Type == SHT_ARM_EXIDX11
) {
1240
11
1241
11
      if (!Sections.empty() && isa<ARMExidxSentinelSection>(Sections.back())) {
1242
10
        assert(Sections.size() >= 2 &&
1243
10
               "We should create a sentinel section only if there are "
1244
10
               "alive regular exidx sections.");
1245
10
        // The last executable section is required to fill the sentinel.
1246
10
        // Remember it here so that we don't have to find it again.
1247
10
        auto *Sentinel = cast<ARMExidxSentinelSection>(Sections.back());
1248
10
        Sentinel->Highest = Sections[Sections.size() - 2]->getLinkOrderDep();
1249
10
      }
1250
11
1251
11
      if (Config->MergeArmExidx) {
1252
8
        // The EHABI for the Arm Architecture permits consecutive identical
1253
8
        // table entries to be merged. We use a simple implementation that
1254
8
        // removes a .ARM.exidx Input Section if it can be merged into the
1255
8
        // previous one. This does not require any rewriting of InputSection
1256
8
        // contents but misses opportunities for fine grained deduplication
1257
8
        // where only a subset of the InputSection contents can be merged.
1258
8
        int Cur = 1;
1259
8
        int Prev = 0;
1260
8
        // The last one is a sentinel entry which should not be removed.
1261
8
        int N = Sections.size() - 1;
1262
16
        while (Cur < N) {
1263
8
          if (isDuplicateArmExidxSec(Sections[Prev], Sections[Cur]))
1264
3
            Sections[Cur] = nullptr;
1265
5
          else
1266
5
            Prev = Cur;
1267
8
          ++Cur;
1268
8
        }
1269
8
      }
1270
11
    }
1271
12
1272
57
    for (int I = 0, N = Sections.size(); I < N; 
++I45
)
1273
45
      *ScriptSections[I] = Sections[I];
1274
12
1275
12
    // Remove the Sections we marked as duplicate earlier.
1276
12
    for (BaseCommand *Base : Sec->SectionCommands)
1277
12
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
1278
12
        ISD->Sections.erase(
1279
12
            std::remove(ISD->Sections.begin(), ISD->Sections.end(), nullptr),
1280
12
            ISD->Sections.end());
1281
12
  }
1282
116
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::resolveShfLinkOrder()
Line
Count
Source
1219
50
template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
1220
627
  for (OutputSection *Sec : OutputSections) {
1221
627
    if (!(Sec->Flags & SHF_LINK_ORDER))
1222
627
      continue;
1223
0
1224
0
    // Link order may be distributed across several InputSectionDescriptions
1225
0
    // but sort must consider them all at once.
1226
0
    std::vector<InputSection **> ScriptSections;
1227
0
    std::vector<InputSection *> Sections;
1228
0
    for (BaseCommand *Base : Sec->SectionCommands) {
1229
0
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base)) {
1230
0
        for (InputSection *&IS : ISD->Sections) {
1231
0
          ScriptSections.push_back(&IS);
1232
0
          Sections.push_back(IS);
1233
0
        }
1234
0
      }
1235
0
    }
1236
0
    std::stable_sort(Sections.begin(), Sections.end(), compareByFilePosition);
1237
0
1238
0
    if (!Config->Relocatable && Config->EMachine == EM_ARM &&
1239
0
        Sec->Type == SHT_ARM_EXIDX) {
1240
0
1241
0
      if (!Sections.empty() && isa<ARMExidxSentinelSection>(Sections.back())) {
1242
0
        assert(Sections.size() >= 2 &&
1243
0
               "We should create a sentinel section only if there are "
1244
0
               "alive regular exidx sections.");
1245
0
        // The last executable section is required to fill the sentinel.
1246
0
        // Remember it here so that we don't have to find it again.
1247
0
        auto *Sentinel = cast<ARMExidxSentinelSection>(Sections.back());
1248
0
        Sentinel->Highest = Sections[Sections.size() - 2]->getLinkOrderDep();
1249
0
      }
1250
0
1251
0
      if (Config->MergeArmExidx) {
1252
0
        // The EHABI for the Arm Architecture permits consecutive identical
1253
0
        // table entries to be merged. We use a simple implementation that
1254
0
        // removes a .ARM.exidx Input Section if it can be merged into the
1255
0
        // previous one. This does not require any rewriting of InputSection
1256
0
        // contents but misses opportunities for fine grained deduplication
1257
0
        // where only a subset of the InputSection contents can be merged.
1258
0
        int Cur = 1;
1259
0
        int Prev = 0;
1260
0
        // The last one is a sentinel entry which should not be removed.
1261
0
        int N = Sections.size() - 1;
1262
0
        while (Cur < N) {
1263
0
          if (isDuplicateArmExidxSec(Sections[Prev], Sections[Cur]))
1264
0
            Sections[Cur] = nullptr;
1265
0
          else
1266
0
            Prev = Cur;
1267
0
          ++Cur;
1268
0
        }
1269
0
      }
1270
0
    }
1271
0
1272
0
    for (int I = 0, N = Sections.size(); I < N; ++I)
1273
0
      *ScriptSections[I] = Sections[I];
1274
0
1275
0
    // Remove the Sections we marked as duplicate earlier.
1276
0
    for (BaseCommand *Base : Sec->SectionCommands)
1277
0
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
1278
0
        ISD->Sections.erase(
1279
0
            std::remove(ISD->Sections.begin(), ISD->Sections.end(), nullptr),
1280
0
            ISD->Sections.end());
1281
0
  }
1282
50
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::resolveShfLinkOrder()
Line
Count
Source
1219
694
template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
1220
71.3k
  for (OutputSection *Sec : OutputSections) {
1221
71.3k
    if (!(Sec->Flags & SHF_LINK_ORDER))
1222
71.3k
      continue;
1223
2
1224
2
    // Link order may be distributed across several InputSectionDescriptions
1225
2
    // but sort must consider them all at once.
1226
2
    std::vector<InputSection **> ScriptSections;
1227
2
    std::vector<InputSection *> Sections;
1228
2
    for (BaseCommand *Base : Sec->SectionCommands) {
1229
2
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base)) {
1230
3
        for (InputSection *&IS : ISD->Sections) {
1231
3
          ScriptSections.push_back(&IS);
1232
3
          Sections.push_back(IS);
1233
3
        }
1234
2
      }
1235
2
    }
1236
2
    std::stable_sort(Sections.begin(), Sections.end(), compareByFilePosition);
1237
2
1238
2
    if (!Config->Relocatable && Config->EMachine == EM_ARM &&
1239
2
        
Sec->Type == SHT_ARM_EXIDX0
) {
1240
0
1241
0
      if (!Sections.empty() && isa<ARMExidxSentinelSection>(Sections.back())) {
1242
0
        assert(Sections.size() >= 2 &&
1243
0
               "We should create a sentinel section only if there are "
1244
0
               "alive regular exidx sections.");
1245
0
        // The last executable section is required to fill the sentinel.
1246
0
        // Remember it here so that we don't have to find it again.
1247
0
        auto *Sentinel = cast<ARMExidxSentinelSection>(Sections.back());
1248
0
        Sentinel->Highest = Sections[Sections.size() - 2]->getLinkOrderDep();
1249
0
      }
1250
0
1251
0
      if (Config->MergeArmExidx) {
1252
0
        // The EHABI for the Arm Architecture permits consecutive identical
1253
0
        // table entries to be merged. We use a simple implementation that
1254
0
        // removes a .ARM.exidx Input Section if it can be merged into the
1255
0
        // previous one. This does not require any rewriting of InputSection
1256
0
        // contents but misses opportunities for fine grained deduplication
1257
0
        // where only a subset of the InputSection contents can be merged.
1258
0
        int Cur = 1;
1259
0
        int Prev = 0;
1260
0
        // The last one is a sentinel entry which should not be removed.
1261
0
        int N = Sections.size() - 1;
1262
0
        while (Cur < N) {
1263
0
          if (isDuplicateArmExidxSec(Sections[Prev], Sections[Cur]))
1264
0
            Sections[Cur] = nullptr;
1265
0
          else
1266
0
            Prev = Cur;
1267
0
          ++Cur;
1268
0
        }
1269
0
      }
1270
0
    }
1271
2
1272
5
    for (int I = 0, N = Sections.size(); I < N; 
++I3
)
1273
3
      *ScriptSections[I] = Sections[I];
1274
2
1275
2
    // Remove the Sections we marked as duplicate earlier.
1276
2
    for (BaseCommand *Base : Sec->SectionCommands)
1277
2
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
1278
2
        ISD->Sections.erase(
1279
2
            std::remove(ISD->Sections.begin(), ISD->Sections.end(), nullptr),
1280
2
            ISD->Sections.end());
1281
2
  }
1282
694
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::resolveShfLinkOrder()
Line
Count
Source
1219
27
template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
1220
345
  for (OutputSection *Sec : OutputSections) {
1221
345
    if (!(Sec->Flags & SHF_LINK_ORDER))
1222
345
      continue;
1223
0
1224
0
    // Link order may be distributed across several InputSectionDescriptions
1225
0
    // but sort must consider them all at once.
1226
0
    std::vector<InputSection **> ScriptSections;
1227
0
    std::vector<InputSection *> Sections;
1228
0
    for (BaseCommand *Base : Sec->SectionCommands) {
1229
0
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base)) {
1230
0
        for (InputSection *&IS : ISD->Sections) {
1231
0
          ScriptSections.push_back(&IS);
1232
0
          Sections.push_back(IS);
1233
0
        }
1234
0
      }
1235
0
    }
1236
0
    std::stable_sort(Sections.begin(), Sections.end(), compareByFilePosition);
1237
0
1238
0
    if (!Config->Relocatable && Config->EMachine == EM_ARM &&
1239
0
        Sec->Type == SHT_ARM_EXIDX) {
1240
0
1241
0
      if (!Sections.empty() && isa<ARMExidxSentinelSection>(Sections.back())) {
1242
0
        assert(Sections.size() >= 2 &&
1243
0
               "We should create a sentinel section only if there are "
1244
0
               "alive regular exidx sections.");
1245
0
        // The last executable section is required to fill the sentinel.
1246
0
        // Remember it here so that we don't have to find it again.
1247
0
        auto *Sentinel = cast<ARMExidxSentinelSection>(Sections.back());
1248
0
        Sentinel->Highest = Sections[Sections.size() - 2]->getLinkOrderDep();
1249
0
      }
1250
0
1251
0
      if (Config->MergeArmExidx) {
1252
0
        // The EHABI for the Arm Architecture permits consecutive identical
1253
0
        // table entries to be merged. We use a simple implementation that
1254
0
        // removes a .ARM.exidx Input Section if it can be merged into the
1255
0
        // previous one. This does not require any rewriting of InputSection
1256
0
        // contents but misses opportunities for fine grained deduplication
1257
0
        // where only a subset of the InputSection contents can be merged.
1258
0
        int Cur = 1;
1259
0
        int Prev = 0;
1260
0
        // The last one is a sentinel entry which should not be removed.
1261
0
        int N = Sections.size() - 1;
1262
0
        while (Cur < N) {
1263
0
          if (isDuplicateArmExidxSec(Sections[Prev], Sections[Cur]))
1264
0
            Sections[Cur] = nullptr;
1265
0
          else
1266
0
            Prev = Cur;
1267
0
          ++Cur;
1268
0
        }
1269
0
      }
1270
0
    }
1271
0
1272
0
    for (int I = 0, N = Sections.size(); I < N; ++I)
1273
0
      *ScriptSections[I] = Sections[I];
1274
0
1275
0
    // Remove the Sections we marked as duplicate earlier.
1276
0
    for (BaseCommand *Base : Sec->SectionCommands)
1277
0
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
1278
0
        ISD->Sections.erase(
1279
0
            std::remove(ISD->Sections.begin(), ISD->Sections.end(), nullptr),
1280
0
            ISD->Sections.end());
1281
0
  }
1282
27
}
1283
1284
static void applySynthetic(const std::vector<SyntheticSection *> &Sections,
1285
2.71k
                           std::function<void(SyntheticSection *)> Fn) {
1286
2.71k
  for (SyntheticSection *SS : Sections)
1287
22.2k
    if (SS && 
SS->getParent()17.2k
&&
!SS->empty()15.9k
)
1288
6.32k
      Fn(SS);
1289
2.71k
}
1290
1291
// In order to allow users to manipulate linker-synthesized sections,
1292
// we had to add synthetic sections to the input section list early,
1293
// even before we make decisions whether they are needed. This allows
1294
// users to write scripts like this: ".mygot : { .got }".
1295
//
1296
// Doing it has an unintended side effects. If it turns out that we
1297
// don't need a .got (for example) at all because there's no
1298
// relocation that needs a .got, we don't want to emit .got.
1299
//
1300
// To deal with the above problem, this function is called after
1301
// scanRelocations is called to remove synthetic sections that turn
1302
// out to be empty.
1303
887
static void removeUnusedSyntheticSections() {
1304
887
  // All input synthetic sections that can be empty are placed after
1305
887
  // all regular ones. We iterate over them all and exit at first
1306
887
  // non-synthetic.
1307
17.0k
  for (InputSectionBase *S : llvm::reverse(InputSections)) {
1308
17.0k
    SyntheticSection *SS = dyn_cast<SyntheticSection>(S);
1309
17.0k
    if (!SS)
1310
883
      return;
1311
16.1k
    OutputSection *OS = SS->getParent();
1312
16.1k
    if (!SS->empty() || 
!OS9.67k
)
1313
6.48k
      continue;
1314
9.67k
1315
9.67k
    std::vector<BaseCommand *>::iterator Empty = OS->SectionCommands.end();
1316
9.67k
    for (auto I = OS->SectionCommands.begin(), E = OS->SectionCommands.end();
1317
19.3k
         I != E; 
++I9.68k
) {
1318
9.68k
      BaseCommand *B = *I;
1319
9.68k
      if (auto *ISD = dyn_cast<InputSectionDescription>(B)) {
1320
9.67k
        llvm::erase_if(ISD->Sections,
1321
12.4k
                       [=](InputSection *IS) { return IS == SS; });
1322
9.67k
        if (ISD->Sections.empty())
1323
6.91k
          Empty = I;
1324
9.67k
      }
1325
9.68k
    }
1326
9.67k
    if (Empty != OS->SectionCommands.end())
1327
6.91k
      OS->SectionCommands.erase(Empty);
1328
9.67k
1329
9.67k
    // If there are no other sections in the output section, remove it from the
1330
9.67k
    // output.
1331
9.67k
    if (OS->SectionCommands.empty())
1332
6.91k
      OS->Live = false;
1333
9.67k
  }
1334
887
}
1335
1336
// Returns true if a symbol can be replaced at load-time by a symbol
1337
// with the same name defined in other ELF executable or DSO.
1338
12.8k
static bool computeIsPreemptible(const Symbol &B) {
1339
12.8k
  assert(!B.isLocal());
1340
12.8k
  // Only symbols that appear in dynsym can be preempted.
1341
12.8k
  if (!B.includeInDynsym())
1342
11.9k
    return false;
1343
974
1344
974
  // Only default visibility symbols can be preempted.
1345
974
  if (B.Visibility != STV_DEFAULT)
1346
15
    return false;
1347
959
1348
959
  // At this point copy relocations have not been created yet, so any
1349
959
  // symbol that is not defined locally is preemptible.
1350
959
  if (!B.isDefined())
1351
420
    return true;
1352
539
1353
539
  // If we have a dynamic list it specifies which local symbols are preemptible.
1354
539
  if (Config->HasDynamicList)
1355
8
    return false;
1356
531
1357
531
  if (!Config->Shared)
1358
38
    return false;
1359
493
1360
493
  // -Bsymbolic means that definitions are not preempted.
1361
493
  if (Config->Bsymbolic || 
(486
Config->BsymbolicFunctions486
&&
B.isFunc()0
))
1362
7
    return false;
1363
486
  return true;
1364
486
}
1365
1366
// Create output section objects and add them to OutputSections.
1367
936
template <class ELFT> void Writer<ELFT>::finalizeSections() {
1368
936
  Out::DebugInfo = findSection(".debug_info");
1369
936
  Out::PreinitArray = findSection(".preinit_array");
1370
936
  Out::InitArray = findSection(".init_array");
1371
936
  Out::FiniArray = findSection(".fini_array");
1372
936
1373
936
  // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1374
936
  // symbols for sections, so that the runtime can get the start and end
1375
936
  // addresses of each section by section name. Add such symbols.
1376
936
  if (!Config->Relocatable) {
1377
907
    addStartEndSymbols();
1378
907
    for (BaseCommand *Base : Script->SectionCommands)
1379
81.0k
      if (auto *Sec = dyn_cast<OutputSection>(Base))
1380
80.8k
        addStartStopSymbols(Sec);
1381
907
  }
1382
936
1383
936
  // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1384
936
  // It should be okay as no one seems to care about the type.
1385
936
  // Even the author of gold doesn't remember why gold behaves that way.
1386
936
  // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1387
936
  if (InX::DynSymTab)
1388
488
    Symtab->addRegular("_DYNAMIC", STV_HIDDEN, STT_NOTYPE, 0 /*Value*/,
1389
488
                       /*Size=*/0, STB_WEAK, InX::Dynamic,
1390
488
                       /*File=*/nullptr);
1391
936
1392
936
  // Define __rel[a]_iplt_{start,end} symbols if needed.
1393
936
  addRelIpltSymbols();
1394
936
1395
936
  // This responsible for splitting up .eh_frame section into
1396
936
  // pieces. The relocation scan uses those pieces, so this has to be
1397
936
  // earlier.
1398
936
  applySynthetic({InX::EhFrame},
1399
936
                 [](SyntheticSection *SS) 
{ SS->finalizeContents(); }46
);
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::finalizeSections()::'lambda'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1399
1
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::finalizeSections()::'lambda'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1399
1
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::finalizeSections()::'lambda'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1399
41
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::finalizeSections()::'lambda'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1399
3
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1400
936
1401
936
  for (Symbol *S : Symtab->getSymbols())
1402
12.8k
    S->IsPreemptible |= computeIsPreemptible(*S);
1403
936
1404
936
  // Scan relocations. This must be done after every symbol is declared so that
1405
936
  // we can correctly decide if a dynamic relocation is needed.
1406
936
  if (!Config->Relocatable)
1407
907
    forEachRelSec(scanRelocations<ELFT>);
1408
936
1409
936
  if (InX::Plt && !InX::Plt->empty())
1410
87
    InX::Plt->addSymbols();
1411
936
  if (InX::Iplt && !InX::Iplt->empty())
1412
12
    InX::Iplt->addSymbols();
1413
936
1414
936
  // Now that we have defined all possible global symbols including linker-
1415
936
  // synthesized ones. Visit all symbols to give the finishing touches.
1416
12.8k
  for (Symbol *Sym : Symtab->getSymbols()) {
1417
12.8k
    if (!includeInSymtab(*Sym))
1418
194
      continue;
1419
12.7k
    if (InX::SymTab)
1420
12.7k
      InX::SymTab->addSymbol(Sym);
1421
12.7k
1422
12.7k
    if (InX::DynSymTab && 
Sym->includeInDynsym()1.63k
) {
1423
827
      InX::DynSymTab->addSymbol(Sym);
1424
827
      if (auto *SS = dyn_cast<SharedSymbol>(Sym))
1425
176
        if (cast<SharedFile<ELFT>>(Sym->File)->IsNeeded)
1426
172
          In<ELFT>::VerNeed->addSymbol(SS);
1427
827
    }
1428
12.7k
  }
1429
936
1430
936
  // Do not proceed if there was an undefined symbol.
1431
936
  if (errorCount())
1432
49
    return;
1433
887
1434
887
  removeUnusedSyntheticSections();
1435
887
1436
887
  sortSections();
1437
887
  Script->removeEmptyCommands();
1438
887
1439
887
  // Now that we have the final list, create a list of all the
1440
887
  // OutputSections for convenience.
1441
887
  for (BaseCommand *Base : Script->SectionCommands)
1442
73.5k
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1443
73.4k
      OutputSections.push_back(Sec);
1444
887
1445
887
  // Prefer command line supplied address over other constraints.
1446
73.4k
  for (OutputSection *Sec : OutputSections) {
1447
73.4k
    auto I = Config->SectionStartMap.find(Sec->Name);
1448
73.4k
    if (I != Config->SectionStartMap.end())
1449
14
      Sec->AddrExpr = [=] { return I->second; };
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::finalizeSections()::'lambda'()::operator()() const
Line
Count
Source
1449
3
      Sec->AddrExpr = [=] { return I->second; };
Unexecuted instantiation: Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::finalizeSections()::'lambda'()::operator()() const
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::finalizeSections()::'lambda'()::operator()() const
Line
Count
Source
1449
11
      Sec->AddrExpr = [=] { return I->second; };
Unexecuted instantiation: Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::finalizeSections()::'lambda'()::operator()() const
1450
73.4k
  }
1451
887
1452
887
  // This is a bit of a hack. A value of 0 means undef, so we set it
1453
887
  // to 1 t make __ehdr_start defined. The section number is not
1454
887
  // particularly relevant.
1455
887
  Out::ElfHeader->SectionIndex = 1;
1456
887
1457
887
  unsigned I = 1;
1458
73.4k
  for (OutputSection *Sec : OutputSections) {
1459
73.4k
    Sec->SectionIndex = I++;
1460
73.4k
    Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1461
73.4k
  }
1462
887
1463
887
  // Binary and relocatable output does not have PHDRS.
1464
887
  // The headers have to be created before finalize as that can influence the
1465
887
  // image base and the dynamic section on mips includes the image base.
1466
887
  if (!Config->Relocatable && 
!Config->OFormatBinary859
) {
1467
857
    Phdrs = Script->hasPhdrsCommands() ? 
Script->createPhdrs()15
:
createPhdrs()842
;
1468
857
    addPtArmExid(Phdrs);
1469
857
    Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1470
857
  }
1471
887
1472
887
  // Some symbols are defined in term of program headers. Now that we
1473
887
  // have the headers, we can find out which sections they point to.
1474
887
  setReservedSymbolSections();
1475
887
1476
887
  // Dynamic section must be the last one in this list and dynamic
1477
887
  // symbol table section (DynSymTab) must be the first one.
1478
887
  applySynthetic(
1479
887
      {InX::DynSymTab,   InX::Bss,          InX::BssRelRo, InX::GnuHashTab,
1480
887
       InX::HashTab,     InX::SymTab,       InX::ShStrTab, InX::StrTab,
1481
887
       In<ELFT>::VerDef, InX::DynStrTab,    InX::Got,      InX::MipsGot,
1482
887
       InX::IgotPlt,     InX::GotPlt,       InX::RelaDyn,  InX::RelaIplt,
1483
887
       InX::RelaPlt,     InX::Plt,          InX::Iplt,     InX::EhFrameHdr,
1484
887
       In<ELFT>::VerSym, In<ELFT>::VerNeed, InX::Dynamic},
1485
5.39k
      [](SyntheticSection *SS) { SS->finalizeContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::finalizeSections()::'lambda0'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1485
774
      [](SyntheticSection *SS) { SS->finalizeContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::finalizeSections()::'lambda0'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1485
318
      [](SyntheticSection *SS) { SS->finalizeContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::finalizeSections()::'lambda0'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1485
4.11k
      [](SyntheticSection *SS) { SS->finalizeContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::finalizeSections()::'lambda0'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1485
191
      [](SyntheticSection *SS) { SS->finalizeContents(); });
1486
887
1487
887
  if (!Script->HasSectionsCommand && 
!Config->Relocatable709
)
1488
681
    fixSectionAlignments();
1489
887
1490
887
  // After link order processing .ARM.exidx sections can be deduplicated, which
1491
887
  // needs to be resolved before any other address dependent operation.
1492
887
  resolveShfLinkOrder();
1493
887
1494
887
  // Some architectures need to generate content that depends on the address
1495
887
  // of InputSections. For example some architectures use small displacements
1496
887
  // for jump instructions that is is the linker's responsibility for creating
1497
887
  // range extension thunks for. As the generation of the content may also
1498
887
  // alter InputSection addresses we must converge to a fixed point.
1499
887
  if (Target->NeedsThunks || 
Config->AndroidPackDynRelocs720
) {
1500
167
    ThunkCreator TC;
1501
167
    AArch64Err843419Patcher A64P;
1502
167
    bool Changed;
1503
196
    do {
1504
196
      Script->assignAddresses();
1505
196
      Changed = false;
1506
196
      if (Target->NeedsThunks)
1507
196
        Changed |= TC.createThunks(OutputSections);
1508
196
      if (Config->FixCortexA53Errata843419) {
1509
8
        if (Changed)
1510
1
          Script->assignAddresses();
1511
8
        Changed |= A64P.createFixes();
1512
8
      }
1513
196
      if (InX::MipsGot)
1514
77
        InX::MipsGot->updateAllocSize();
1515
196
      Changed |= InX::RelaDyn->updateAllocSize();
1516
196
    } while (Changed);
1517
167
  }
1518
887
1519
887
  // Fill other section headers. The dynamic table is finalized
1520
887
  // at the end because some tags like RELSZ depend on result
1521
887
  // of finalizing other sections.
1522
887
  for (OutputSection *Sec : OutputSections)
1523
73.4k
    Sec->finalize<ELFT>();
1524
887
1525
887
  // createThunks may have added local symbols to the static symbol table
1526
887
  applySynthetic({InX::SymTab},
1527
887
                 [](SyntheticSection *SS) 
{ SS->postThunkContents(); }884
);
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::finalizeSections()::'lambda1'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1527
116
                 [](SyntheticSection *SS) { SS->postThunkContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::finalizeSections()::'lambda1'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1527
50
                 [](SyntheticSection *SS) { SS->postThunkContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::finalizeSections()::'lambda1'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1527
691
                 [](SyntheticSection *SS) { SS->postThunkContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::finalizeSections()::'lambda1'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1527
27
                 [](SyntheticSection *SS) { SS->postThunkContents(); });
1528
887
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::finalizeSections()
Line
Count
Source
1367
118
template <class ELFT> void Writer<ELFT>::finalizeSections() {
1368
118
  Out::DebugInfo = findSection(".debug_info");
1369
118
  Out::PreinitArray = findSection(".preinit_array");
1370
118
  Out::InitArray = findSection(".init_array");
1371
118
  Out::FiniArray = findSection(".fini_array");
1372
118
1373
118
  // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1374
118
  // symbols for sections, so that the runtime can get the start and end
1375
118
  // addresses of each section by section name. Add such symbols.
1376
118
  if (!Config->Relocatable) {
1377
117
    addStartEndSymbols();
1378
117
    for (BaseCommand *Base : Script->SectionCommands)
1379
2.14k
      if (auto *Sec = dyn_cast<OutputSection>(Base))
1380
2.13k
        addStartStopSymbols(Sec);
1381
117
  }
1382
118
1383
118
  // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1384
118
  // It should be okay as no one seems to care about the type.
1385
118
  // Even the author of gold doesn't remember why gold behaves that way.
1386
118
  // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1387
118
  if (InX::DynSymTab)
1388
69
    Symtab->addRegular("_DYNAMIC", STV_HIDDEN, STT_NOTYPE, 0 /*Value*/,
1389
69
                       /*Size=*/0, STB_WEAK, InX::Dynamic,
1390
69
                       /*File=*/nullptr);
1391
118
1392
118
  // Define __rel[a]_iplt_{start,end} symbols if needed.
1393
118
  addRelIpltSymbols();
1394
118
1395
118
  // This responsible for splitting up .eh_frame section into
1396
118
  // pieces. The relocation scan uses those pieces, so this has to be
1397
118
  // earlier.
1398
118
  applySynthetic({InX::EhFrame},
1399
118
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1400
118
1401
118
  for (Symbol *S : Symtab->getSymbols())
1402
528
    S->IsPreemptible |= computeIsPreemptible(*S);
1403
118
1404
118
  // Scan relocations. This must be done after every symbol is declared so that
1405
118
  // we can correctly decide if a dynamic relocation is needed.
1406
118
  if (!Config->Relocatable)
1407
117
    forEachRelSec(scanRelocations<ELFT>);
1408
118
1409
118
  if (InX::Plt && !InX::Plt->empty())
1410
14
    InX::Plt->addSymbols();
1411
118
  if (InX::Iplt && !InX::Iplt->empty())
1412
5
    InX::Iplt->addSymbols();
1413
118
1414
118
  // Now that we have defined all possible global symbols including linker-
1415
118
  // synthesized ones. Visit all symbols to give the finishing touches.
1416
528
  for (Symbol *Sym : Symtab->getSymbols()) {
1417
528
    if (!includeInSymtab(*Sym))
1418
23
      continue;
1419
505
    if (InX::SymTab)
1420
505
      InX::SymTab->addSymbol(Sym);
1421
505
1422
505
    if (InX::DynSymTab && 
Sym->includeInDynsym()291
) {
1423
167
      InX::DynSymTab->addSymbol(Sym);
1424
167
      if (auto *SS = dyn_cast<SharedSymbol>(Sym))
1425
42
        if (cast<SharedFile<ELFT>>(Sym->File)->IsNeeded)
1426
40
          In<ELFT>::VerNeed->addSymbol(SS);
1427
167
    }
1428
505
  }
1429
118
1430
118
  // Do not proceed if there was an undefined symbol.
1431
118
  if (errorCount())
1432
2
    return;
1433
116
1434
116
  removeUnusedSyntheticSections();
1435
116
1436
116
  sortSections();
1437
116
  Script->removeEmptyCommands();
1438
116
1439
116
  // Now that we have the final list, create a list of all the
1440
116
  // OutputSections for convenience.
1441
116
  for (BaseCommand *Base : Script->SectionCommands)
1442
1.15k
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1443
1.14k
      OutputSections.push_back(Sec);
1444
116
1445
116
  // Prefer command line supplied address over other constraints.
1446
1.14k
  for (OutputSection *Sec : OutputSections) {
1447
1.14k
    auto I = Config->SectionStartMap.find(Sec->Name);
1448
1.14k
    if (I != Config->SectionStartMap.end())
1449
3
      Sec->AddrExpr = [=] { return I->second; };
1450
1.14k
  }
1451
116
1452
116
  // This is a bit of a hack. A value of 0 means undef, so we set it
1453
116
  // to 1 t make __ehdr_start defined. The section number is not
1454
116
  // particularly relevant.
1455
116
  Out::ElfHeader->SectionIndex = 1;
1456
116
1457
116
  unsigned I = 1;
1458
1.14k
  for (OutputSection *Sec : OutputSections) {
1459
1.14k
    Sec->SectionIndex = I++;
1460
1.14k
    Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1461
1.14k
  }
1462
116
1463
116
  // Binary and relocatable output does not have PHDRS.
1464
116
  // The headers have to be created before finalize as that can influence the
1465
116
  // image base and the dynamic section on mips includes the image base.
1466
116
  if (!Config->Relocatable && 
!Config->OFormatBinary115
) {
1467
115
    Phdrs = Script->hasPhdrsCommands() ? 
Script->createPhdrs()4
:
createPhdrs()111
;
1468
115
    addPtArmExid(Phdrs);
1469
115
    Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1470
115
  }
1471
116
1472
116
  // Some symbols are defined in term of program headers. Now that we
1473
116
  // have the headers, we can find out which sections they point to.
1474
116
  setReservedSymbolSections();
1475
116
1476
116
  // Dynamic section must be the last one in this list and dynamic
1477
116
  // symbol table section (DynSymTab) must be the first one.
1478
116
  applySynthetic(
1479
116
      {InX::DynSymTab,   InX::Bss,          InX::BssRelRo, InX::GnuHashTab,
1480
116
       InX::HashTab,     InX::SymTab,       InX::ShStrTab, InX::StrTab,
1481
116
       In<ELFT>::VerDef, InX::DynStrTab,    InX::Got,      InX::MipsGot,
1482
116
       InX::IgotPlt,     InX::GotPlt,       InX::RelaDyn,  InX::RelaIplt,
1483
116
       InX::RelaPlt,     InX::Plt,          InX::Iplt,     InX::EhFrameHdr,
1484
116
       In<ELFT>::VerSym, In<ELFT>::VerNeed, InX::Dynamic},
1485
116
      [](SyntheticSection *SS) { SS->finalizeContents(); });
1486
116
1487
116
  if (!Script->HasSectionsCommand && 
!Config->Relocatable102
)
1488
101
    fixSectionAlignments();
1489
116
1490
116
  // After link order processing .ARM.exidx sections can be deduplicated, which
1491
116
  // needs to be resolved before any other address dependent operation.
1492
116
  resolveShfLinkOrder();
1493
116
1494
116
  // Some architectures need to generate content that depends on the address
1495
116
  // of InputSections. For example some architectures use small displacements
1496
116
  // for jump instructions that is is the linker's responsibility for creating
1497
116
  // range extension thunks for. As the generation of the content may also
1498
116
  // alter InputSection addresses we must converge to a fixed point.
1499
116
  if (Target->NeedsThunks || 
Config->AndroidPackDynRelocs55
) {
1500
61
    ThunkCreator TC;
1501
61
    AArch64Err843419Patcher A64P;
1502
61
    bool Changed;
1503
76
    do {
1504
76
      Script->assignAddresses();
1505
76
      Changed = false;
1506
76
      if (Target->NeedsThunks)
1507
76
        Changed |= TC.createThunks(OutputSections);
1508
76
      if (Config->FixCortexA53Errata843419) {
1509
0
        if (Changed)
1510
0
          Script->assignAddresses();
1511
0
        Changed |= A64P.createFixes();
1512
0
      }
1513
76
      if (InX::MipsGot)
1514
5
        InX::MipsGot->updateAllocSize();
1515
76
      Changed |= InX::RelaDyn->updateAllocSize();
1516
76
    } while (Changed);
1517
61
  }
1518
116
1519
116
  // Fill other section headers. The dynamic table is finalized
1520
116
  // at the end because some tags like RELSZ depend on result
1521
116
  // of finalizing other sections.
1522
116
  for (OutputSection *Sec : OutputSections)
1523
1.14k
    Sec->finalize<ELFT>();
1524
116
1525
116
  // createThunks may have added local symbols to the static symbol table
1526
116
  applySynthetic({InX::SymTab},
1527
116
                 [](SyntheticSection *SS) { SS->postThunkContents(); });
1528
116
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::finalizeSections()
Line
Count
Source
1367
52
template <class ELFT> void Writer<ELFT>::finalizeSections() {
1368
52
  Out::DebugInfo = findSection(".debug_info");
1369
52
  Out::PreinitArray = findSection(".preinit_array");
1370
52
  Out::InitArray = findSection(".init_array");
1371
52
  Out::FiniArray = findSection(".fini_array");
1372
52
1373
52
  // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1374
52
  // symbols for sections, so that the runtime can get the start and end
1375
52
  // addresses of each section by section name. Add such symbols.
1376
52
  if (!Config->Relocatable) {
1377
47
    addStartEndSymbols();
1378
47
    for (BaseCommand *Base : Script->SectionCommands)
1379
911
      if (auto *Sec = dyn_cast<OutputSection>(Base))
1380
911
        addStartStopSymbols(Sec);
1381
47
  }
1382
52
1383
52
  // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1384
52
  // It should be okay as no one seems to care about the type.
1385
52
  // Even the author of gold doesn't remember why gold behaves that way.
1386
52
  // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1387
52
  if (InX::DynSymTab)
1388
28
    Symtab->addRegular("_DYNAMIC", STV_HIDDEN, STT_NOTYPE, 0 /*Value*/,
1389
28
                       /*Size=*/0, STB_WEAK, InX::Dynamic,
1390
28
                       /*File=*/nullptr);
1391
52
1392
52
  // Define __rel[a]_iplt_{start,end} symbols if needed.
1393
52
  addRelIpltSymbols();
1394
52
1395
52
  // This responsible for splitting up .eh_frame section into
1396
52
  // pieces. The relocation scan uses those pieces, so this has to be
1397
52
  // earlier.
1398
52
  applySynthetic({InX::EhFrame},
1399
52
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1400
52
1401
52
  for (Symbol *S : Symtab->getSymbols())
1402
239
    S->IsPreemptible |= computeIsPreemptible(*S);
1403
52
1404
52
  // Scan relocations. This must be done after every symbol is declared so that
1405
52
  // we can correctly decide if a dynamic relocation is needed.
1406
52
  if (!Config->Relocatable)
1407
47
    forEachRelSec(scanRelocations<ELFT>);
1408
52
1409
52
  if (InX::Plt && !InX::Plt->empty())
1410
3
    InX::Plt->addSymbols();
1411
52
  if (InX::Iplt && !InX::Iplt->empty())
1412
0
    InX::Iplt->addSymbols();
1413
52
1414
52
  // Now that we have defined all possible global symbols including linker-
1415
52
  // synthesized ones. Visit all symbols to give the finishing touches.
1416
239
  for (Symbol *Sym : Symtab->getSymbols()) {
1417
239
    if (!includeInSymtab(*Sym))
1418
21
      continue;
1419
218
    if (InX::SymTab)
1420
218
      InX::SymTab->addSymbol(Sym);
1421
218
1422
218
    if (InX::DynSymTab && 
Sym->includeInDynsym()126
) {
1423
61
      InX::DynSymTab->addSymbol(Sym);
1424
61
      if (auto *SS = dyn_cast<SharedSymbol>(Sym))
1425
8
        if (cast<SharedFile<ELFT>>(Sym->File)->IsNeeded)
1426
8
          In<ELFT>::VerNeed->addSymbol(SS);
1427
61
    }
1428
218
  }
1429
52
1430
52
  // Do not proceed if there was an undefined symbol.
1431
52
  if (errorCount())
1432
2
    return;
1433
50
1434
50
  removeUnusedSyntheticSections();
1435
50
1436
50
  sortSections();
1437
50
  Script->removeEmptyCommands();
1438
50
1439
50
  // Now that we have the final list, create a list of all the
1440
50
  // OutputSections for convenience.
1441
50
  for (BaseCommand *Base : Script->SectionCommands)
1442
627
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1443
627
      OutputSections.push_back(Sec);
1444
50
1445
50
  // Prefer command line supplied address over other constraints.
1446
627
  for (OutputSection *Sec : OutputSections) {
1447
627
    auto I = Config->SectionStartMap.find(Sec->Name);
1448
627
    if (I != Config->SectionStartMap.end())
1449
0
      Sec->AddrExpr = [=] { return I->second; };
1450
627
  }
1451
50
1452
50
  // This is a bit of a hack. A value of 0 means undef, so we set it
1453
50
  // to 1 t make __ehdr_start defined. The section number is not
1454
50
  // particularly relevant.
1455
50
  Out::ElfHeader->SectionIndex = 1;
1456
50
1457
50
  unsigned I = 1;
1458
627
  for (OutputSection *Sec : OutputSections) {
1459
627
    Sec->SectionIndex = I++;
1460
627
    Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1461
627
  }
1462
50
1463
50
  // Binary and relocatable output does not have PHDRS.
1464
50
  // The headers have to be created before finalize as that can influence the
1465
50
  // image base and the dynamic section on mips includes the image base.
1466
50
  if (!Config->Relocatable && 
!Config->OFormatBinary46
) {
1467
46
    Phdrs = Script->hasPhdrsCommands() ? 
Script->createPhdrs()0
: createPhdrs();
1468
46
    addPtArmExid(Phdrs);
1469
46
    Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1470
46
  }
1471
50
1472
50
  // Some symbols are defined in term of program headers. Now that we
1473
50
  // have the headers, we can find out which sections they point to.
1474
50
  setReservedSymbolSections();
1475
50
1476
50
  // Dynamic section must be the last one in this list and dynamic
1477
50
  // symbol table section (DynSymTab) must be the first one.
1478
50
  applySynthetic(
1479
50
      {InX::DynSymTab,   InX::Bss,          InX::BssRelRo, InX::GnuHashTab,
1480
50
       InX::HashTab,     InX::SymTab,       InX::ShStrTab, InX::StrTab,
1481
50
       In<ELFT>::VerDef, InX::DynStrTab,    InX::Got,      InX::MipsGot,
1482
50
       InX::IgotPlt,     InX::GotPlt,       InX::RelaDyn,  InX::RelaIplt,
1483
50
       InX::RelaPlt,     InX::Plt,          InX::Iplt,     InX::EhFrameHdr,
1484
50
       In<ELFT>::VerSym, In<ELFT>::VerNeed, InX::Dynamic},
1485
50
      [](SyntheticSection *SS) { SS->finalizeContents(); });
1486
50
1487
50
  if (!Script->HasSectionsCommand && 
!Config->Relocatable47
)
1488
43
    fixSectionAlignments();
1489
50
1490
50
  // After link order processing .ARM.exidx sections can be deduplicated, which
1491
50
  // needs to be resolved before any other address dependent operation.
1492
50
  resolveShfLinkOrder();
1493
50
1494
50
  // Some architectures need to generate content that depends on the address
1495
50
  // of InputSections. For example some architectures use small displacements
1496
50
  // for jump instructions that is is the linker's responsibility for creating
1497
50
  // range extension thunks for. As the generation of the content may also
1498
50
  // alter InputSection addresses we must converge to a fixed point.
1499
50
  if (Target->NeedsThunks || 
Config->AndroidPackDynRelocs1
) {
1500
49
    ThunkCreator TC;
1501
49
    AArch64Err843419Patcher A64P;
1502
49
    bool Changed;
1503
54
    do {
1504
54
      Script->assignAddresses();
1505
54
      Changed = false;
1506
54
      if (Target->NeedsThunks)
1507
54
        Changed |= TC.createThunks(OutputSections);
1508
54
      if (Config->FixCortexA53Errata843419) {
1509
0
        if (Changed)
1510
0
          Script->assignAddresses();
1511
0
        Changed |= A64P.createFixes();
1512
0
      }
1513
54
      if (InX::MipsGot)
1514
54
        InX::MipsGot->updateAllocSize();
1515
54
      Changed |= InX::RelaDyn->updateAllocSize();
1516
54
    } while (Changed);
1517
49
  }
1518
50
1519
50
  // Fill other section headers. The dynamic table is finalized
1520
50
  // at the end because some tags like RELSZ depend on result
1521
50
  // of finalizing other sections.
1522
50
  for (OutputSection *Sec : OutputSections)
1523
627
    Sec->finalize<ELFT>();
1524
50
1525
50
  // createThunks may have added local symbols to the static symbol table
1526
50
  applySynthetic({InX::SymTab},
1527
50
                 [](SyntheticSection *SS) { SS->postThunkContents(); });
1528
50
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::finalizeSections()
Line
Count
Source
1367
738
template <class ELFT> void Writer<ELFT>::finalizeSections() {
1368
738
  Out::DebugInfo = findSection(".debug_info");
1369
738
  Out::PreinitArray = findSection(".preinit_array");
1370
738
  Out::InitArray = findSection(".init_array");
1371
738
  Out::FiniArray = findSection(".fini_array");
1372
738
1373
738
  // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1374
738
  // symbols for sections, so that the runtime can get the start and end
1375
738
  // addresses of each section by section name. Add such symbols.
1376
738
  if (!Config->Relocatable) {
1377
715
    addStartEndSymbols();
1378
715
    for (BaseCommand *Base : Script->SectionCommands)
1379
77.4k
      if (auto *Sec = dyn_cast<OutputSection>(Base))
1380
77.2k
        addStartStopSymbols(Sec);
1381
715
  }
1382
738
1383
738
  // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1384
738
  // It should be okay as no one seems to care about the type.
1385
738
  // Even the author of gold doesn't remember why gold behaves that way.
1386
738
  // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1387
738
  if (InX::DynSymTab)
1388
374
    Symtab->addRegular("_DYNAMIC", STV_HIDDEN, STT_NOTYPE, 0 /*Value*/,
1389
374
                       /*Size=*/0, STB_WEAK, InX::Dynamic,
1390
374
                       /*File=*/nullptr);
1391
738
1392
738
  // Define __rel[a]_iplt_{start,end} symbols if needed.
1393
738
  addRelIpltSymbols();
1394
738
1395
738
  // This responsible for splitting up .eh_frame section into
1396
738
  // pieces. The relocation scan uses those pieces, so this has to be
1397
738
  // earlier.
1398
738
  applySynthetic({InX::EhFrame},
1399
738
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1400
738
1401
738
  for (Symbol *S : Symtab->getSymbols())
1402
2.00k
    S->IsPreemptible |= computeIsPreemptible(*S);
1403
738
1404
738
  // Scan relocations. This must be done after every symbol is declared so that
1405
738
  // we can correctly decide if a dynamic relocation is needed.
1406
738
  if (!Config->Relocatable)
1407
715
    forEachRelSec(scanRelocations<ELFT>);
1408
738
1409
738
  if (InX::Plt && !InX::Plt->empty())
1410
68
    InX::Plt->addSymbols();
1411
738
  if (InX::Iplt && !InX::Iplt->empty())
1412
7
    InX::Iplt->addSymbols();
1413
738
1414
738
  // Now that we have defined all possible global symbols including linker-
1415
738
  // synthesized ones. Visit all symbols to give the finishing touches.
1416
2.00k
  for (Symbol *Sym : Symtab->getSymbols()) {
1417
2.00k
    if (!includeInSymtab(*Sym))
1418
143
      continue;
1419
1.86k
    if (InX::SymTab)
1420
1.86k
      InX::SymTab->addSymbol(Sym);
1421
1.86k
1422
1.86k
    if (InX::DynSymTab && 
Sym->includeInDynsym()1.14k
) {
1423
563
      InX::DynSymTab->addSymbol(Sym);
1424
563
      if (auto *SS = dyn_cast<SharedSymbol>(Sym))
1425
121
        if (cast<SharedFile<ELFT>>(Sym->File)->IsNeeded)
1426
119
          In<ELFT>::VerNeed->addSymbol(SS);
1427
563
    }
1428
1.86k
  }
1429
738
1430
738
  // Do not proceed if there was an undefined symbol.
1431
738
  if (errorCount())
1432
44
    return;
1433
694
1434
694
  removeUnusedSyntheticSections();
1435
694
1436
694
  sortSections();
1437
694
  Script->removeEmptyCommands();
1438
694
1439
694
  // Now that we have the final list, create a list of all the
1440
694
  // OutputSections for convenience.
1441
694
  for (BaseCommand *Base : Script->SectionCommands)
1442
71.4k
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1443
71.3k
      OutputSections.push_back(Sec);
1444
694
1445
694
  // Prefer command line supplied address over other constraints.
1446
71.3k
  for (OutputSection *Sec : OutputSections) {
1447
71.3k
    auto I = Config->SectionStartMap.find(Sec->Name);
1448
71.3k
    if (I != Config->SectionStartMap.end())
1449
11
      Sec->AddrExpr = [=] { return I->second; };
1450
71.3k
  }
1451
694
1452
694
  // This is a bit of a hack. A value of 0 means undef, so we set it
1453
694
  // to 1 t make __ehdr_start defined. The section number is not
1454
694
  // particularly relevant.
1455
694
  Out::ElfHeader->SectionIndex = 1;
1456
694
1457
694
  unsigned I = 1;
1458
71.3k
  for (OutputSection *Sec : OutputSections) {
1459
71.3k
    Sec->SectionIndex = I++;
1460
71.3k
    Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1461
71.3k
  }
1462
694
1463
694
  // Binary and relocatable output does not have PHDRS.
1464
694
  // The headers have to be created before finalize as that can influence the
1465
694
  // image base and the dynamic section on mips includes the image base.
1466
694
  if (!Config->Relocatable && 
!Config->OFormatBinary671
) {
1467
669
    Phdrs = Script->hasPhdrsCommands() ? 
Script->createPhdrs()11
:
createPhdrs()658
;
1468
669
    addPtArmExid(Phdrs);
1469
669
    Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1470
669
  }
1471
694
1472
694
  // Some symbols are defined in term of program headers. Now that we
1473
694
  // have the headers, we can find out which sections they point to.
1474
694
  setReservedSymbolSections();
1475
694
1476
694
  // Dynamic section must be the last one in this list and dynamic
1477
694
  // symbol table section (DynSymTab) must be the first one.
1478
694
  applySynthetic(
1479
694
      {InX::DynSymTab,   InX::Bss,          InX::BssRelRo, InX::GnuHashTab,
1480
694
       InX::HashTab,     InX::SymTab,       InX::ShStrTab, InX::StrTab,
1481
694
       In<ELFT>::VerDef, InX::DynStrTab,    InX::Got,      InX::MipsGot,
1482
694
       InX::IgotPlt,     InX::GotPlt,       InX::RelaDyn,  InX::RelaIplt,
1483
694
       InX::RelaPlt,     InX::Plt,          InX::Iplt,     InX::EhFrameHdr,
1484
694
       In<ELFT>::VerSym, In<ELFT>::VerNeed, InX::Dynamic},
1485
694
      [](SyntheticSection *SS) { SS->finalizeContents(); });
1486
694
1487
694
  if (!Script->HasSectionsCommand && 
!Config->Relocatable535
)
1488
512
    fixSectionAlignments();
1489
694
1490
694
  // After link order processing .ARM.exidx sections can be deduplicated, which
1491
694
  // needs to be resolved before any other address dependent operation.
1492
694
  resolveShfLinkOrder();
1493
694
1494
694
  // Some architectures need to generate content that depends on the address
1495
694
  // of InputSections. For example some architectures use small displacements
1496
694
  // for jump instructions that is is the linker's responsibility for creating
1497
694
  // range extension thunks for. As the generation of the content may also
1498
694
  // alter InputSection addresses we must converge to a fixed point.
1499
694
  if (Target->NeedsThunks || 
Config->AndroidPackDynRelocs655
) {
1500
39
    ThunkCreator TC;
1501
39
    AArch64Err843419Patcher A64P;
1502
39
    bool Changed;
1503
48
    do {
1504
48
      Script->assignAddresses();
1505
48
      Changed = false;
1506
48
      if (Target->NeedsThunks)
1507
48
        Changed |= TC.createThunks(OutputSections);
1508
48
      if (Config->FixCortexA53Errata843419) {
1509
8
        if (Changed)
1510
1
          Script->assignAddresses();
1511
8
        Changed |= A64P.createFixes();
1512
8
      }
1513
48
      if (InX::MipsGot)
1514
0
        InX::MipsGot->updateAllocSize();
1515
48
      Changed |= InX::RelaDyn->updateAllocSize();
1516
48
    } while (Changed);
1517
39
  }
1518
694
1519
694
  // Fill other section headers. The dynamic table is finalized
1520
694
  // at the end because some tags like RELSZ depend on result
1521
694
  // of finalizing other sections.
1522
694
  for (OutputSection *Sec : OutputSections)
1523
71.3k
    Sec->finalize<ELFT>();
1524
694
1525
694
  // createThunks may have added local symbols to the static symbol table
1526
694
  applySynthetic({InX::SymTab},
1527
694
                 [](SyntheticSection *SS) { SS->postThunkContents(); });
1528
694
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::finalizeSections()
Line
Count
Source
1367
28
template <class ELFT> void Writer<ELFT>::finalizeSections() {
1368
28
  Out::DebugInfo = findSection(".debug_info");
1369
28
  Out::PreinitArray = findSection(".preinit_array");
1370
28
  Out::InitArray = findSection(".init_array");
1371
28
  Out::FiniArray = findSection(".fini_array");
1372
28
1373
28
  // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1374
28
  // symbols for sections, so that the runtime can get the start and end
1375
28
  // addresses of each section by section name. Add such symbols.
1376
28
  if (!Config->Relocatable) {
1377
28
    addStartEndSymbols();
1378
28
    for (BaseCommand *Base : Script->SectionCommands)
1379
548
      if (auto *Sec = dyn_cast<OutputSection>(Base))
1380
547
        addStartStopSymbols(Sec);
1381
28
  }
1382
28
1383
28
  // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1384
28
  // It should be okay as no one seems to care about the type.
1385
28
  // Even the author of gold doesn't remember why gold behaves that way.
1386
28
  // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1387
28
  if (InX::DynSymTab)
1388
17
    Symtab->addRegular("_DYNAMIC", STV_HIDDEN, STT_NOTYPE, 0 /*Value*/,
1389
17
                       /*Size=*/0, STB_WEAK, InX::Dynamic,
1390
17
                       /*File=*/nullptr);
1391
28
1392
28
  // Define __rel[a]_iplt_{start,end} symbols if needed.
1393
28
  addRelIpltSymbols();
1394
28
1395
28
  // This responsible for splitting up .eh_frame section into
1396
28
  // pieces. The relocation scan uses those pieces, so this has to be
1397
28
  // earlier.
1398
28
  applySynthetic({InX::EhFrame},
1399
28
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1400
28
1401
28
  for (Symbol *S : Symtab->getSymbols())
1402
10.1k
    S->IsPreemptible |= computeIsPreemptible(*S);
1403
28
1404
28
  // Scan relocations. This must be done after every symbol is declared so that
1405
28
  // we can correctly decide if a dynamic relocation is needed.
1406
28
  if (!Config->Relocatable)
1407
28
    forEachRelSec(scanRelocations<ELFT>);
1408
28
1409
28
  if (InX::Plt && !InX::Plt->empty())
1410
2
    InX::Plt->addSymbols();
1411
28
  if (InX::Iplt && !InX::Iplt->empty())
1412
0
    InX::Iplt->addSymbols();
1413
28
1414
28
  // Now that we have defined all possible global symbols including linker-
1415
28
  // synthesized ones. Visit all symbols to give the finishing touches.
1416
10.1k
  for (Symbol *Sym : Symtab->getSymbols()) {
1417
10.1k
    if (!includeInSymtab(*Sym))
1418
7
      continue;
1419
10.1k
    if (InX::SymTab)
1420
10.1k
      InX::SymTab->addSymbol(Sym);
1421
10.1k
1422
10.1k
    if (InX::DynSymTab && 
Sym->includeInDynsym()72
) {
1423
36
      InX::DynSymTab->addSymbol(Sym);
1424
36
      if (auto *SS = dyn_cast<SharedSymbol>(Sym))
1425
5
        if (cast<SharedFile<ELFT>>(Sym->File)->IsNeeded)
1426
5
          In<ELFT>::VerNeed->addSymbol(SS);
1427
36
    }
1428
10.1k
  }
1429
28
1430
28
  // Do not proceed if there was an undefined symbol.
1431
28
  if (errorCount())
1432
1
    return;
1433
27
1434
27
  removeUnusedSyntheticSections();
1435
27
1436
27
  sortSections();
1437
27
  Script->removeEmptyCommands();
1438
27
1439
27
  // Now that we have the final list, create a list of all the
1440
27
  // OutputSections for convenience.
1441
27
  for (BaseCommand *Base : Script->SectionCommands)
1442
346
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1443
345
      OutputSections.push_back(Sec);
1444
27
1445
27
  // Prefer command line supplied address over other constraints.
1446
345
  for (OutputSection *Sec : OutputSections) {
1447
345
    auto I = Config->SectionStartMap.find(Sec->Name);
1448
345
    if (I != Config->SectionStartMap.end())
1449
0
      Sec->AddrExpr = [=] { return I->second; };
1450
345
  }
1451
27
1452
27
  // This is a bit of a hack. A value of 0 means undef, so we set it
1453
27
  // to 1 t make __ehdr_start defined. The section number is not
1454
27
  // particularly relevant.
1455
27
  Out::ElfHeader->SectionIndex = 1;
1456
27
1457
27
  unsigned I = 1;
1458
345
  for (OutputSection *Sec : OutputSections) {
1459
345
    Sec->SectionIndex = I++;
1460
345
    Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1461
345
  }
1462
27
1463
27
  // Binary and relocatable output does not have PHDRS.
1464
27
  // The headers have to be created before finalize as that can influence the
1465
27
  // image base and the dynamic section on mips includes the image base.
1466
27
  if (!Config->Relocatable && !Config->OFormatBinary) {
1467
27
    Phdrs = Script->hasPhdrsCommands() ? 
Script->createPhdrs()0
: createPhdrs();
1468
27
    addPtArmExid(Phdrs);
1469
27
    Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1470
27
  }
1471
27
1472
27
  // Some symbols are defined in term of program headers. Now that we
1473
27
  // have the headers, we can find out which sections they point to.
1474
27
  setReservedSymbolSections();
1475
27
1476
27
  // Dynamic section must be the last one in this list and dynamic
1477
27
  // symbol table section (DynSymTab) must be the first one.
1478
27
  applySynthetic(
1479
27
      {InX::DynSymTab,   InX::Bss,          InX::BssRelRo, InX::GnuHashTab,
1480
27
       InX::HashTab,     InX::SymTab,       InX::ShStrTab, InX::StrTab,
1481
27
       In<ELFT>::VerDef, InX::DynStrTab,    InX::Got,      InX::MipsGot,
1482
27
       InX::IgotPlt,     InX::GotPlt,       InX::RelaDyn,  InX::RelaIplt,
1483
27
       InX::RelaPlt,     InX::Plt,          InX::Iplt,     InX::EhFrameHdr,
1484
27
       In<ELFT>::VerSym, In<ELFT>::VerNeed, InX::Dynamic},
1485
27
      [](SyntheticSection *SS) { SS->finalizeContents(); });
1486
27
1487
27
  if (!Script->HasSectionsCommand && 
!Config->Relocatable25
)
1488
25
    fixSectionAlignments();
1489
27
1490
27
  // After link order processing .ARM.exidx sections can be deduplicated, which
1491
27
  // needs to be resolved before any other address dependent operation.
1492
27
  resolveShfLinkOrder();
1493
27
1494
27
  // Some architectures need to generate content that depends on the address
1495
27
  // of InputSections. For example some architectures use small displacements
1496
27
  // for jump instructions that is is the linker's responsibility for creating
1497
27
  // range extension thunks for. As the generation of the content may also
1498
27
  // alter InputSection addresses we must converge to a fixed point.
1499
27
  if (Target->NeedsThunks || 
Config->AndroidPackDynRelocs9
) {
1500
18
    ThunkCreator TC;
1501
18
    AArch64Err843419Patcher A64P;
1502
18
    bool Changed;
1503
18
    do {
1504
18
      Script->assignAddresses();
1505
18
      Changed = false;
1506
18
      if (Target->NeedsThunks)
1507
18
        Changed |= TC.createThunks(OutputSections);
1508
18
      if (Config->FixCortexA53Errata843419) {
1509
0
        if (