Coverage Report

Created: 2018-08-19 21:11

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