Coverage Report

Created: 2019-01-18 03:29

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