Coverage Report

Created: 2017-10-03 07:32

/Users/buildslave/jenkins/sharedspace/clang-stage2-coverage-R@2/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 "Config.h"
12
#include "Filesystem.h"
13
#include "LinkerScript.h"
14
#include "MapFile.h"
15
#include "Memory.h"
16
#include "OutputSections.h"
17
#include "Relocations.h"
18
#include "Strings.h"
19
#include "SymbolTable.h"
20
#include "SyntheticSections.h"
21
#include "Target.h"
22
#include "Threads.h"
23
#include "llvm/ADT/StringMap.h"
24
#include "llvm/ADT/StringSwitch.h"
25
#include "llvm/Support/FileOutputBuffer.h"
26
#include <climits>
27
28
using namespace llvm;
29
using namespace llvm::ELF;
30
using namespace llvm::object;
31
using namespace llvm::support;
32
using namespace llvm::support::endian;
33
34
using namespace lld;
35
using namespace lld::elf;
36
37
namespace {
38
// The writer writes a SymbolTable result to a file.
39
template <class ELFT> class Writer {
40
public:
41
  typedef typename ELFT::Shdr Elf_Shdr;
42
  typedef typename ELFT::Ehdr Elf_Ehdr;
43
  typedef typename ELFT::Phdr Elf_Phdr;
44
45
  void run();
46
47
private:
48
  void createSyntheticSections();
49
  void copyLocalSymbols();
50
  void addSectionSymbols();
51
  void addReservedSymbols();
52
  void createSections();
53
  void forEachRelSec(std::function<void(InputSectionBase &)> Fn);
54
  void sortSections();
55
  void finalizeSections();
56
  void addPredefinedSections();
57
  void setReservedSymbolSections();
58
59
  std::vector<PhdrEntry *> createPhdrs();
60
  void removeEmptyPTLoad();
61
  void addPtArmExid(std::vector<PhdrEntry *> &Phdrs);
62
  void assignFileOffsets();
63
  void assignFileOffsetsBinary();
64
  void setPhdrs();
65
  void fixSectionAlignments();
66
  void openFile();
67
  void writeTrapInstr();
68
  void writeHeader();
69
  void writeSections();
70
  void writeSectionsBinary();
71
  void writeBuildId();
72
73
  std::unique_ptr<FileOutputBuffer> Buffer;
74
75
  OutputSectionFactory Factory;
76
77
  void addRelIpltSymbols();
78
  void addStartEndSymbols();
79
  void addStartStopSymbols(OutputSection *Sec);
80
  uint64_t getEntryAddr();
81
  OutputSection *findSection(StringRef Name);
82
83
  std::vector<PhdrEntry *> Phdrs;
84
85
  uint64_t FileSize;
86
  uint64_t SectionHeaderOff;
87
88
  bool HasGotBaseSym = false;
89
};
90
} // anonymous namespace
91
92
229k
StringRef elf::getOutputSectionName(StringRef Name) {
93
229k
  // ".zdebug_" is a prefix for ZLIB-compressed sections.
94
229k
  // Because we decompressed input sections, we want to remove 'z'.
95
229k
  if (Name.startswith(".zdebug_"))
96
2
    return Saver.save("." + Name.substr(2));
97
229k
98
229k
  
if (229k
Config->Relocatable229k
)
99
1.03k
    return Name;
100
228k
101
228k
  for (StringRef V :
102
228k
       {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
103
228k
        ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
104
3.36M
        ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."}) {
105
3.36M
    StringRef Prefix = V.drop_back();
106
3.36M
    if (
Name.startswith(V) || 3.36M
Name == Prefix3.36M
)
107
5.85k
      return Prefix;
108
222k
  }
109
222k
110
222k
  // CommonSection is identified as "COMMON" in linker scripts.
111
222k
  // By default, it should go to .bss section.
112
222k
  
if (222k
Name == "COMMON"222k
)
113
69
    return ".bss";
114
222k
115
222k
  return Name;
116
222k
}
117
118
1.59k
static bool needsInterpSection() {
119
199
  return !SharedFiles.empty() && !Config->DynamicLinker.empty() &&
120
5
         !Script->ignoreInterpSection();
121
1.59k
}
122
123
1.59k
template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
void lld::elf::writeResult<llvm::object::ELFType<(llvm::support::endianness)0, true> >()
Line
Count
Source
123
44
template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
void lld::elf::writeResult<llvm::object::ELFType<(llvm::support::endianness)1, true> >()
Line
Count
Source
123
1.26k
template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
void lld::elf::writeResult<llvm::object::ELFType<(llvm::support::endianness)0, false> >()
Line
Count
Source
123
95
template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
void lld::elf::writeResult<llvm::object::ELFType<(llvm::support::endianness)1, false> >()
Line
Count
Source
123
193
template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
124
125
1.52k
template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
126
7.89k
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
127
7.89k
    if (P->p_type != PT_LOAD)
128
4.27k
      return false;
129
3.61k
    
if (3.61k
!P->FirstSec3.61k
)
130
14
      return true;
131
3.60k
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
132
3.60k
    return Size == 0;
133
3.60k
  });
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
126
1.06k
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
127
1.06k
    if (P->p_type != PT_LOAD)
128
594
      return false;
129
471
    
if (471
!P->FirstSec471
)
130
3
      return true;
131
468
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
132
468
    return Size == 0;
133
468
  });
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
126
482
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
127
482
    if (P->p_type != PT_LOAD)
128
233
      return false;
129
249
    
if (249
!P->FirstSec249
)
130
0
      return true;
131
249
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
132
249
    return Size == 0;
133
249
  });
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
126
6.09k
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
127
6.09k
    if (P->p_type != PT_LOAD)
128
3.31k
      return false;
129
2.77k
    
if (2.77k
!P->FirstSec2.77k
)
130
11
      return true;
131
2.76k
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
132
2.76k
    return Size == 0;
133
2.76k
  });
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
126
258
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
127
258
    if (P->p_type != PT_LOAD)
128
134
      return false;
129
124
    
if (124
!P->FirstSec124
)
130
0
      return true;
131
124
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
132
124
    return Size == 0;
133
124
  });
134
1.52k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::removeEmptyPTLoad()
Line
Count
Source
125
189
template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
126
189
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
127
189
    if (P->p_type != PT_LOAD)
128
189
      return false;
129
189
    if (!P->FirstSec)
130
189
      return true;
131
189
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
132
189
    return Size == 0;
133
189
  });
134
189
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::removeEmptyPTLoad()
Line
Count
Source
125
93
template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
126
93
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
127
93
    if (P->p_type != PT_LOAD)
128
93
      return false;
129
93
    if (!P->FirstSec)
130
93
      return true;
131
93
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
132
93
    return Size == 0;
133
93
  });
134
93
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::removeEmptyPTLoad()
Line
Count
Source
125
1.20k
template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
126
1.20k
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
127
1.20k
    if (P->p_type != PT_LOAD)
128
1.20k
      return false;
129
1.20k
    if (!P->FirstSec)
130
1.20k
      return true;
131
1.20k
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
132
1.20k
    return Size == 0;
133
1.20k
  });
134
1.20k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::removeEmptyPTLoad()
Line
Count
Source
125
44
template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
126
44
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
127
44
    if (P->p_type != PT_LOAD)
128
44
      return false;
129
44
    if (!P->FirstSec)
130
44
      return true;
131
44
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
132
44
    return Size == 0;
133
44
  });
134
44
}
135
136
1.53k
template <class ELFT> static void combineEhFrameSections() {
137
227k
  for (InputSectionBase *&S : InputSections) {
138
227k
    EhInputSection *ES = dyn_cast<EhInputSection>(S);
139
227k
    if (
!ES || 227k
!ES->Live95
)
140
227k
      continue;
141
95
142
95
    In<ELFT>::EhFrame->addSection(ES);
143
95
    S = nullptr;
144
95
  }
145
1.53k
146
1.53k
  std::vector<InputSectionBase *> &V = InputSections;
147
1.53k
  V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
148
1.53k
}
Writer.cpp:void combineEhFrameSections<llvm::object::ELFType<(llvm::support::endianness)1, false> >()
Line
Count
Source
136
187
template <class ELFT> static void combineEhFrameSections() {
137
3.90k
  for (InputSectionBase *&S : InputSections) {
138
3.90k
    EhInputSection *ES = dyn_cast<EhInputSection>(S);
139
3.90k
    if (
!ES || 3.90k
!ES->Live4
)
140
3.90k
      continue;
141
4
142
4
    In<ELFT>::EhFrame->addSection(ES);
143
4
    S = nullptr;
144
4
  }
145
187
146
187
  std::vector<InputSectionBase *> &V = InputSections;
147
187
  V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
148
187
}
Writer.cpp:void combineEhFrameSections<llvm::object::ELFType<(llvm::support::endianness)0, true> >()
Line
Count
Source
136
43
template <class ELFT> static void combineEhFrameSections() {
137
1.07k
  for (InputSectionBase *&S : InputSections) {
138
1.07k
    EhInputSection *ES = dyn_cast<EhInputSection>(S);
139
1.07k
    if (
!ES || 1.07k
!ES->Live3
)
140
1.06k
      continue;
141
3
142
3
    In<ELFT>::EhFrame->addSection(ES);
143
3
    S = nullptr;
144
3
  }
145
43
146
43
  std::vector<InputSectionBase *> &V = InputSections;
147
43
  V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
148
43
}
Writer.cpp:void combineEhFrameSections<llvm::object::ELFType<(llvm::support::endianness)1, true> >()
Line
Count
Source
136
1.22k
template <class ELFT> static void combineEhFrameSections() {
137
220k
  for (InputSectionBase *&S : InputSections) {
138
220k
    EhInputSection *ES = dyn_cast<EhInputSection>(S);
139
220k
    if (
!ES || 220k
!ES->Live87
)
140
220k
      continue;
141
87
142
87
    In<ELFT>::EhFrame->addSection(ES);
143
87
    S = nullptr;
144
87
  }
145
1.22k
146
1.22k
  std::vector<InputSectionBase *> &V = InputSections;
147
1.22k
  V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
148
1.22k
}
Writer.cpp:void combineEhFrameSections<llvm::object::ELFType<(llvm::support::endianness)0, false> >()
Line
Count
Source
136
87
template <class ELFT> static void combineEhFrameSections() {
137
2.37k
  for (InputSectionBase *&S : InputSections) {
138
2.37k
    EhInputSection *ES = dyn_cast<EhInputSection>(S);
139
2.37k
    if (
!ES || 2.37k
!ES->Live1
)
140
2.37k
      continue;
141
1
142
1
    In<ELFT>::EhFrame->addSection(ES);
143
1
    S = nullptr;
144
1
  }
145
87
146
87
  std::vector<InputSectionBase *> &V = InputSections;
147
87
  V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
148
87
}
149
150
// The main function of the writer.
151
1.59k
template <class ELFT> void Writer<ELFT>::run() {
152
1.59k
  // Create linker-synthesized sections such as .got or .plt.
153
1.59k
  // Such sections are of type input section.
154
1.59k
  createSyntheticSections();
155
1.59k
156
1.59k
  if (!Config->Relocatable)
157
1.53k
    combineEhFrameSections<ELFT>();
158
1.59k
159
1.59k
  // We need to create some reserved symbols such as _end. Create them.
160
1.59k
  if (!Config->Relocatable)
161
1.53k
    addReservedSymbols();
162
1.59k
163
1.59k
  // Create output sections.
164
1.59k
  if (
Script->Opt.HasSections1.59k
) {
165
295
    // If linker script contains SECTIONS commands, let it create sections.
166
295
    Script->processCommands(Factory);
167
295
168
295
    // Linker scripts may have left some input sections unassigned.
169
295
    // Assign such sections using the default rule.
170
295
    Script->addOrphanSections(Factory);
171
1.59k
  } else {
172
1.30k
    // If linker script does not contain SECTIONS commands, create
173
1.30k
    // output sections by default rules. We still need to give the
174
1.30k
    // linker script a chance to run, because it might contain
175
1.30k
    // non-SECTIONS commands such as ASSERT.
176
1.30k
    Script->processCommands(Factory);
177
1.30k
    createSections();
178
1.30k
  }
179
1.59k
180
1.59k
  if (Config->Discard != DiscardPolicy::All)
181
1.59k
    copyLocalSymbols();
182
1.59k
183
1.59k
  if (Config->CopyRelocs)
184
72
    addSectionSymbols();
185
1.59k
186
1.59k
  // Now that we have a complete set of output sections. This function
187
1.59k
  // completes section contents. For example, we need to add strings
188
1.59k
  // to the string table, and add entries to .got and .plt.
189
1.59k
  // finalizeSections does that.
190
1.59k
  finalizeSections();
191
1.59k
  if (ErrorCount)
192
69
    return;
193
1.52k
194
1.52k
  // If -compressed-debug-sections is specified, we need to compress
195
1.52k
  // .debug_* sections. Do it right now because it changes the size of
196
1.52k
  // output sections.
197
1.52k
  parallelForEach(OutputSections,
198
209k
                  [](OutputSection *Sec) { Sec->maybeCompress<ELFT>(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::run()::'lambda'(lld::elf::OutputSection*)::operator()(lld::elf::OutputSection*) const
Line
Count
Source
198
1.78k
                  [](OutputSection *Sec) { Sec->maybeCompress<ELFT>(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::run()::'lambda'(lld::elf::OutputSection*)::operator()(lld::elf::OutputSection*) const
Line
Count
Source
198
529
                  [](OutputSection *Sec) { Sec->maybeCompress<ELFT>(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::run()::'lambda'(lld::elf::OutputSection*)::operator()(lld::elf::OutputSection*) const
Line
Count
Source
198
205k
                  [](OutputSection *Sec) { Sec->maybeCompress<ELFT>(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::run()::'lambda'(lld::elf::OutputSection*)::operator()(lld::elf::OutputSection*) const
Line
Count
Source
198
1.19k
                  [](OutputSection *Sec) { Sec->maybeCompress<ELFT>(); });
199
1.52k
200
1.52k
  Script->assignAddresses();
201
1.52k
  Script->allocateHeaders(Phdrs);
202
1.52k
203
1.52k
  // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
204
1.52k
  // 0 sized region. This has to be done late since only after assignAddresses
205
1.52k
  // we know the size of the sections.
206
1.52k
  removeEmptyPTLoad();
207
1.52k
208
1.52k
  if (!Config->OFormatBinary)
209
1.52k
    assignFileOffsets();
210
1.52k
  else
211
5
    assignFileOffsetsBinary();
212
1.52k
213
1.52k
  setPhdrs();
214
1.52k
215
1.52k
  if (
Config->Relocatable1.52k
) {
216
59
    for (OutputSection *Sec : OutputSections)
217
396
      Sec->Addr = 0;
218
59
  }
219
1.52k
220
1.52k
  // It does not make sense try to open the file if we have error already.
221
1.52k
  if (ErrorCount)
222
8
    return;
223
1.52k
  // Write the result down to a file.
224
1.52k
  openFile();
225
1.52k
  if (ErrorCount)
226
1
    return;
227
1.52k
228
1.52k
  
if (1.52k
!Config->OFormatBinary1.52k
) {
229
1.51k
    writeTrapInstr();
230
1.51k
    writeHeader();
231
1.51k
    writeSections();
232
1.52k
  } else {
233
5
    writeSectionsBinary();
234
5
  }
235
1.52k
236
1.52k
  // Backfill .note.gnu.build-id section content. This is done at last
237
1.52k
  // because the content is usually a hash value of the entire output file.
238
1.52k
  writeBuildId();
239
1.52k
  if (ErrorCount)
240
34
    return;
241
1.48k
242
1.48k
  // Handle -Map option.
243
1.48k
  writeMapFile<ELFT>();
244
1.48k
  if (ErrorCount)
245
0
    return;
246
1.48k
247
1.48k
  
if (auto 1.48k
EC1.48k
= Buffer->commit())
248
0
    error("failed to write to the output file: " + EC.message());
249
1.48k
250
1.48k
  // Flush the output streams and exit immediately. A full shutdown
251
1.48k
  // is a good test that we are keeping track of all allocated memory,
252
1.48k
  // but actually freeing it is a waste of time in a regular linker run.
253
1.48k
  if (Config->ExitEarly)
254
0
    exitLld(0);
255
1.48k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::run()
Line
Count
Source
151
44
template <class ELFT> void Writer<ELFT>::run() {
152
44
  // Create linker-synthesized sections such as .got or .plt.
153
44
  // Such sections are of type input section.
154
44
  createSyntheticSections();
155
44
156
44
  if (!Config->Relocatable)
157
43
    combineEhFrameSections<ELFT>();
158
44
159
44
  // We need to create some reserved symbols such as _end. Create them.
160
44
  if (!Config->Relocatable)
161
43
    addReservedSymbols();
162
44
163
44
  // Create output sections.
164
44
  if (
Script->Opt.HasSections44
) {
165
2
    // If linker script contains SECTIONS commands, let it create sections.
166
2
    Script->processCommands(Factory);
167
2
168
2
    // Linker scripts may have left some input sections unassigned.
169
2
    // Assign such sections using the default rule.
170
2
    Script->addOrphanSections(Factory);
171
44
  } else {
172
42
    // If linker script does not contain SECTIONS commands, create
173
42
    // output sections by default rules. We still need to give the
174
42
    // linker script a chance to run, because it might contain
175
42
    // non-SECTIONS commands such as ASSERT.
176
42
    Script->processCommands(Factory);
177
42
    createSections();
178
42
  }
179
44
180
44
  if (Config->Discard != DiscardPolicy::All)
181
43
    copyLocalSymbols();
182
44
183
44
  if (Config->CopyRelocs)
184
1
    addSectionSymbols();
185
44
186
44
  // Now that we have a complete set of output sections. This function
187
44
  // completes section contents. For example, we need to add strings
188
44
  // to the string table, and add entries to .got and .plt.
189
44
  // finalizeSections does that.
190
44
  finalizeSections();
191
44
  if (ErrorCount)
192
0
    return;
193
44
194
44
  // If -compressed-debug-sections is specified, we need to compress
195
44
  // .debug_* sections. Do it right now because it changes the size of
196
44
  // output sections.
197
44
  parallelForEach(OutputSections,
198
44
                  [](OutputSection *Sec) { Sec->maybeCompress<ELFT>(); });
199
44
200
44
  Script->assignAddresses();
201
44
  Script->allocateHeaders(Phdrs);
202
44
203
44
  // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
204
44
  // 0 sized region. This has to be done late since only after assignAddresses
205
44
  // we know the size of the sections.
206
44
  removeEmptyPTLoad();
207
44
208
44
  if (!Config->OFormatBinary)
209
44
    assignFileOffsets();
210
44
  else
211
0
    assignFileOffsetsBinary();
212
44
213
44
  setPhdrs();
214
44
215
44
  if (
Config->Relocatable44
) {
216
1
    for (OutputSection *Sec : OutputSections)
217
10
      Sec->Addr = 0;
218
1
  }
219
44
220
44
  // It does not make sense try to open the file if we have error already.
221
44
  if (ErrorCount)
222
0
    return;
223
44
  // Write the result down to a file.
224
44
  openFile();
225
44
  if (ErrorCount)
226
0
    return;
227
44
228
44
  
if (44
!Config->OFormatBinary44
) {
229
44
    writeTrapInstr();
230
44
    writeHeader();
231
44
    writeSections();
232
44
  } else {
233
0
    writeSectionsBinary();
234
0
  }
235
44
236
44
  // Backfill .note.gnu.build-id section content. This is done at last
237
44
  // because the content is usually a hash value of the entire output file.
238
44
  writeBuildId();
239
44
  if (ErrorCount)
240
2
    return;
241
42
242
42
  // Handle -Map option.
243
42
  writeMapFile<ELFT>();
244
42
  if (ErrorCount)
245
0
    return;
246
42
247
42
  
if (auto 42
EC42
= Buffer->commit())
248
0
    error("failed to write to the output file: " + EC.message());
249
42
250
42
  // Flush the output streams and exit immediately. A full shutdown
251
42
  // is a good test that we are keeping track of all allocated memory,
252
42
  // but actually freeing it is a waste of time in a regular linker run.
253
42
  if (Config->ExitEarly)
254
0
    exitLld(0);
255
42
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::run()
Line
Count
Source
151
1.26k
template <class ELFT> void Writer<ELFT>::run() {
152
1.26k
  // Create linker-synthesized sections such as .got or .plt.
153
1.26k
  // Such sections are of type input section.
154
1.26k
  createSyntheticSections();
155
1.26k
156
1.26k
  if (!Config->Relocatable)
157
1.22k
    combineEhFrameSections<ELFT>();
158
1.26k
159
1.26k
  // We need to create some reserved symbols such as _end. Create them.
160
1.26k
  if (!Config->Relocatable)
161
1.22k
    addReservedSymbols();
162
1.26k
163
1.26k
  // Create output sections.
164
1.26k
  if (
Script->Opt.HasSections1.26k
) {
165
267
    // If linker script contains SECTIONS commands, let it create sections.
166
267
    Script->processCommands(Factory);
167
267
168
267
    // Linker scripts may have left some input sections unassigned.
169
267
    // Assign such sections using the default rule.
170
267
    Script->addOrphanSections(Factory);
171
1.26k
  } else {
172
999
    // If linker script does not contain SECTIONS commands, create
173
999
    // output sections by default rules. We still need to give the
174
999
    // linker script a chance to run, because it might contain
175
999
    // non-SECTIONS commands such as ASSERT.
176
999
    Script->processCommands(Factory);
177
999
    createSections();
178
999
  }
179
1.26k
180
1.26k
  if (Config->Discard != DiscardPolicy::All)
181
1.26k
    copyLocalSymbols();
182
1.26k
183
1.26k
  if (Config->CopyRelocs)
184
56
    addSectionSymbols();
185
1.26k
186
1.26k
  // Now that we have a complete set of output sections. This function
187
1.26k
  // completes section contents. For example, we need to add strings
188
1.26k
  // to the string table, and add entries to .got and .plt.
189
1.26k
  // finalizeSections does that.
190
1.26k
  finalizeSections();
191
1.26k
  if (ErrorCount)
192
63
    return;
193
1.20k
194
1.20k
  // If -compressed-debug-sections is specified, we need to compress
195
1.20k
  // .debug_* sections. Do it right now because it changes the size of
196
1.20k
  // output sections.
197
1.20k
  parallelForEach(OutputSections,
198
1.20k
                  [](OutputSection *Sec) { Sec->maybeCompress<ELFT>(); });
199
1.20k
200
1.20k
  Script->assignAddresses();
201
1.20k
  Script->allocateHeaders(Phdrs);
202
1.20k
203
1.20k
  // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
204
1.20k
  // 0 sized region. This has to be done late since only after assignAddresses
205
1.20k
  // we know the size of the sections.
206
1.20k
  removeEmptyPTLoad();
207
1.20k
208
1.20k
  if (!Config->OFormatBinary)
209
1.19k
    assignFileOffsets();
210
1.20k
  else
211
5
    assignFileOffsetsBinary();
212
1.20k
213
1.20k
  setPhdrs();
214
1.20k
215
1.20k
  if (
Config->Relocatable1.20k
) {
216
45
    for (OutputSection *Sec : OutputSections)
217
271
      Sec->Addr = 0;
218
45
  }
219
1.20k
220
1.20k
  // It does not make sense try to open the file if we have error already.
221
1.20k
  if (ErrorCount)
222
8
    return;
223
1.19k
  // Write the result down to a file.
224
1.19k
  openFile();
225
1.19k
  if (ErrorCount)
226
0
    return;
227
1.19k
228
1.19k
  
if (1.19k
!Config->OFormatBinary1.19k
) {
229
1.19k
    writeTrapInstr();
230
1.19k
    writeHeader();
231
1.19k
    writeSections();
232
1.19k
  } else {
233
5
    writeSectionsBinary();
234
5
  }
235
1.19k
236
1.19k
  // Backfill .note.gnu.build-id section content. This is done at last
237
1.19k
  // because the content is usually a hash value of the entire output file.
238
1.19k
  writeBuildId();
239
1.19k
  if (ErrorCount)
240
23
    return;
241
1.17k
242
1.17k
  // Handle -Map option.
243
1.17k
  writeMapFile<ELFT>();
244
1.17k
  if (ErrorCount)
245
0
    return;
246
1.17k
247
1.17k
  
if (auto 1.17k
EC1.17k
= Buffer->commit())
248
0
    error("failed to write to the output file: " + EC.message());
249
1.17k
250
1.17k
  // Flush the output streams and exit immediately. A full shutdown
251
1.17k
  // is a good test that we are keeping track of all allocated memory,
252
1.17k
  // but actually freeing it is a waste of time in a regular linker run.
253
1.17k
  if (Config->ExitEarly)
254
0
    exitLld(0);
255
1.17k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::run()
Line
Count
Source
151
95
template <class ELFT> void Writer<ELFT>::run() {
152
95
  // Create linker-synthesized sections such as .got or .plt.
153
95
  // Such sections are of type input section.
154
95
  createSyntheticSections();
155
95
156
95
  if (!Config->Relocatable)
157
87
    combineEhFrameSections<ELFT>();
158
95
159
95
  // We need to create some reserved symbols such as _end. Create them.
160
95
  if (!Config->Relocatable)
161
87
    addReservedSymbols();
162
95
163
95
  // Create output sections.
164
95
  if (
Script->Opt.HasSections95
) {
165
7
    // If linker script contains SECTIONS commands, let it create sections.
166
7
    Script->processCommands(Factory);
167
7
168
7
    // Linker scripts may have left some input sections unassigned.
169
7
    // Assign such sections using the default rule.
170
7
    Script->addOrphanSections(Factory);
171
95
  } else {
172
88
    // If linker script does not contain SECTIONS commands, create
173
88
    // output sections by default rules. We still need to give the
174
88
    // linker script a chance to run, because it might contain
175
88
    // non-SECTIONS commands such as ASSERT.
176
88
    Script->processCommands(Factory);
177
88
    createSections();
178
88
  }
179
95
180
95
  if (Config->Discard != DiscardPolicy::All)
181
94
    copyLocalSymbols();
182
95
183
95
  if (Config->CopyRelocs)
184
8
    addSectionSymbols();
185
95
186
95
  // Now that we have a complete set of output sections. This function
187
95
  // completes section contents. For example, we need to add strings
188
95
  // to the string table, and add entries to .got and .plt.
189
95
  // finalizeSections does that.
190
95
  finalizeSections();
191
95
  if (ErrorCount)
192
2
    return;
193
93
194
93
  // If -compressed-debug-sections is specified, we need to compress
195
93
  // .debug_* sections. Do it right now because it changes the size of
196
93
  // output sections.
197
93
  parallelForEach(OutputSections,
198
93
                  [](OutputSection *Sec) { Sec->maybeCompress<ELFT>(); });
199
93
200
93
  Script->assignAddresses();
201
93
  Script->allocateHeaders(Phdrs);
202
93
203
93
  // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
204
93
  // 0 sized region. This has to be done late since only after assignAddresses
205
93
  // we know the size of the sections.
206
93
  removeEmptyPTLoad();
207
93
208
93
  if (!Config->OFormatBinary)
209
93
    assignFileOffsets();
210
93
  else
211
0
    assignFileOffsetsBinary();
212
93
213
93
  setPhdrs();
214
93
215
93
  if (
Config->Relocatable93
) {
216
7
    for (OutputSection *Sec : OutputSections)
217
65
      Sec->Addr = 0;
218
7
  }
219
93
220
93
  // It does not make sense try to open the file if we have error already.
221
93
  if (ErrorCount)
222
0
    return;
223
93
  // Write the result down to a file.
224
93
  openFile();
225
93
  if (ErrorCount)
226
0
    return;
227
93
228
93
  
if (93
!Config->OFormatBinary93
) {
229
93
    writeTrapInstr();
230
93
    writeHeader();
231
93
    writeSections();
232
93
  } else {
233
0
    writeSectionsBinary();
234
0
  }
235
93
236
93
  // Backfill .note.gnu.build-id section content. This is done at last
237
93
  // because the content is usually a hash value of the entire output file.
238
93
  writeBuildId();
239
93
  if (ErrorCount)
240
3
    return;
241
90
242
90
  // Handle -Map option.
243
90
  writeMapFile<ELFT>();
244
90
  if (ErrorCount)
245
0
    return;
246
90
247
90
  
if (auto 90
EC90
= Buffer->commit())
248
0
    error("failed to write to the output file: " + EC.message());
249
90
250
90
  // Flush the output streams and exit immediately. A full shutdown
251
90
  // is a good test that we are keeping track of all allocated memory,
252
90
  // but actually freeing it is a waste of time in a regular linker run.
253
90
  if (Config->ExitEarly)
254
0
    exitLld(0);
255
90
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::run()
Line
Count
Source
151
193
template <class ELFT> void Writer<ELFT>::run() {
152
193
  // Create linker-synthesized sections such as .got or .plt.
153
193
  // Such sections are of type input section.
154
193
  createSyntheticSections();
155
193
156
193
  if (!Config->Relocatable)
157
187
    combineEhFrameSections<ELFT>();
158
193
159
193
  // We need to create some reserved symbols such as _end. Create them.
160
193
  if (!Config->Relocatable)
161
187
    addReservedSymbols();
162
193
163
193
  // Create output sections.
164
193
  if (
Script->Opt.HasSections193
) {
165
19
    // If linker script contains SECTIONS commands, let it create sections.
166
19
    Script->processCommands(Factory);
167
19
168
19
    // Linker scripts may have left some input sections unassigned.
169
19
    // Assign such sections using the default rule.
170
19
    Script->addOrphanSections(Factory);
171
193
  } else {
172
174
    // If linker script does not contain SECTIONS commands, create
173
174
    // output sections by default rules. We still need to give the
174
174
    // linker script a chance to run, because it might contain
175
174
    // non-SECTIONS commands such as ASSERT.
176
174
    Script->processCommands(Factory);
177
174
    createSections();
178
174
  }
179
193
180
193
  if (Config->Discard != DiscardPolicy::All)
181
193
    copyLocalSymbols();
182
193
183
193
  if (Config->CopyRelocs)
184
7
    addSectionSymbols();
185
193
186
193
  // Now that we have a complete set of output sections. This function
187
193
  // completes section contents. For example, we need to add strings
188
193
  // to the string table, and add entries to .got and .plt.
189
193
  // finalizeSections does that.
190
193
  finalizeSections();
191
193
  if (ErrorCount)
192
4
    return;
193
189
194
189
  // If -compressed-debug-sections is specified, we need to compress
195
189
  // .debug_* sections. Do it right now because it changes the size of
196
189
  // output sections.
197
189
  parallelForEach(OutputSections,
198
189
                  [](OutputSection *Sec) { Sec->maybeCompress<ELFT>(); });
199
189
200
189
  Script->assignAddresses();
201
189
  Script->allocateHeaders(Phdrs);
202
189
203
189
  // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
204
189
  // 0 sized region. This has to be done late since only after assignAddresses
205
189
  // we know the size of the sections.
206
189
  removeEmptyPTLoad();
207
189
208
189
  if (!Config->OFormatBinary)
209
189
    assignFileOffsets();
210
189
  else
211
0
    assignFileOffsetsBinary();
212
189
213
189
  setPhdrs();
214
189
215
189
  if (
Config->Relocatable189
) {
216
6
    for (OutputSection *Sec : OutputSections)
217
50
      Sec->Addr = 0;
218
6
  }
219
189
220
189
  // It does not make sense try to open the file if we have error already.
221
189
  if (ErrorCount)
222
0
    return;
223
189
  // Write the result down to a file.
224
189
  openFile();
225
189
  if (ErrorCount)
226
1
    return;
227
188
228
188
  
if (188
!Config->OFormatBinary188
) {
229
188
    writeTrapInstr();
230
188
    writeHeader();
231
188
    writeSections();
232
188
  } else {
233
0
    writeSectionsBinary();
234
0
  }
235
188
236
188
  // Backfill .note.gnu.build-id section content. This is done at last
237
188
  // because the content is usually a hash value of the entire output file.
238
188
  writeBuildId();
239
188
  if (ErrorCount)
240
6
    return;
241
182
242
182
  // Handle -Map option.
243
182
  writeMapFile<ELFT>();
244
182
  if (ErrorCount)
245
0
    return;
246
182
247
182
  
if (auto 182
EC182
= Buffer->commit())
248
0
    error("failed to write to the output file: " + EC.message());
249
182
250
182
  // Flush the output streams and exit immediately. A full shutdown
251
182
  // is a good test that we are keeping track of all allocated memory,
252
182
  // but actually freeing it is a waste of time in a regular linker run.
253
182
  if (Config->ExitEarly)
254
0
    exitLld(0);
255
182
}
256
257
// Initialize Out members.
258
1.59k
template <class ELFT> void Writer<ELFT>::createSyntheticSections() {
259
1.59k
  // Initialize all pointers with NULL. This is needed because
260
1.59k
  // you can call lld::elf::main more than once as a library.
261
1.59k
  memset(&Out::First, 0, sizeof(Out));
262
1.59k
263
26.7k
  auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::createSyntheticSections()::'lambda'(lld::elf::InputSectionBase*)::operator()(lld::elf::InputSectionBase*) const
Line
Count
Source
263
3.29k
  auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::createSyntheticSections()::'lambda'(lld::elf::InputSectionBase*)::operator()(lld::elf::InputSectionBase*) const
Line
Count
Source
263
1.80k
  auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::createSyntheticSections()::'lambda'(lld::elf::InputSectionBase*)::operator()(lld::elf::InputSectionBase*) const
Line
Count
Source
263
814
  auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::createSyntheticSections()::'lambda'(lld::elf::InputSectionBase*)::operator()(lld::elf::InputSectionBase*) const
Line
Count
Source
263
20.8k
  auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
264
1.59k
265
1.59k
  InX::DynStrTab = make<StringTableSection>(".dynstr", true);
266
1.59k
  InX::Dynamic = make<DynamicSection<ELFT>>();
267
1.59k
  In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>(
268
1.59k
      Config->IsRela ? 
".rela.dyn"1.31k
:
".rel.dyn"284
, Config->ZCombreloc);
269
1.59k
  InX::ShStrTab = make<StringTableSection>(".shstrtab", false);
270
1.59k
271
1.59k
  Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
272
1.59k
  Out::ElfHeader->Size = sizeof(Elf_Ehdr);
273
1.59k
  Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
274
1.59k
  Out::ProgramHeaders->updateAlignment(Config->Wordsize);
275
1.59k
276
1.59k
  if (
needsInterpSection()1.59k
) {
277
4
    InX::Interp = createInterpSection();
278
4
    Add(InX::Interp);
279
1.59k
  } else {
280
1.59k
    InX::Interp = nullptr;
281
1.59k
  }
282
1.59k
283
1.59k
  if (
Config->Strip != StripPolicy::All1.59k
) {
284
1.59k
    InX::StrTab = make<StringTableSection>(".strtab", false);
285
1.59k
    InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab);
286
1.59k
  }
287
1.59k
288
1.59k
  if (
Config->BuildId != BuildIdKind::None1.59k
) {
289
12
    InX::BuildId = make<BuildIdSection>();
290
12
    Add(InX::BuildId);
291
12
  }
292
1.59k
293
1.59k
  for (InputSection *S : createCommonSections())
294
84
    Add(S);
295
1.59k
296
1.59k
  InX::Bss = make<BssSection>(".bss");
297
1.59k
  Add(InX::Bss);
298
1.59k
  InX::BssRelRo = make<BssSection>(".bss.rel.ro");
299
1.59k
  Add(InX::BssRelRo);
300
1.59k
301
1.59k
  // Add MIPS-specific sections.
302
1.59k
  if (
Config->EMachine == EM_MIPS1.59k
) {
303
137
    if (
!Config->Shared && 137
Config->HasDynSymTab80
) {
304
20
      InX::MipsRldMap = make<MipsRldMapSection>();
305
20
      Add(InX::MipsRldMap);
306
20
    }
307
137
    if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
308
135
      Add(Sec);
309
137
    if (auto *Sec = MipsOptionsSection<ELFT>::create())
310
30
      Add(Sec);
311
137
    if (auto *Sec = MipsReginfoSection<ELFT>::create())
312
105
      Add(Sec);
313
137
  }
314
1.59k
315
1.59k
  if (
Config->HasDynSymTab1.59k
) {
316
805
    InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab);
317
805
    Add(InX::DynSymTab);
318
805
319
805
    In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
320
805
    Add(In<ELFT>::VerSym);
321
805
322
805
    if (
!Config->VersionDefinitions.empty()805
) {
323
36
      In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
324
36
      Add(In<ELFT>::VerDef);
325
36
    }
326
805
327
805
    In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
328
805
    Add(In<ELFT>::VerNeed);
329
805
330
805
    if (
Config->GnuHash805
) {
331
5
      InX::GnuHashTab = make<GnuHashTableSection>();
332
5
      Add(InX::GnuHashTab);
333
5
    }
334
805
335
805
    if (
Config->SysvHash805
) {
336
801
      InX::HashTab = make<HashTableSection>();
337
801
      Add(InX::HashTab);
338
801
    }
339
805
340
805
    Add(InX::Dynamic);
341
805
    Add(InX::DynStrTab);
342
805
    Add(In<ELFT>::RelaDyn);
343
805
  }
344
1.59k
345
1.59k
  // Add .got. MIPS' .got is so different from the other archs,
346
1.59k
  // it has its own class.
347
1.59k
  if (
Config->EMachine == EM_MIPS1.59k
) {
348
137
    InX::MipsGot = make<MipsGotSection>();
349
137
    Add(InX::MipsGot);
350
1.59k
  } else {
351
1.46k
    InX::Got = make<GotSection>();
352
1.46k
    Add(InX::Got);
353
1.46k
  }
354
1.59k
355
1.59k
  InX::GotPlt = make<GotPltSection>();
356
1.59k
  Add(InX::GotPlt);
357
1.59k
  InX::IgotPlt = make<IgotPltSection>();
358
1.59k
  Add(InX::IgotPlt);
359
1.59k
360
1.59k
  if (
Config->GdbIndex1.59k
) {
361
9
    InX::GdbIndex = createGdbIndex<ELFT>();
362
9
    Add(InX::GdbIndex);
363
9
  }
364
1.59k
365
1.59k
  // We always need to add rel[a].plt to output if it has entries.
366
1.59k
  // Even for static linking it can contain R_[*]_IRELATIVE relocations.
367
1.59k
  In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>(
368
1.59k
      Config->IsRela ? 
".rela.plt"1.31k
:
".rel.plt"284
, false /*Sort*/);
369
1.59k
  Add(In<ELFT>::RelaPlt);
370
1.59k
371
1.59k
  // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
372
1.59k
  // that the IRelative relocations are processed last by the dynamic loader
373
1.59k
  In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>(
374
1.59k
      (Config->EMachine == EM_ARM) ? 
".rel.dyn"82
:
In<ELFT>::RelaPlt->Name1.51k
,
375
1.59k
      false /*Sort*/);
376
1.59k
  Add(In<ELFT>::RelaIplt);
377
1.59k
378
1.59k
  InX::Plt = make<PltSection>(Target->PltHeaderSize);
379
1.59k
  Add(InX::Plt);
380
1.59k
  InX::Iplt = make<PltSection>(0);
381
1.59k
  Add(InX::Iplt);
382
1.59k
383
1.59k
  if (
!Config->Relocatable1.59k
) {
384
1.53k
    if (
Config->EhFrameHdr1.53k
) {
385
16
      In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>();
386
16
      Add(In<ELFT>::EhFrameHdr);
387
16
    }
388
1.53k
    In<ELFT>::EhFrame = make<EhFrameSection<ELFT>>();
389
1.53k
    Add(In<ELFT>::EhFrame);
390
1.53k
  }
391
1.59k
392
1.59k
  if (InX::SymTab)
393
1.59k
    Add(InX::SymTab);
394
1.59k
  Add(InX::ShStrTab);
395
1.59k
  if (InX::StrTab)
396
1.59k
    Add(InX::StrTab);
397
1.59k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::createSyntheticSections()
Line
Count
Source
258
44
template <class ELFT> void Writer<ELFT>::createSyntheticSections() {
259
44
  // Initialize all pointers with NULL. This is needed because
260
44
  // you can call lld::elf::main more than once as a library.
261
44
  memset(&Out::First, 0, sizeof(Out));
262
44
263
44
  auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
264
44
265
44
  InX::DynStrTab = make<StringTableSection>(".dynstr", true);
266
44
  InX::Dynamic = make<DynamicSection<ELFT>>();
267
44
  In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>(
268
44
      Config->IsRela ? 
".rela.dyn"44
:
".rel.dyn"0
, Config->ZCombreloc);
269
44
  InX::ShStrTab = make<StringTableSection>(".shstrtab", false);
270
44
271
44
  Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
272
44
  Out::ElfHeader->Size = sizeof(Elf_Ehdr);
273
44
  Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
274
44
  Out::ProgramHeaders->updateAlignment(Config->Wordsize);
275
44
276
44
  if (
needsInterpSection()44
) {
277
1
    InX::Interp = createInterpSection();
278
1
    Add(InX::Interp);
279
44
  } else {
280
43
    InX::Interp = nullptr;
281
43
  }
282
44
283
44
  if (
Config->Strip != StripPolicy::All44
) {
284
44
    InX::StrTab = make<StringTableSection>(".strtab", false);
285
44
    InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab);
286
44
  }
287
44
288
44
  if (
Config->BuildId != BuildIdKind::None44
) {
289
0
    InX::BuildId = make<BuildIdSection>();
290
0
    Add(InX::BuildId);
291
0
  }
292
44
293
44
  for (InputSection *S : createCommonSections())
294
2
    Add(S);
295
44
296
44
  InX::Bss = make<BssSection>(".bss");
297
44
  Add(InX::Bss);
298
44
  InX::BssRelRo = make<BssSection>(".bss.rel.ro");
299
44
  Add(InX::BssRelRo);
300
44
301
44
  // Add MIPS-specific sections.
302
44
  if (
Config->EMachine == EM_MIPS44
) {
303
28
    if (
!Config->Shared && 28
Config->HasDynSymTab17
) {
304
5
      InX::MipsRldMap = make<MipsRldMapSection>();
305
5
      Add(InX::MipsRldMap);
306
5
    }
307
28
    if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
308
28
      Add(Sec);
309
28
    if (auto *Sec = MipsOptionsSection<ELFT>::create())
310
28
      Add(Sec);
311
28
    if (auto *Sec = MipsReginfoSection<ELFT>::create())
312
0
      Add(Sec);
313
28
  }
314
44
315
44
  if (
Config->HasDynSymTab44
) {
316
25
    InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab);
317
25
    Add(InX::DynSymTab);
318
25
319
25
    In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
320
25
    Add(In<ELFT>::VerSym);
321
25
322
25
    if (
!Config->VersionDefinitions.empty()25
) {
323
0
      In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
324
0
      Add(In<ELFT>::VerDef);
325
0
    }
326
25
327
25
    In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
328
25
    Add(In<ELFT>::VerNeed);
329
25
330
25
    if (
Config->GnuHash25
) {
331
1
      InX::GnuHashTab = make<GnuHashTableSection>();
332
1
      Add(InX::GnuHashTab);
333
1
    }
334
25
335
25
    if (
Config->SysvHash25
) {
336
25
      InX::HashTab = make<HashTableSection>();
337
25
      Add(InX::HashTab);
338
25
    }
339
25
340
25
    Add(InX::Dynamic);
341
25
    Add(InX::DynStrTab);
342
25
    Add(In<ELFT>::RelaDyn);
343
25
  }
344
44
345
44
  // Add .got. MIPS' .got is so different from the other archs,
346
44
  // it has its own class.
347
44
  if (
Config->EMachine == EM_MIPS44
) {
348
28
    InX::MipsGot = make<MipsGotSection>();
349
28
    Add(InX::MipsGot);
350
44
  } else {
351
16
    InX::Got = make<GotSection>();
352
16
    Add(InX::Got);
353
16
  }
354
44
355
44
  InX::GotPlt = make<GotPltSection>();
356
44
  Add(InX::GotPlt);
357
44
  InX::IgotPlt = make<IgotPltSection>();
358
44
  Add(InX::IgotPlt);
359
44
360
44
  if (
Config->GdbIndex44
) {
361
0
    InX::GdbIndex = createGdbIndex<ELFT>();
362
0
    Add(InX::GdbIndex);
363
0
  }
364
44
365
44
  // We always need to add rel[a].plt to output if it has entries.
366
44
  // Even for static linking it can contain R_[*]_IRELATIVE relocations.
367
44
  In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>(
368
44
      Config->IsRela ? 
".rela.plt"44
:
".rel.plt"0
, false /*Sort*/);
369
44
  Add(In<ELFT>::RelaPlt);
370
44
371
44
  // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
372
44
  // that the IRelative relocations are processed last by the dynamic loader
373
44
  In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>(
374
44
      (Config->EMachine == EM_ARM) ? 
".rel.dyn"0
:
In<ELFT>::RelaPlt->Name44
,
375
44
      false /*Sort*/);
376
44
  Add(In<ELFT>::RelaIplt);
377
44
378
44
  InX::Plt = make<PltSection>(Target->PltHeaderSize);
379
44
  Add(InX::Plt);
380
44
  InX::Iplt = make<PltSection>(0);
381
44
  Add(InX::Iplt);
382
44
383
44
  if (
!Config->Relocatable44
) {
384
43
    if (
Config->EhFrameHdr43
) {
385
3
      In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>();
386
3
      Add(In<ELFT>::EhFrameHdr);
387
3
    }
388
43
    In<ELFT>::EhFrame = make<EhFrameSection<ELFT>>();
389
43
    Add(In<ELFT>::EhFrame);
390
43
  }
391
44
392
44
  if (InX::SymTab)
393
44
    Add(InX::SymTab);
394
44
  Add(InX::ShStrTab);
395
44
  if (InX::StrTab)
396
44
    Add(InX::StrTab);
397
44
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::createSyntheticSections()
Line
Count
Source
258
1.26k
template <class ELFT> void Writer<ELFT>::createSyntheticSections() {
259
1.26k
  // Initialize all pointers with NULL. This is needed because
260
1.26k
  // you can call lld::elf::main more than once as a library.
261
1.26k
  memset(&Out::First, 0, sizeof(Out));
262
1.26k
263
1.26k
  auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
264
1.26k
265
1.26k
  InX::DynStrTab = make<StringTableSection>(".dynstr", true);
266
1.26k
  InX::Dynamic = make<DynamicSection<ELFT>>();
267
1.26k
  In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>(
268
1.26k
      Config->IsRela ? 
".rela.dyn"1.26k
:
".rel.dyn"0
, Config->ZCombreloc);
269
1.26k
  InX::ShStrTab = make<StringTableSection>(".shstrtab", false);
270
1.26k
271
1.26k
  Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
272
1.26k
  Out::ElfHeader->Size = sizeof(Elf_Ehdr);
273
1.26k
  Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
274
1.26k
  Out::ProgramHeaders->updateAlignment(Config->Wordsize);
275
1.26k
276
1.26k
  if (
needsInterpSection()1.26k
) {
277
2
    InX::Interp = createInterpSection();
278
2
    Add(InX::Interp);
279
1.26k
  } else {
280
1.26k
    InX::Interp = nullptr;
281
1.26k
  }
282
1.26k
283
1.26k
  if (
Config->Strip != StripPolicy::All1.26k
) {
284
1.26k
    InX::StrTab = make<StringTableSection>(".strtab", false);
285
1.26k
    InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab);
286
1.26k
  }
287
1.26k
288
1.26k
  if (
Config->BuildId != BuildIdKind::None1.26k
) {
289
12
    InX::BuildId = make<BuildIdSection>();
290
12
    Add(InX::BuildId);
291
12
  }
292
1.26k
293
1.26k
  for (InputSection *S : createCommonSections())
294
76
    Add(S);
295
1.26k
296
1.26k
  InX::Bss = make<BssSection>(".bss");
297
1.26k
  Add(InX::Bss);
298
1.26k
  InX::BssRelRo = make<BssSection>(".bss.rel.ro");
299
1.26k
  Add(InX::BssRelRo);
300
1.26k
301
1.26k
  // Add MIPS-specific sections.
302
1.26k
  if (
Config->EMachine == EM_MIPS1.26k
) {
303
2
    if (
!Config->Shared && 2
Config->HasDynSymTab2
) {
304
0
      InX::MipsRldMap = make<MipsRldMapSection>();
305
0
      Add(InX::MipsRldMap);
306
0
    }
307
2
    if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
308
2
      Add(Sec);
309
2
    if (auto *Sec = MipsOptionsSection<ELFT>::create())
310
2
      Add(Sec);
311
2
    if (auto *Sec = MipsReginfoSection<ELFT>::create())
312
0
      Add(Sec);
313
2
  }
314
1.26k
315
1.26k
  if (
Config->HasDynSymTab1.26k
) {
316
618
    InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab);
317
618
    Add(InX::DynSymTab);
318
618
319
618
    In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
320
618
    Add(In<ELFT>::VerSym);
321
618
322
618
    if (
!Config->VersionDefinitions.empty()618
) {
323
36
      In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
324
36
      Add(In<ELFT>::VerDef);
325
36
    }
326
618
327
618
    In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
328
618
    Add(In<ELFT>::VerNeed);
329
618
330
618
    if (
Config->GnuHash618
) {
331
2
      InX::GnuHashTab = make<GnuHashTableSection>();
332
2
      Add(InX::GnuHashTab);
333
2
    }
334
618
335
618
    if (
Config->SysvHash618
) {
336
616
      InX::HashTab = make<HashTableSection>();
337
616
      Add(InX::HashTab);
338
616
    }
339
618
340
618
    Add(InX::Dynamic);
341
618
    Add(InX::DynStrTab);
342
618
    Add(In<ELFT>::RelaDyn);
343
618
  }
344
1.26k
345
1.26k
  // Add .got. MIPS' .got is so different from the other archs,
346
1.26k
  // it has its own class.
347
1.26k
  if (
Config->EMachine == EM_MIPS1.26k
) {
348
2
    InX::MipsGot = make<MipsGotSection>();
349
2
    Add(InX::MipsGot);
350
1.26k
  } else {
351
1.26k
    InX::Got = make<GotSection>();
352
1.26k
    Add(InX::Got);
353
1.26k
  }
354
1.26k
355
1.26k
  InX::GotPlt = make<GotPltSection>();
356
1.26k
  Add(InX::GotPlt);
357
1.26k
  InX::IgotPlt = make<IgotPltSection>();
358
1.26k
  Add(InX::IgotPlt);
359
1.26k
360
1.26k
  if (
Config->GdbIndex1.26k
) {
361
8
    InX::GdbIndex = createGdbIndex<ELFT>();
362
8
    Add(InX::GdbIndex);
363
8
  }
364
1.26k
365
1.26k
  // We always need to add rel[a].plt to output if it has entries.
366
1.26k
  // Even for static linking it can contain R_[*]_IRELATIVE relocations.
367
1.26k
  In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>(
368
1.26k
      Config->IsRela ? 
".rela.plt"1.26k
:
".rel.plt"0
, false /*Sort*/);
369
1.26k
  Add(In<ELFT>::RelaPlt);
370
1.26k
371
1.26k
  // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
372
1.26k
  // that the IRelative relocations are processed last by the dynamic loader
373
1.26k
  In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>(
374
1.26k
      (Config->EMachine == EM_ARM) ? 
".rel.dyn"0
:
In<ELFT>::RelaPlt->Name1.26k
,
375
1.26k
      false /*Sort*/);
376
1.26k
  Add(In<ELFT>::RelaIplt);
377
1.26k
378
1.26k
  InX::Plt = make<PltSection>(Target->PltHeaderSize);
379
1.26k
  Add(InX::Plt);
380
1.26k
  InX::Iplt = make<PltSection>(0);
381
1.26k
  Add(InX::Iplt);
382
1.26k
383
1.26k
  if (
!Config->Relocatable1.26k
) {
384
1.22k
    if (
Config->EhFrameHdr1.22k
) {
385
12
      In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>();
386
12
      Add(In<ELFT>::EhFrameHdr);
387
12
    }
388
1.22k
    In<ELFT>::EhFrame = make<EhFrameSection<ELFT>>();
389
1.22k
    Add(In<ELFT>::EhFrame);
390
1.22k
  }
391
1.26k
392
1.26k
  if (InX::SymTab)
393
1.26k
    Add(InX::SymTab);
394
1.26k
  Add(InX::ShStrTab);
395
1.26k
  if (InX::StrTab)
396
1.26k
    Add(InX::StrTab);
397
1.26k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::createSyntheticSections()
Line
Count
Source
258
193
template <class ELFT> void Writer<ELFT>::createSyntheticSections() {
259
193
  // Initialize all pointers with NULL. This is needed because
260
193
  // you can call lld::elf::main more than once as a library.
261
193
  memset(&Out::First, 0, sizeof(Out));
262
193
263
193
  auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
264
193
265
193
  InX::DynStrTab = make<StringTableSection>(".dynstr", true);
266
193
  InX::Dynamic = make<DynamicSection<ELFT>>();
267
193
  In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>(
268
193
      Config->IsRela ? 
".rela.dyn"3
:
".rel.dyn"190
, Config->ZCombreloc);
269
193
  InX::ShStrTab = make<StringTableSection>(".shstrtab", false);
270
193
271
193
  Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
272
193
  Out::ElfHeader->Size = sizeof(Elf_Ehdr);
273
193
  Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
274
193
  Out::ProgramHeaders->updateAlignment(Config->Wordsize);
275
193
276
193
  if (
needsInterpSection()193
) {
277
1
    InX::Interp = createInterpSection();
278
1
    Add(InX::Interp);
279
193
  } else {
280
192
    InX::Interp = nullptr;
281
192
  }
282
193
283
193
  if (
Config->Strip != StripPolicy::All193
) {
284
193
    InX::StrTab = make<StringTableSection>(".strtab", false);
285
193
    InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab);
286
193
  }
287
193
288
193
  if (
Config->BuildId != BuildIdKind::None193
) {
289
0
    InX::BuildId = make<BuildIdSection>();
290
0
    Add(InX::BuildId);
291
0
  }
292
193
293
193
  for (InputSection *S : createCommonSections())
294
6
    Add(S);
295
193
296
193
  InX::Bss = make<BssSection>(".bss");
297
193
  Add(InX::Bss);
298
193
  InX::BssRelRo = make<BssSection>(".bss.rel.ro");
299
193
  Add(InX::BssRelRo);
300
193
301
193
  // Add MIPS-specific sections.
302
193
  if (
Config->EMachine == EM_MIPS193
) {
303
14
    if (
!Config->Shared && 14
Config->HasDynSymTab8
) {
304
2
      InX::MipsRldMap = make<MipsRldMapSection>();
305
2
      Add(InX::MipsRldMap);
306
2
    }
307
14
    if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
308
13
      Add(Sec);
309
14
    if (auto *Sec = MipsOptionsSection<ELFT>::create())
310
0
      Add(Sec);
311
14
    if (auto *Sec = MipsReginfoSection<ELFT>::create())
312
13
      Add(Sec);
313
14
  }
314
193
315
193
  if (
Config->HasDynSymTab193
) {
316
108
    InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab);
317
108
    Add(InX::DynSymTab);
318
108
319
108
    In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
320
108
    Add(In<ELFT>::VerSym);
321
108
322
108
    if (
!Config->VersionDefinitions.empty()108
) {
323
0
      In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
324
0
      Add(In<ELFT>::VerDef);
325
0
    }
326
108
327
108
    In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
328
108
    Add(In<ELFT>::VerNeed);
329
108
330
108
    if (
Config->GnuHash108
) {
331
2
      InX::GnuHashTab = make<GnuHashTableSection>();
332
2
      Add(InX::GnuHashTab);
333
2
    }
334
108
335
108
    if (
Config->SysvHash108
) {
336
106
      InX::HashTab = make<HashTableSection>();
337
106
      Add(InX::HashTab);
338
106
    }
339
108
340
108
    Add(InX::Dynamic);
341
108
    Add(InX::DynStrTab);
342
108
    Add(In<ELFT>::RelaDyn);
343
108
  }
344
193
345
193
  // Add .got. MIPS' .got is so different from the other archs,
346
193
  // it has its own class.
347
193
  if (
Config->EMachine == EM_MIPS193
) {
348
14
    InX::MipsGot = make<MipsGotSection>();
349
14
    Add(InX::MipsGot);
350
193
  } else {
351
179
    InX::Got = make<GotSection>();
352
179
    Add(InX::Got);
353
179
  }
354
193
355
193
  InX::GotPlt = make<GotPltSection>();
356
193
  Add(InX::GotPlt);
357
193
  InX::IgotPlt = make<IgotPltSection>();
358
193
  Add(InX::IgotPlt);
359
193
360
193
  if (
Config->GdbIndex193
) {
361
1
    InX::GdbIndex = createGdbIndex<ELFT>();
362
1
    Add(InX::GdbIndex);
363
1
  }
364
193
365
193
  // We always need to add rel[a].plt to output if it has entries.
366
193
  // Even for static linking it can contain R_[*]_IRELATIVE relocations.
367
193
  In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>(
368
193
      Config->IsRela ? 
".rela.plt"3
:
".rel.plt"190
, false /*Sort*/);
369
193
  Add(In<ELFT>::RelaPlt);
370
193
371
193
  // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
372
193
  // that the IRelative relocations are processed last by the dynamic loader
373
193
  In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>(
374
193
      (Config->EMachine == EM_ARM) ? 
".rel.dyn"82
:
In<ELFT>::RelaPlt->Name111
,
375
193
      false /*Sort*/);
376
193
  Add(In<ELFT>::RelaIplt);
377
193
378
193
  InX::Plt = make<PltSection>(Target->PltHeaderSize);
379
193
  Add(InX::Plt);
380
193
  InX::Iplt = make<PltSection>(0);
381
193
  Add(InX::Iplt);
382
193
383
193
  if (
!Config->Relocatable193
) {
384
187
    if (
Config->EhFrameHdr187
) {
385
0
      In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>();
386
0
      Add(In<ELFT>::EhFrameHdr);
387
0
    }
388
187
    In<ELFT>::EhFrame = make<EhFrameSection<ELFT>>();
389
187
    Add(In<ELFT>::EhFrame);
390
187
  }
391
193
392
193
  if (InX::SymTab)
393
193
    Add(InX::SymTab);
394
193
  Add(InX::ShStrTab);
395
193
  if (InX::StrTab)
396
193
    Add(InX::StrTab);
397
193
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::createSyntheticSections()
Line
Count
Source
258
95
template <class ELFT> void Writer<ELFT>::createSyntheticSections() {
259
95
  // Initialize all pointers with NULL. This is needed because
260
95
  // you can call lld::elf::main more than once as a library.
261
95
  memset(&Out::First, 0, sizeof(Out));
262
95
263
95
  auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
264
95
265
95
  InX::DynStrTab = make<StringTableSection>(".dynstr", true);
266
95
  InX::Dynamic = make<DynamicSection<ELFT>>();
267
95
  In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>(
268
95
      Config->IsRela ? 
".rela.dyn"1
:
".rel.dyn"94
, Config->ZCombreloc);
269
95
  InX::ShStrTab = make<StringTableSection>(".shstrtab", false);
270
95
271
95
  Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
272
95
  Out::ElfHeader->Size = sizeof(Elf_Ehdr);
273
95
  Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
274
95
  Out::ProgramHeaders->updateAlignment(Config->Wordsize);
275
95
276
95
  if (
needsInterpSection()95
) {
277
0
    InX::Interp = createInterpSection();
278
0
    Add(InX::Interp);
279
95
  } else {
280
95
    InX::Interp = nullptr;
281
95
  }
282
95
283
95
  if (
Config->Strip != StripPolicy::All95
) {
284
95
    InX::StrTab = make<StringTableSection>(".strtab", false);
285
95
    InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab);
286
95
  }
287
95
288
95
  if (
Config->BuildId != BuildIdKind::None95
) {
289
0
    InX::BuildId = make<BuildIdSection>();
290
0
    Add(InX::BuildId);
291
0
  }
292
95
293
95
  for (InputSection *S : createCommonSections())
294
0
    Add(S);
295
95
296
95
  InX::Bss = make<BssSection>(".bss");
297
95
  Add(InX::Bss);
298
95
  InX::BssRelRo = make<BssSection>(".bss.rel.ro");
299
95
  Add(InX::BssRelRo);
300
95
301
95
  // Add MIPS-specific sections.
302
95
  if (
Config->EMachine == EM_MIPS95
) {
303
93
    if (
!Config->Shared && 93
Config->HasDynSymTab53
) {
304
13
      InX::MipsRldMap = make<MipsRldMapSection>();
305
13
      Add(InX::MipsRldMap);
306
13
    }
307
93
    if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
308
92
      Add(Sec);
309
93
    if (auto *Sec = MipsOptionsSection<ELFT>::create())
310
0
      Add(Sec);
311
93
    if (auto *Sec = MipsReginfoSection<ELFT>::create())
312
92
      Add(Sec);
313
93
  }
314
95
315
95
  if (
Config->HasDynSymTab95
) {
316
54
    InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab);
317
54
    Add(InX::DynSymTab);
318
54
319
54
    In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
320
54
    Add(In<ELFT>::VerSym);
321
54
322
54
    if (
!Config->VersionDefinitions.empty()54
) {
323
0
      In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
324
0
      Add(In<ELFT>::VerDef);
325
0
    }
326
54
327
54
    In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
328
54
    Add(In<ELFT>::VerNeed);
329
54
330
54
    if (
Config->GnuHash54
) {
331
0
      InX::GnuHashTab = make<GnuHashTableSection>();
332
0
      Add(InX::GnuHashTab);
333
0
    }
334
54
335
54
    if (
Config->SysvHash54
) {
336
54
      InX::HashTab = make<HashTableSection>();
337
54
      Add(InX::HashTab);
338
54
    }
339
54
340
54
    Add(InX::Dynamic);
341
54
    Add(InX::DynStrTab);
342
54
    Add(In<ELFT>::RelaDyn);
343
54
  }
344
95
345
95
  // Add .got. MIPS' .got is so different from the other archs,
346
95
  // it has its own class.
347
95
  if (
Config->EMachine == EM_MIPS95
) {
348
93
    InX::MipsGot = make<MipsGotSection>();
349
93
    Add(InX::MipsGot);
350
95
  } else {
351
2
    InX::Got = make<GotSection>();
352
2
    Add(InX::Got);
353
2
  }
354
95
355
95
  InX::GotPlt = make<GotPltSection>();
356
95
  Add(InX::GotPlt);
357
95
  InX::IgotPlt = make<IgotPltSection>();
358
95
  Add(InX::IgotPlt);
359
95
360
95
  if (
Config->GdbIndex95
) {
361
0
    InX::GdbIndex = createGdbIndex<ELFT>();
362
0
    Add(InX::GdbIndex);
363
0
  }
364
95
365
95
  // We always need to add rel[a].plt to output if it has entries.
366
95
  // Even for static linking it can contain R_[*]_IRELATIVE relocations.
367
95
  In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>(
368
95
      Config->IsRela ? 
".rela.plt"1
:
".rel.plt"94
, false /*Sort*/);
369
95
  Add(In<ELFT>::RelaPlt);
370
95
371
95
  // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
372
95
  // that the IRelative relocations are processed last by the dynamic loader
373
95
  In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>(
374
95
      (Config->EMachine == EM_ARM) ? 
".rel.dyn"0
:
In<ELFT>::RelaPlt->Name95
,
375
95
      false /*Sort*/);
376
95
  Add(In<ELFT>::RelaIplt);
377
95
378
95
  InX::Plt = make<PltSection>(Target->PltHeaderSize);
379
95
  Add(InX::Plt);
380
95
  InX::Iplt = make<PltSection>(0);
381
95
  Add(InX::Iplt);
382
95
383
95
  if (
!Config->Relocatable95
) {
384
87
    if (
Config->EhFrameHdr87
) {
385
1
      In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>();
386
1
      Add(In<ELFT>::EhFrameHdr);
387
1
    }
388
87
    In<ELFT>::EhFrame = make<EhFrameSection<ELFT>>();
389
87
    Add(In<ELFT>::EhFrame);
390
87
  }
391
95
392
95
  if (InX::SymTab)
393
95
    Add(InX::SymTab);
394
95
  Add(InX::ShStrTab);
395
95
  if (InX::StrTab)
396
95
    Add(InX::StrTab);
397
95
}
398
399
static bool shouldKeepInSymtab(SectionBase *Sec, StringRef SymName,
400
1.21k
                               const SymbolBody &B) {
401
1.21k
  if (
B.isFile() || 1.21k
B.isSection()1.07k
)
402
549
    return false;
403
666
404
666
  // If sym references a section in a discarded group, don't keep it.
405
666
  
if (666
Sec == &InputSection::Discarded666
)
406
0
    return false;
407
666
408
666
  
if (666
Config->Discard == DiscardPolicy::None666
)
409
43
    return true;
410
623
411
623
  // In ELF assembly .L symbols are normally discarded by the assembler.
412
623
  // If the assembler fails to do so, the linker discards them if
413
623
  // * --discard-locals is used.
414
623
  // * The symbol is in a SHF_MERGE section, which is normally the reason for
415
623
  //   the assembler keeping the .L symbol.
416
623
  
if (623
!SymName.startswith(".L") && 623
!SymName.empty()615
)
417
613
    return true;
418
10
419
10
  
if (10
Config->Discard == DiscardPolicy::Locals10
)
420
2
    return false;
421
8
422
8
  
return !Sec || 8
!(Sec->Flags & SHF_MERGE)6
;
423
1.21k
}
424
425
5.95k
static bool includeInSymtab(const SymbolBody &B) {
426
5.95k
  if (
!B.isLocal() && 5.95k
!B.symbol()->IsUsedInRegularObj4.65k
)
427
338
    return false;
428
5.61k
429
5.61k
  
if (auto *5.61k
D5.61k
= dyn_cast<DefinedRegular>(&B)) {
430
5.02k
    // Always include absolute symbols.
431
5.02k
    SectionBase *Sec = D->Section;
432
5.02k
    if (!Sec)
433
549
      return true;
434
4.48k
    
if (auto *4.48k
IS4.48k
= dyn_cast<InputSectionBase>(Sec)) {
435
4.35k
      Sec = IS->Repl;
436
4.35k
      IS = cast<InputSectionBase>(Sec);
437
4.35k
      // Exclude symbols pointing to garbage-collected sections.
438
4.35k
      if (!IS->Live)
439
97
        return false;
440
4.38k
    }
441
4.38k
    
if (auto *4.38k
S4.38k
= dyn_cast<MergeInputSection>(Sec))
442
46
      
if (46
!S->getSectionPiece(D->Value)->Live46
)
443
6
        return false;
444
4.37k
    return true;
445
4.37k
  }
446
585
447
585
  
if (auto *585
Sym585
= dyn_cast<DefinedCommon>(&B))
448
87
    return Sym->Live;
449
498
  return true;
450
498
}
451
452
// Local symbols are not in the linker's symbol table. This function scans
453
// each object file's symbol table to copy local symbols to the output.
454
1.59k
template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
455
1.59k
  if (!InX::SymTab)
456
3
    return;
457
1.59k
  
for (InputFile *File : ObjectFiles) 1.59k
{
458
1.90k
    ObjFile<ELFT> *F = cast<ObjFile<ELFT>>(File);
459
1.30k
    for (SymbolBody *B : F->getLocalSymbols()) {
460
1.30k
      if (!B->IsLocal)
461
0
        fatal(toString(F) +
462
0
              ": broken object: getLocalSymbols returns a non-local symbol");
463
1.30k
      auto *DR = dyn_cast<DefinedRegular>(B);
464
1.30k
465
1.30k
      // No reason to keep local undefined symbol in symtab.
466
1.30k
      if (!DR)
467
4
        continue;
468
1.30k
      
if (1.30k
!includeInSymtab(*B)1.30k
)
469
87
        continue;
470
1.21k
471
1.21k
      SectionBase *Sec = DR->Section;
472
1.21k
      if (!shouldKeepInSymtab(Sec, B->getName(), *B))
473
557
        continue;
474
658
      InX::SymTab->addSymbol(B);
475
658
    }
476
1.90k
  }
477
1.59k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::copyLocalSymbols()
Line
Count
Source
454
1.26k
template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
455
1.26k
  if (!InX::SymTab)
456
3
    return;
457
1.26k
  
for (InputFile *File : ObjectFiles) 1.26k
{
458
1.50k
    ObjFile<ELFT> *F = cast<ObjFile<ELFT>>(File);
459
809
    for (SymbolBody *B : F->getLocalSymbols()) {
460
809
      if (!B->IsLocal)
461
0
        fatal(toString(F) +
462
0
              ": broken object: getLocalSymbols returns a non-local symbol");
463
809
      auto *DR = dyn_cast<DefinedRegular>(B);
464
809
465
809
      // No reason to keep local undefined symbol in symtab.
466
809
      if (!DR)
467
4
        continue;
468
805
      
if (805
!includeInSymtab(*B)805
)
469
73
        continue;
470
732
471
732
      SectionBase *Sec = DR->Section;
472
732
      if (!shouldKeepInSymtab(Sec, B->getName(), *B))
473
390
        continue;
474
342
      InX::SymTab->addSymbol(B);
475
342
    }
476
1.50k
  }
477
1.26k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::copyLocalSymbols()
Line
Count
Source
454
43
template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
455
43
  if (!InX::SymTab)
456
0
    return;
457
43
  
for (InputFile *File : ObjectFiles) 43
{
458
50
    ObjFile<ELFT> *F = cast<ObjFile<ELFT>>(File);
459
41
    for (SymbolBody *B : F->getLocalSymbols()) {
460
41
      if (!B->IsLocal)
461
0
        fatal(toString(F) +
462
0
              ": broken object: getLocalSymbols returns a non-local symbol");
463
41
      auto *DR = dyn_cast<DefinedRegular>(B);
464
41
465
41
      // No reason to keep local undefined symbol in symtab.
466
41
      if (!DR)
467
0
        continue;
468
41
      
if (41
!includeInSymtab(*B)41
)
469
4
        continue;
470
37
471
37
      SectionBase *Sec = DR->Section;
472
37
      if (!shouldKeepInSymtab(Sec, B->getName(), *B))
473
24
        continue;
474
13
      InX::SymTab->addSymbol(B);
475
13
    }
476
50
  }
477
43
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::copyLocalSymbols()
Line
Count
Source
454
193
template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
455
193
  if (!InX::SymTab)
456
0
    return;
457
193
  
for (InputFile *File : ObjectFiles) 193
{
458
221
    ObjFile<ELFT> *F = cast<ObjFile<ELFT>>(File);
459
341
    for (SymbolBody *B : F->getLocalSymbols()) {
460
341
      if (!B->IsLocal)
461
0
        fatal(toString(F) +
462
0
              ": broken object: getLocalSymbols returns a non-local symbol");
463
341
      auto *DR = dyn_cast<DefinedRegular>(B);
464
341
465
341
      // No reason to keep local undefined symbol in symtab.
466
341
      if (!DR)
467
0
        continue;
468
341
      
if (341
!includeInSymtab(*B)341
)
469
8
        continue;
470
333
471
333
      SectionBase *Sec = DR->Section;
472
333
      if (!shouldKeepInSymtab(Sec, B->getName(), *B))
473
85
        continue;
474
248
      InX::SymTab->addSymbol(B);
475
248
    }
476
221
  }
477
193
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::copyLocalSymbols()
Line
Count
Source
454
94
template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
455
94
  if (!InX::SymTab)
456
0
    return;
457
94
  
for (InputFile *File : ObjectFiles) 94
{
458
124
    ObjFile<ELFT> *F = cast<ObjFile<ELFT>>(File);
459
115
    for (SymbolBody *B : F->getLocalSymbols()) {
460
115
      if (!B->IsLocal)
461
0
        fatal(toString(F) +
462
0
              ": broken object: getLocalSymbols returns a non-local symbol");
463
115
      auto *DR = dyn_cast<DefinedRegular>(B);
464
115
465
115
      // No reason to keep local undefined symbol in symtab.
466
115
      if (!DR)
467
0
        continue;
468
115
      
if (115
!includeInSymtab(*B)115
)
469
2
        continue;
470
113
471
113
      SectionBase *Sec = DR->Section;
472
113
      if (!shouldKeepInSymtab(Sec, B->getName(), *B))
473
58
        continue;
474
55
      InX::SymTab->addSymbol(B);
475
55
    }
476
124
  }
477
94
}
478
479
72
template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
480
72
  // Create one STT_SECTION symbol for each output section we might
481
72
  // have a relocation with.
482
1.01k
  for (BaseCommand *Base : Script->Opt.Commands) {
483
1.01k
    auto *Sec = dyn_cast<OutputSection>(Base);
484
1.01k
    if (!Sec)
485
66
      continue;
486
951
    
auto I = llvm::find_if(Sec->Commands, [](BaseCommand *Base) 951
{
487
951
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
488
949
        return !ISD->Sections.empty();
489
2
      return false;
490
2
    });
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
486
116
    auto I = llvm::find_if(Sec->Commands, [](BaseCommand *Base) {
487
116
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
488
116
        return !ISD->Sections.empty();
489
0
      return false;
490
0
    });
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
486
15
    auto I = llvm::find_if(Sec->Commands, [](BaseCommand *Base) {
487
15
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
488
15
        return !ISD->Sections.empty();
489
0
      return false;
490
0
    });
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
486
110
    auto I = llvm::find_if(Sec->Commands, [](BaseCommand *Base) {
487
110
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
488
109
        return !ISD->Sections.empty();
489
1
      return false;
490
1
    });
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
486
710
    auto I = llvm::find_if(Sec->Commands, [](BaseCommand *Base) {
487
710
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
488
709
        return !ISD->Sections.empty();
489
1
      return false;
490
1
    });
491
951
    if (I == Sec->Commands.end())
492
2
      continue;
493
949
    InputSection *IS = cast<InputSectionDescription>(*I)->Sections[0];
494
949
    if (
isa<SyntheticSection>(IS) || 949
IS->Type == SHT_REL223
||
495
206
        IS->Type == SHT_RELA)
496
776
      continue;
497
173
498
173
    auto *Sym =
499
173
        make<DefinedRegular>("", /*IsLocal=*/true, /*StOther=*/0, STT_SECTION,
500
173
                             /*Value=*/0, /*Size=*/0, IS);
501
173
    InX::SymTab->addSymbol(Sym);
502
173
  }
503
72
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addSectionSymbols()
Line
Count
Source
479
1
template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
480
1
  // Create one STT_SECTION symbol for each output section we might
481
1
  // have a relocation with.
482
16
  for (BaseCommand *Base : Script->Opt.Commands) {
483
16
    auto *Sec = dyn_cast<OutputSection>(Base);
484
16
    if (!Sec)
485
1
      continue;
486
15
    auto I = llvm::find_if(Sec->Commands, [](BaseCommand *Base) {
487
15
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
488
15
        return !ISD->Sections.empty();
489
15
      return false;
490
15
    });
491
15
    if (I == Sec->Commands.end())
492
0
      continue;
493
15
    InputSection *IS = cast<InputSectionDescription>(*I)->Sections[0];
494
15
    if (
isa<SyntheticSection>(IS) || 15
IS->Type == SHT_REL5
||
495
5
        IS->Type == SHT_RELA)
496
10
      continue;
497
5
498
5
    auto *Sym =
499
5
        make<DefinedRegular>("", /*IsLocal=*/true, /*StOther=*/0, STT_SECTION,
500
5
                             /*Value=*/0, /*Size=*/0, IS);
501
5
    InX::SymTab->addSymbol(Sym);
502
5
  }
503
1
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addSectionSymbols()
Line
Count
Source
479
7
template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
480
7
  // Create one STT_SECTION symbol for each output section we might
481
7
  // have a relocation with.
482
116
  for (BaseCommand *Base : Script->Opt.Commands) {
483
116
    auto *Sec = dyn_cast<OutputSection>(Base);
484
116
    if (!Sec)
485
6
      continue;
486
110
    auto I = llvm::find_if(Sec->Commands, [](BaseCommand *Base) {
487
110
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
488
110
        return !ISD->Sections.empty();
489
110
      return false;
490
110
    });
491
110
    if (I == Sec->Commands.end())
492
1
      continue;
493
109
    InputSection *IS = cast<InputSectionDescription>(*I)->Sections[0];
494
109
    if (
isa<SyntheticSection>(IS) || 109
IS->Type == SHT_REL33
||
495
23
        IS->Type == SHT_RELA)
496
86
      continue;
497
23
498
23
    auto *Sym =
499
23
        make<DefinedRegular>("", /*IsLocal=*/true, /*StOther=*/0, STT_SECTION,
500
23
                             /*Value=*/0, /*Size=*/0, IS);
501
23
    InX::SymTab->addSymbol(Sym);
502
23
  }
503
7
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addSectionSymbols()
Line
Count
Source
479
56
template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
480
56
  // Create one STT_SECTION symbol for each output section we might
481
56
  // have a relocation with.
482
761
  for (BaseCommand *Base : Script->Opt.Commands) {
483
761
    auto *Sec = dyn_cast<OutputSection>(Base);
484
761
    if (!Sec)
485
51
      continue;
486
710
    auto I = llvm::find_if(Sec->Commands, [](BaseCommand *Base) {
487
710
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
488
710
        return !ISD->Sections.empty();
489
710
      return false;
490
710
    });
491
710
    if (I == Sec->Commands.end())
492
1
      continue;
493
709
    InputSection *IS = cast<InputSectionDescription>(*I)->Sections[0];
494
709
    if (
isa<SyntheticSection>(IS) || 709
IS->Type == SHT_REL149
||
495
149
        IS->Type == SHT_RELA)
496
593
      continue;
497
116
498
116
    auto *Sym =
499
116
        make<DefinedRegular>("", /*IsLocal=*/true, /*StOther=*/0, STT_SECTION,
500
116
                             /*Value=*/0, /*Size=*/0, IS);
501
116
    InX::SymTab->addSymbol(Sym);
502
116
  }
503
56
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addSectionSymbols()
Line
Count
Source
479
8
template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
480
8
  // Create one STT_SECTION symbol for each output section we might
481
8
  // have a relocation with.
482
124
  for (BaseCommand *Base : Script->Opt.Commands) {
483
124
    auto *Sec = dyn_cast<OutputSection>(Base);
484
124
    if (!Sec)
485
8
      continue;
486
116
    auto I = llvm::find_if(Sec->Commands, [](BaseCommand *Base) {
487
116
      if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
488
116
        return !ISD->Sections.empty();
489
116
      return false;
490
116
    });
491
116
    if (I == Sec->Commands.end())
492
0
      continue;
493
116
    InputSection *IS = cast<InputSectionDescription>(*I)->Sections[0];
494
116
    if (
isa<SyntheticSection>(IS) || 116
IS->Type == SHT_REL36
||
495
29
        IS->Type == SHT_RELA)
496
87
      continue;
497
29
498
29
    auto *Sym =
499
29
        make<DefinedRegular>("", /*IsLocal=*/true, /*StOther=*/0, STT_SECTION,
500
29
                             /*Value=*/0, /*Size=*/0, IS);
501
29
    InX::SymTab->addSymbol(Sym);
502
29
  }
503
8
}
504
505
// Today's loaders have a feature to make segments read-only after
506
// processing dynamic relocations to enhance security. PT_GNU_RELRO
507
// is defined for that.
508
//
509
// This function returns true if a section needs to be put into a
510
// PT_GNU_RELRO segment.
511
144k
static bool isRelroSection(const OutputSection *Sec) {
512
144k
  if (!Config->ZRelro)
513
86
    return false;
514
144k
515
144k
  uint64_t Flags = Sec->Flags;
516
144k
517
144k
  // Non-allocatable or non-writable sections don't need RELRO because
518
144k
  // they are not writable or not even mapped to memory in the first place.
519
144k
  // RELRO is for sections that are essentially read-only but need to
520
144k
  // be writable only at process startup to allow dynamic linker to
521
144k
  // apply relocations.
522
144k
  if (
!(Flags & SHF_ALLOC) || 144k
!(Flags & SHF_WRITE)144k
)
523
140k
    return false;
524
3.46k
525
3.46k
  // Once initialized, TLS data segments are used as data templates
526
3.46k
  // for a thread-local storage. For each new thread, runtime
527
3.46k
  // allocates memory for a TLS and copy templates there. No thread
528
3.46k
  // are supposed to use templates directly. Thus, it can be in RELRO.
529
3.46k
  
if (3.46k
Flags & SHF_TLS3.46k
)
530
131
    return true;
531
3.33k
532
3.33k
  // .init_array, .preinit_array and .fini_array contain pointers to
533
3.33k
  // functions that are executed on process startup or exit. These
534
3.33k
  // pointers are set by the static linker, and they are not expected
535
3.33k
  // to change at runtime. But if you are an attacker, you could do
536
3.33k
  // interesting things by manipulating pointers in .fini_array, for
537
3.33k
  // example. So they are put into RELRO.
538
3.33k
  uint32_t Type = Sec->Type;
539
3.33k
  if (
Type == SHT_INIT_ARRAY || 3.33k
Type == SHT_FINI_ARRAY3.31k
||
540
3.30k
      Type == SHT_PREINIT_ARRAY)
541
44
    return true;
542
3.29k
543
3.29k
  // .got contains pointers to external symbols. They are resolved by
544
3.29k
  // the dynamic linker when a module is loaded into memory, and after
545
3.29k
  // that they are not expected to change. So, it can be in RELRO.
546
3.29k
  
if (3.29k
InX::Got && 3.29k
Sec == InX::Got->getParent()2.48k
)
547
190
    return true;
548
3.10k
549
3.10k
  // .got.plt contains pointers to external function symbols. They are
550
3.10k
  // by default resolved lazily, so we usually cannot put it into RELRO.
551
3.10k
  // However, if "-z now" is given, the lazy symbol resolution is
552
3.10k
  // disabled, which enables us to put it into RELRO.
553
3.10k
  
if (3.10k
Sec == InX::GotPlt->getParent()3.10k
)
554
272
    return Config->ZNow;
555
2.83k
556
2.83k
  // .dynamic section contains data for the dynamic linker, and
557
2.83k
  // there's no need to write to it at runtime, so it's better to put
558
2.83k
  // it into RELRO.
559
2.83k
  
if (2.83k
Sec == InX::Dynamic->getParent()2.83k
)
560
1.35k
    return true;
561
1.47k
562
1.47k
  // .bss.rel.ro is used for copy relocations for read-only symbols.
563
1.47k
  // Since the dynamic linker needs to process copy relocations, the
564
1.47k
  // section cannot be read-only, but once initialized, they shouldn't
565
1.47k
  // change.
566
1.47k
  
if (1.47k
Sec == InX::BssRelRo->getParent()1.47k
)
567
6
    return true;
568
1.46k
569
1.46k
  // Sections with some special names are put into RELRO. This is a
570
1.46k
  // bit unfortunate because section names shouldn't be significant in
571
1.46k
  // ELF in spirit. But in reality many linker features depend on
572
1.46k
  // magic section names.
573
1.46k
  StringRef S = Sec->Name;
574
1.46k
  return S == ".data.rel.ro" || 
S == ".ctors"1.45k
||
S == ".dtors"1.44k
||
S == ".jcr"1.43k
||
575
1.46k
         
S == ".eh_frame"1.43k
||
S == ".openbsd.randomdata"1.43k
;
576
144k
}
577
578
// We compute a rank for each section. The rank indicates where the
579
// section should be placed in the file.  Instead of using simple
580
// numbers (0,1,2...), we use a series of flags. One for each decision
581
// point when placing the section.
582
// Using flags has two key properties:
583
// * It is easy to check if a give branch was taken.
584
// * It is easy two see how similar two ranks are (see getRankProximity).
585
enum RankFlags {
586
  RF_NOT_ADDR_SET = 1 << 16,
587
  RF_NOT_INTERP = 1 << 15,
588
  RF_NOT_ALLOC = 1 << 14,
589
  RF_WRITE = 1 << 13,
590
  RF_EXEC_WRITE = 1 << 12,
591
  RF_EXEC = 1 << 11,
592
  RF_NON_TLS_BSS = 1 << 10,
593
  RF_NON_TLS_BSS_RO = 1 << 9,
594
  RF_NOT_TLS = 1 << 8,
595
  RF_BSS = 1 << 7,
596
  RF_PPC_NOT_TOCBSS = 1 << 6,
597
  RF_PPC_OPD = 1 << 5,
598
  RF_PPC_TOCL = 1 << 4,
599
  RF_PPC_TOC = 1 << 3,
600
  RF_PPC_BRANCH_LT = 1 << 2,
601
  RF_MIPS_GPREL = 1 << 1,
602
  RF_MIPS_NOT_GOT = 1 << 0
603
};
604
605
208k
static unsigned getSectionRank(const OutputSection *Sec) {
606
208k
  unsigned Rank = 0;
607
208k
608
208k
  // We want to put section specified by -T option first, so we
609
208k
  // can start assigning VA starting from them later.
610
208k
  if (Config->SectionStartMap.count(Sec->Name))
611
41
    return Rank;
612
208k
  Rank |= RF_NOT_ADDR_SET;
613
208k
614
208k
  // Put .interp first because some loaders want to see that section
615
208k
  // on the first page of the executable file when loaded into memory.
616
208k
  if (Sec->Name == ".interp")
617
4
    return Rank;
618
208k
  Rank |= RF_NOT_INTERP;
619
208k
620
208k
  // Allocatable sections go first to reduce the total PT_LOAD size and
621
208k
  // so debug info doesn't change addresses in actual code.
622
208k
  if (!(Sec->Flags & SHF_ALLOC))
623
136k
    return Rank | RF_NOT_ALLOC;
624
72.2k
625
72.2k
  // Sort sections based on their access permission in the following
626
72.2k
  // order: R, RX, RWX, RW.  This order is based on the following
627
72.2k
  // considerations:
628
72.2k
  // * Read-only sections come first such that they go in the
629
72.2k
  //   PT_LOAD covering the program headers at the start of the file.
630
72.2k
  // * Read-only, executable sections come next, unless the
631
72.2k
  //   -no-rosegment option is used.
632
72.2k
  // * Writable, executable sections follow such that .plt on
633
72.2k
  //   architectures where it needs to be writable will be placed
634
72.2k
  //   between .text and .data.
635
72.2k
  // * Writable sections come last, such that .bss lands at the very
636
72.2k
  //   end of the last PT_LOAD.
637
72.2k
  bool IsExec = Sec->Flags & SHF_EXECINSTR;
638
72.2k
  bool IsWrite = Sec->Flags & SHF_WRITE;
639
72.2k
640
72.2k
  if (
IsExec72.2k
) {
641
1.77k
    if (IsWrite)
642
18
      Rank |= RF_EXEC_WRITE;
643
1.75k
    else 
if (1.75k
!Config->SingleRoRx1.75k
)
644
1.38k
      Rank |= RF_EXEC;
645
72.2k
  } else {
646
70.4k
    if (IsWrite)
647
1.75k
      Rank |= RF_WRITE;
648
70.4k
  }
649
72.2k
650
72.2k
  // If we got here we know that both A and B are in the same PT_LOAD.
651
72.2k
652
72.2k
  bool IsTls = Sec->Flags & SHF_TLS;
653
72.2k
  bool IsNoBits = Sec->Type == SHT_NOBITS;
654
72.2k
655
72.2k
  // The first requirement we have is to put (non-TLS) nobits sections last. The
656
72.2k
  // reason is that the only thing the dynamic linker will see about them is a
657
72.2k
  // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
658
72.2k
  // PT_LOAD, so that has to correspond to the nobits sections.
659
279
  bool IsNonTlsNoBits = IsNoBits && !IsTls;
660
72.2k
  if (IsNonTlsNoBits)
661
228
    Rank |= RF_NON_TLS_BSS;
662
72.2k
663
72.2k
  // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
664
72.2k
  // sections after r/w ones, so that the RelRo sections are contiguous.
665
72.2k
  bool IsRelRo = isRelroSection(Sec);
666
72.2k
  if (
IsNonTlsNoBits && 72.2k
!IsRelRo228
)
667
225
    Rank |= RF_NON_TLS_BSS_RO;
668
72.2k
  if (
!IsNonTlsNoBits && 72.2k
IsRelRo71.9k
)
669
910
    Rank |= RF_NON_TLS_BSS_RO;
670
72.2k
671
72.2k
  // The TLS initialization block needs to be a single contiguous block in a R/W
672
72.2k
  // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
673
72.2k
  // sections. The TLS NOBITS sections are placed here as they don't take up
674
72.2k
  // virtual address space in the PT_LOAD.
675
72.2k
  if (!IsTls)
676
72.1k
    Rank |= RF_NOT_TLS;
677
72.2k
678
72.2k
  // Within the TLS initialization block, the non-nobits sections need to appear
679
72.2k
  // first.
680
72.2k
  if (IsNoBits)
681
279
    Rank |= RF_BSS;
682
72.2k
683
72.2k
  // Some architectures have additional ordering restrictions for sections
684
72.2k
  // within the same PT_LOAD.
685
72.2k
  if (
Config->EMachine == EM_PPC6472.2k
) {
686
96
    // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections
687
96
    // that we would like to make sure appear is a specific order to maximize
688
96
    // their coverage by a single signed 16-bit offset from the TOC base
689
96
    // pointer. Conversely, the special .tocbss section should be first among
690
96
    // all SHT_NOBITS sections. This will put it next to the loaded special
691
96
    // PPC64 sections (and, thus, within reach of the TOC base pointer).
692
96
    StringRef Name = Sec->Name;
693
96
    if (Name != ".tocbss")
694
96
      Rank |= RF_PPC_NOT_TOCBSS;
695
96
696
96
    if (Name == ".opd")
697
6
      Rank |= RF_PPC_OPD;
698
96
699
96
    if (Name == ".toc1")
700
1
      Rank |= RF_PPC_TOCL;
701
96
702
96
    if (Name == ".toc")
703
3
      Rank |= RF_PPC_TOC;
704
96
705
96
    if (Name == ".branch_lt")
706
0
      Rank |= RF_PPC_BRANCH_LT;
707
96
  }
708
72.2k
  if (
Config->EMachine == EM_MIPS72.2k
) {
709
1.14k
    // All sections with SHF_MIPS_GPREL flag should be grouped together
710
1.14k
    // because data in these sections is addressable with a gp relative address.
711
1.14k
    if (Sec->Flags & SHF_MIPS_GPREL)
712
129
      Rank |= RF_MIPS_GPREL;
713
1.14k
714
1.14k
    if (Sec->Name != ".got")
715
1.01k
      Rank |= RF_MIPS_NOT_GOT;
716
1.14k
  }
717
208k
718
208k
  return Rank;
719
208k
}
720
721
1.25M
static bool compareSections(const BaseCommand *ACmd, const BaseCommand *BCmd) {
722
1.25M
  const OutputSection *A = cast<OutputSection>(ACmd);
723
1.25M
  const OutputSection *B = cast<OutputSection>(BCmd);
724
1.25M
  if (A->SortRank != B->SortRank)
725
80.0k
    return A->SortRank < B->SortRank;
726
1.17M
  
if (1.17M
!(A->SortRank & RF_NOT_ADDR_SET)1.17M
)
727
20
    return Config->SectionStartMap.lookup(A->Name) <
728
20
           Config->SectionStartMap.lookup(B->Name);
729
1.17M
  return false;
730
1.17M
}
731
732
78.3k
void PhdrEntry::add(OutputSection *Sec) {
733
78.3k
  LastSec = Sec;
734
78.3k
  if (!FirstSec)
735
6.68k
    FirstSec = Sec;
736
78.3k
  p_align = std::max(p_align, Sec->Alignment);
737
78.3k
  if (p_type == PT_LOAD)
738
75.0k
    Sec->PtLoad = this;
739
78.3k
}
740
741
template <class ELFT>
742
static Symbol *addRegular(StringRef Name, SectionBase *Sec, uint64_t Value,
743
                          uint8_t StOther = STV_HIDDEN,
744
893
                          uint8_t Binding = STB_WEAK) {
745
893
  // The linker generated symbols are added as STB_WEAK to allow user defined
746
893
  // ones to override them.
747
893
  return Symtab->addRegular<ELFT>(Name, StOther, STT_NOTYPE, Value,
748
893
                                  /*Size=*/0, Binding, Sec,
749
893
                                  /*File=*/nullptr);
750
893
}
Writer.cpp:lld::elf::Symbol* addRegular<llvm::object::ELFType<(llvm::support::endianness)1, true> >(llvm::StringRef, lld::elf::SectionBase*, unsigned long long, unsigned char, unsigned char)
Line
Count
Source
744
691
                          uint8_t Binding = STB_WEAK) {
745
691
  // The linker generated symbols are added as STB_WEAK to allow user defined
746
691
  // ones to override them.
747
691
  return Symtab->addRegular<ELFT>(Name, StOther, STT_NOTYPE, Value,
748
691
                                  /*Size=*/0, Binding, Sec,
749
691
                                  /*File=*/nullptr);
750
691
}
Writer.cpp:lld::elf::Symbol* addRegular<llvm::object::ELFType<(llvm::support::endianness)1, false> >(llvm::StringRef, lld::elf::SectionBase*, unsigned long long, unsigned char, unsigned char)
Line
Count
Source
744
122
                          uint8_t Binding = STB_WEAK) {
745
122
  // The linker generated symbols are added as STB_WEAK to allow user defined
746
122
  // ones to override them.
747
122
  return Symtab->addRegular<ELFT>(Name, StOther, STT_NOTYPE, Value,
748
122
                                  /*Size=*/0, Binding, Sec,
749
122
                                  /*File=*/nullptr);
750
122
}
Writer.cpp:lld::elf::Symbol* addRegular<llvm::object::ELFType<(llvm::support::endianness)0, false> >(llvm::StringRef, lld::elf::SectionBase*, unsigned long long, unsigned char, unsigned char)
Line
Count
Source
744
54
                          uint8_t Binding = STB_WEAK) {
745
54
  // The linker generated symbols are added as STB_WEAK to allow user defined
746
54
  // ones to override them.
747
54
  return Symtab->addRegular<ELFT>(Name, StOther, STT_NOTYPE, Value,
748
54
                                  /*Size=*/0, Binding, Sec,
749
54
                                  /*File=*/nullptr);
750
54
}
Writer.cpp:lld::elf::Symbol* addRegular<llvm::object::ELFType<(llvm::support::endianness)0, true> >(llvm::StringRef, lld::elf::SectionBase*, unsigned long long, unsigned char, unsigned char)
Line
Count
Source
744
26
                          uint8_t Binding = STB_WEAK) {
745
26
  // The linker generated symbols are added as STB_WEAK to allow user defined
746
26
  // ones to override them.
747
26
  return Symtab->addRegular<ELFT>(Name, StOther, STT_NOTYPE, Value,
748
26
                                  /*Size=*/0, Binding, Sec,
749
26
                                  /*File=*/nullptr);
750
26
}
751
752
template <class ELFT>
753
static DefinedRegular *
754
addOptionalRegular(StringRef Name, SectionBase *Sec, uint64_t Val,
755
416k
                   uint8_t StOther = STV_HIDDEN, uint8_t Binding = STB_GLOBAL) {
756
416k
  SymbolBody *S = Symtab->find(Name);
757
416k
  if (!S)
758
415k
    return nullptr;
759
95
  
if (95
S->isInCurrentDSO()95
)
760
7
    return nullptr;
761
88
  return cast<DefinedRegular>(
762
88
      addRegular<ELFT>(Name, Sec, Val, StOther, Binding)->body());
763
88
}
Writer.cpp:lld::elf::DefinedRegular* addOptionalRegular<llvm::object::ELFType<(llvm::support::endianness)1, true> >(llvm::StringRef, lld::elf::SectionBase*, unsigned long long, unsigned char, unsigned char)
Line
Count
Source
755
410k
                   uint8_t StOther = STV_HIDDEN, uint8_t Binding = STB_GLOBAL) {
756
410k
  SymbolBody *S = Symtab->find(Name);
757
410k
  if (!S)
758
410k
    return nullptr;
759
80
  
if (80
S->isInCurrentDSO()80
)
760
7
    return nullptr;
761
73
  return cast<DefinedRegular>(
762
73
      addRegular<ELFT>(Name, Sec, Val, StOther, Binding)->body());
763
73
}
Writer.cpp:lld::elf::DefinedRegular* addOptionalRegular<llvm::object::ELFType<(llvm::support::endianness)0, true> >(llvm::StringRef, lld::elf::SectionBase*, unsigned long long, unsigned char, unsigned char)
Line
Count
Source
755
721
                   uint8_t StOther = STV_HIDDEN, uint8_t Binding = STB_GLOBAL) {
756
721
  SymbolBody *S = Symtab->find(Name);
757
721
  if (!S)
758
720
    return nullptr;
759
1
  
if (1
S->isInCurrentDSO()1
)
760
0
    return nullptr;
761
1
  return cast<DefinedRegular>(
762
1
      addRegular<ELFT>(Name, Sec, Val, StOther, Binding)->body());
763
1
}
Writer.cpp:lld::elf::DefinedRegular* addOptionalRegular<llvm::object::ELFType<(llvm::support::endianness)0, false> >(llvm::StringRef, lld::elf::SectionBase*, unsigned long long, unsigned char, unsigned char)
Line
Count
Source
755
1.43k
                   uint8_t StOther = STV_HIDDEN, uint8_t Binding = STB_GLOBAL) {
756
1.43k
  SymbolBody *S = Symtab->find(Name);
757
1.43k
  if (!S)
758
1.43k
    return nullptr;
759
0
  
if (0
S->isInCurrentDSO()0
)
760
0
    return nullptr;
761
0
  return cast<DefinedRegular>(
762
0
      addRegular<ELFT>(Name, Sec, Val, StOther, Binding)->body());
763
0
}
Writer.cpp:lld::elf::DefinedRegular* addOptionalRegular<llvm::object::ELFType<(llvm::support::endianness)1, false> >(llvm::StringRef, lld::elf::SectionBase*, unsigned long long, unsigned char, unsigned char)
Line
Count
Source
755
3.09k
                   uint8_t StOther = STV_HIDDEN, uint8_t Binding = STB_GLOBAL) {
756
3.09k
  SymbolBody *S = Symtab->find(Name);
757
3.09k
  if (!S)
758
3.08k
    return nullptr;
759
14
  
if (14
S->isInCurrentDSO()14
)
760
0
    return nullptr;
761
14
  return cast<DefinedRegular>(
762
14
      addRegular<ELFT>(Name, Sec, Val, StOther, Binding)->body());
763
14
}
764
765
// The beginning and the ending of .rel[a].plt section are marked
766
// with __rel[a]_iplt_{start,end} symbols if it is a statically linked
767
// executable. The runtime needs these symbols in order to resolve
768
// all IRELATIVE relocs on startup. For dynamic executables, we don't
769
// need these symbols, since IRELATIVE relocs are resolved through GOT
770
// and PLT. For details, see http://www.airs.com/blog/archives/403.
771
1.59k
template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
772
1.59k
  if (!Config->Static)
773
1.57k
    return;
774
20
  
StringRef S = Config->IsRela ? 20
"__rela_iplt_start"13
:
"__rel_iplt_start"7
;
775
20
  addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
776
20
777
20
  S = Config->IsRela ? 
"__rela_iplt_end"13
:
"__rel_iplt_end"7
;
778
1.59k
  addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
779
1.59k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addRelIpltSymbols()
Line
Count
Source
771
1.26k
template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
772
1.26k
  if (!Config->Static)
773
1.25k
    return;
774
12
  
StringRef S = Config->IsRela ? 12
"__rela_iplt_start"12
:
"__rel_iplt_start"0
;
775
12
  addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
776
12
777
12
  S = Config->IsRela ? 
"__rela_iplt_end"12
:
"__rel_iplt_end"0
;
778
1.26k
  addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
779
1.26k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addRelIpltSymbols()
Line
Count
Source
771
95
template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
772
95
  if (!Config->Static)
773
94
    return;
774
1
  
StringRef S = Config->IsRela ? 1
"__rela_iplt_start"0
:
"__rel_iplt_start"1
;
775
1
  addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
776
1
777
1
  S = Config->IsRela ? 
"__rela_iplt_end"0
:
"__rel_iplt_end"1
;
778
95
  addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
779
95
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addRelIpltSymbols()
Line
Count
Source
771
193
template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
772
193
  if (!Config->Static)
773
187
    return;
774
6
  
StringRef S = Config->IsRela ? 6
"__rela_iplt_start"0
:
"__rel_iplt_start"6
;
775
6
  addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
776
6
777
6
  S = Config->IsRela ? 
"__rela_iplt_end"0
:
"__rel_iplt_end"6
;
778
193
  addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
779
193
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addRelIpltSymbols()
Line
Count
Source
771
44
template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
772
44
  if (!Config->Static)
773
43
    return;
774
1
  
StringRef S = Config->IsRela ? 1
"__rela_iplt_start"1
:
"__rel_iplt_start"0
;
775
1
  addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
776
1
777
1
  S = Config->IsRela ? 
"__rela_iplt_end"1
:
"__rel_iplt_end"0
;
778
44
  addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
779
44
}
780
781
// The linker is expected to define some symbols depending on
782
// the linking result. This function defines such symbols.
783
1.53k
template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
784
1.53k
  if (
Config->EMachine == EM_MIPS1.53k
) {
785
128
    // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
786
128
    // so that it points to an absolute address which by default is relative
787
128
    // to GOT. Default offset is 0x7ff0.
788
128
    // See "Global Data Symbols" in Chapter 6 in the following document:
789
128
    // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
790
128
    ElfSym::MipsGp = Symtab->addAbsolute<ELFT>("_gp", STV_HIDDEN, STB_LOCAL);
791
128
792
128
    // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
793
128
    // start of function and 'gp' pointer into GOT.
794
128
    if (Symtab->find("_gp_disp"))
795
8
      ElfSym::MipsGpDisp =
796
8
          Symtab->addAbsolute<ELFT>("_gp_disp", STV_HIDDEN, STB_LOCAL);
797
128
798
128
    // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
799
128
    // pointer. This symbol is used in the code generated by .cpload pseudo-op
800
128
    // in case of using -mno-shared option.
801
128
    // https://sourceware.org/ml/binutils/2004-12/msg00094.html
802
128
    if (Symtab->find("__gnu_local_gp"))
803
1
      ElfSym::MipsLocalGp =
804
1
          Symtab->addAbsolute<ELFT>("__gnu_local_gp", STV_HIDDEN, STB_LOCAL);
805
128
  }
806
1.53k
807
1.53k
  // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
808
1.53k
  // be at some offset from the base of the .got section, usually 0 or the end
809
1.53k
  // of the .got
810
128
  InputSection *GotSection = InX::MipsGot ? cast<InputSection>(InX::MipsGot)
811
1.41k
                                          : cast<InputSection>(InX::Got);
812
1.53k
  ElfSym::GlobalOffsetTable = addOptionalRegular<ELFT>(
813
1.53k
      "_GLOBAL_OFFSET_TABLE_", GotSection, Target->GotBaseSymOff);
814
1.53k
815
1.53k
  // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
816
1.53k
  // static linking the linker is required to optimize away any references to
817
1.53k
  // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
818
1.53k
  // to avoid the undefined symbol error.
819
1.53k
  if (!InX::DynSymTab)
820
735
    Symtab->addIgnored<ELFT>("__tls_get_addr");
821
1.53k
822
1.53k
  // __ehdr_start is the location of ELF file headers. Note that we define
823
1.53k
  // this symbol unconditionally even when using a linker script, which
824
1.53k
  // differs from the behavior implemented by GNU linker which only define
825
1.53k
  // this symbol if ELF headers are in the memory mapped segment.
826
1.53k
  // __executable_start is not documented, but the expectation of at
827
1.53k
  // least the android libc is that it points to the elf header too.
828
1.53k
  // __dso_handle symbol is passed to cxa_finalize as a marker to identify
829
1.53k
  // each DSO. The address of the symbol doesn't matter as long as they are
830
1.53k
  // different in different DSOs, so we chose the start address of the DSO.
831
1.53k
  for (const char *Name :
832
1.53k
       {"__ehdr_start", "__executable_start", "__dso_handle"})
833
4.61k
    addOptionalRegular<ELFT>(Name, Out::ElfHeader, 0, STV_HIDDEN);
834
1.53k
835
1.53k
  // If linker script do layout we do not need to create any standart symbols.
836
1.53k
  if (Script->Opt.HasSections)
837
294
    return;
838
1.24k
839
1.24k
  
auto Add = [](StringRef S, int64_t Pos) 1.24k
{
840
8.70k
    return addOptionalRegular<ELFT>(S, Out::ElfHeader, Pos, STV_DEFAULT);
841
8.70k
  };
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addReservedSymbols()::'lambda'(llvm::StringRef, long long)::operator()(llvm::StringRef, long long) const
Line
Count
Source
839
560
  auto Add = [](StringRef S, int64_t Pos) {
840
560
    return addOptionalRegular<ELFT>(S, Out::ElfHeader, Pos, STV_DEFAULT);
841
560
  };
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addReservedSymbols()::'lambda'(llvm::StringRef, long long)::operator()(llvm::StringRef, long long) const
Line
Count
Source
839
287
  auto Add = [](StringRef S, int64_t Pos) {
840
287
    return addOptionalRegular<ELFT>(S, Out::ElfHeader, Pos, STV_DEFAULT);
841
287
  };
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addReservedSymbols()::'lambda'(llvm::StringRef, long long)::operator()(llvm::StringRef, long long) const
Line
Count
Source
839
6.68k
  auto Add = [](StringRef S, int64_t Pos) {
840
6.68k
    return addOptionalRegular<ELFT>(S, Out::ElfHeader, Pos, STV_DEFAULT);
841
6.68k
  };
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addReservedSymbols()::'lambda'(llvm::StringRef, long long)::operator()(llvm::StringRef, long long) const
Line
Count
Source
839
1.17k
  auto Add = [](StringRef S, int64_t Pos) {
840
1.17k
    return addOptionalRegular<ELFT>(S, Out::ElfHeader, Pos, STV_DEFAULT);
841
1.17k
  };
842
1.53k
843
1.53k
  ElfSym::Bss = Add("__bss_start", 0);
844
1.53k
  ElfSym::End1 = Add("end", -1);
845
1.53k
  ElfSym::End2 = Add("_end", -1);
846
1.53k
  ElfSym::Etext1 = Add("etext", -1);
847
1.53k
  ElfSym::Etext2 = Add("_etext", -1);
848
1.53k
  ElfSym::Edata1 = Add("edata", -1);
849
1.53k
  ElfSym::Edata2 = Add("_edata", -1);
850
1.53k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::addReservedSymbols()
Line
Count
Source
783
187
template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
784
187
  if (
Config->EMachine == EM_MIPS187
) {
785
14
    // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
786
14
    // so that it points to an absolute address which by default is relative
787
14
    // to GOT. Default offset is 0x7ff0.
788
14
    // See "Global Data Symbols" in Chapter 6 in the following document:
789
14
    // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
790
14
    ElfSym::MipsGp = Symtab->addAbsolute<ELFT>("_gp", STV_HIDDEN, STB_LOCAL);
791
14
792
14
    // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
793
14
    // start of function and 'gp' pointer into GOT.
794
14
    if (Symtab->find("_gp_disp"))
795
1
      ElfSym::MipsGpDisp =
796
1
          Symtab->addAbsolute<ELFT>("_gp_disp", STV_HIDDEN, STB_LOCAL);
797
14
798
14
    // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
799
14
    // pointer. This symbol is used in the code generated by .cpload pseudo-op
800
14
    // in case of using -mno-shared option.
801
14
    // https://sourceware.org/ml/binutils/2004-12/msg00094.html
802
14
    if (Symtab->find("__gnu_local_gp"))
803
0
      ElfSym::MipsLocalGp =
804
0
          Symtab->addAbsolute<ELFT>("__gnu_local_gp", STV_HIDDEN, STB_LOCAL);
805
14
  }
806
187
807
187
  // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
808
187
  // be at some offset from the base of the .got section, usually 0 or the end
809
187
  // of the .got
810
14
  InputSection *GotSection = InX::MipsGot ? cast<InputSection>(InX::MipsGot)
811
173
                                          : cast<InputSection>(InX::Got);
812
187
  ElfSym::GlobalOffsetTable = addOptionalRegular<ELFT>(
813
187
      "_GLOBAL_OFFSET_TABLE_", GotSection, Target->GotBaseSymOff);
814
187
815
187
  // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
816
187
  // static linking the linker is required to optimize away any references to
817
187
  // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
818
187
  // to avoid the undefined symbol error.
819
187
  if (!InX::DynSymTab)
820
79
    Symtab->addIgnored<ELFT>("__tls_get_addr");
821
187
822
187
  // __ehdr_start is the location of ELF file headers. Note that we define
823
187
  // this symbol unconditionally even when using a linker script, which
824
187
  // differs from the behavior implemented by GNU linker which only define
825
187
  // this symbol if ELF headers are in the memory mapped segment.
826
187
  // __executable_start is not documented, but the expectation of at
827
187
  // least the android libc is that it points to the elf header too.
828
187
  // __dso_handle symbol is passed to cxa_finalize as a marker to identify
829
187
  // each DSO. The address of the symbol doesn't matter as long as they are
830
187
  // different in different DSOs, so we chose the start address of the DSO.
831
187
  for (const char *Name :
832
187
       {"__ehdr_start", "__executable_start", "__dso_handle"})
833
561
    addOptionalRegular<ELFT>(Name, Out::ElfHeader, 0, STV_HIDDEN);
834
187
835
187
  // If linker script do layout we do not need to create any standart symbols.
836
187
  if (Script->Opt.HasSections)
837
19
    return;
838
168
839
168
  auto Add = [](StringRef S, int64_t Pos) {
840
168
    return addOptionalRegular<ELFT>(S, Out::ElfHeader, Pos, STV_DEFAULT);
841
168
  };
842
168
843
168
  ElfSym::Bss = Add("__bss_start", 0);
844
168
  ElfSym::End1 = Add("end", -1);
845
168
  ElfSym::End2 = Add("_end", -1);
846
168
  ElfSym::Etext1 = Add("etext", -1);
847
168
  ElfSym::Etext2 = Add("_etext", -1);
848
168
  ElfSym::Edata1 = Add("edata", -1);
849
168
  ElfSym::Edata2 = Add("_edata", -1);
850
168
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::addReservedSymbols()
Line
Count
Source
783
43
template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
784
43
  if (
Config->EMachine == EM_MIPS43
) {
785
27
    // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
786
27
    // so that it points to an absolute address which by default is relative
787
27
    // to GOT. Default offset is 0x7ff0.
788
27
    // See "Global Data Symbols" in Chapter 6 in the following document:
789
27
    // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
790
27
    ElfSym::MipsGp = Symtab->addAbsolute<ELFT>("_gp", STV_HIDDEN, STB_LOCAL);
791
27
792
27
    // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
793
27
    // start of function and 'gp' pointer into GOT.
794
27
    if (Symtab->find("_gp_disp"))
795
0
      ElfSym::MipsGpDisp =
796
0
          Symtab->addAbsolute<ELFT>("_gp_disp", STV_HIDDEN, STB_LOCAL);
797
27
798
27
    // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
799
27
    // pointer. This symbol is used in the code generated by .cpload pseudo-op
800
27
    // in case of using -mno-shared option.
801
27
    // https://sourceware.org/ml/binutils/2004-12/msg00094.html
802
27
    if (Symtab->find("__gnu_local_gp"))
803
0
      ElfSym::MipsLocalGp =
804
0
          Symtab->addAbsolute<ELFT>("__gnu_local_gp", STV_HIDDEN, STB_LOCAL);
805
27
  }
806
43
807
43
  // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
808
43
  // be at some offset from the base of the .got section, usually 0 or the end
809
43
  // of the .got
810
27
  InputSection *GotSection = InX::MipsGot ? cast<InputSection>(InX::MipsGot)
811
16
                                          : cast<InputSection>(InX::Got);
812
43
  ElfSym::GlobalOffsetTable = addOptionalRegular<ELFT>(
813
43
      "_GLOBAL_OFFSET_TABLE_", GotSection, Target->GotBaseSymOff);
814
43
815
43
  // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
816
43
  // static linking the linker is required to optimize away any references to
817
43
  // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
818
43
  // to avoid the undefined symbol error.
819
43
  if (!InX::DynSymTab)
820
18
    Symtab->addIgnored<ELFT>("__tls_get_addr");
821
43
822
43
  // __ehdr_start is the location of ELF file headers. Note that we define
823
43
  // this symbol unconditionally even when using a linker script, which
824
43
  // differs from the behavior implemented by GNU linker which only define
825
43
  // this symbol if ELF headers are in the memory mapped segment.
826
43
  // __executable_start is not documented, but the expectation of at
827
43
  // least the android libc is that it points to the elf header too.
828
43
  // __dso_handle symbol is passed to cxa_finalize as a marker to identify
829
43
  // each DSO. The address of the symbol doesn't matter as long as they are
830
43
  // different in different DSOs, so we chose the start address of the DSO.
831
43
  for (const char *Name :
832
43
       {"__ehdr_start", "__executable_start", "__dso_handle"})
833
129
    addOptionalRegular<ELFT>(Name, Out::ElfHeader, 0, STV_HIDDEN);
834
43
835
43
  // If linker script do layout we do not need to create any standart symbols.
836
43
  if (Script->Opt.HasSections)
837
2
    return;
838
41
839
41
  auto Add = [](StringRef S, int64_t Pos) {
840
41
    return addOptionalRegular<ELFT>(S, Out::ElfHeader, Pos, STV_DEFAULT);
841
41
  };
842
41
843
41
  ElfSym::Bss = Add("__bss_start", 0);
844
41
  ElfSym::End1 = Add("end", -1);
845
41
  ElfSym::End2 = Add("_end", -1);
846
41
  ElfSym::Etext1 = Add("etext", -1);
847
41
  ElfSym::Etext2 = Add("_etext", -1);
848
41
  ElfSym::Edata1 = Add("edata", -1);
849
41
  ElfSym::Edata2 = Add("_edata", -1);
850
41
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::addReservedSymbols()
Line
Count
Source
783
87
template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
784
87
  if (
Config->EMachine == EM_MIPS87
) {
785
85
    // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
786
85
    // so that it points to an absolute address which by default is relative
787
85
    // to GOT. Default offset is 0x7ff0.
788
85
    // See "Global Data Symbols" in Chapter 6 in the following document:
789
85
    // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
790
85
    ElfSym::MipsGp = Symtab->addAbsolute<ELFT>("_gp", STV_HIDDEN, STB_LOCAL);
791
85
792
85
    // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
793
85
    // start of function and 'gp' pointer into GOT.
794
85
    if (Symtab->find("_gp_disp"))
795
7
      ElfSym::MipsGpDisp =
796
7
          Symtab->addAbsolute<ELFT>("_gp_disp", STV_HIDDEN, STB_LOCAL);
797
85
798
85
    // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
799
85
    // pointer. This symbol is used in the code generated by .cpload pseudo-op
800
85
    // in case of using -mno-shared option.
801
85
    // https://sourceware.org/ml/binutils/2004-12/msg00094.html
802
85
    if (Symtab->find("__gnu_local_gp"))
803
1
      ElfSym::MipsLocalGp =
804
1
          Symtab->addAbsolute<ELFT>("__gnu_local_gp", STV_HIDDEN, STB_LOCAL);
805
85
  }
806
87
807
87
  // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
808
87
  // be at some offset from the base of the .got section, usually 0 or the end
809
87
  // of the .got
810
85
  InputSection *GotSection = InX::MipsGot ? cast<InputSection>(InX::MipsGot)
811
2
                                          : cast<InputSection>(InX::Got);
812
87
  ElfSym::GlobalOffsetTable = addOptionalRegular<ELFT>(
813
87
      "_GLOBAL_OFFSET_TABLE_", GotSection, Target->GotBaseSymOff);
814
87
815
87
  // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
816
87
  // static linking the linker is required to optimize away any references to
817
87
  // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
818
87
  // to avoid the undefined symbol error.
819
87
  if (!InX::DynSymTab)
820
33
    Symtab->addIgnored<ELFT>("__tls_get_addr");
821
87
822
87
  // __ehdr_start is the location of ELF file headers. Note that we define
823
87
  // this symbol unconditionally even when using a linker script, which
824
87
  // differs from the behavior implemented by GNU linker which only define
825
87
  // this symbol if ELF headers are in the memory mapped segment.
826
87
  // __executable_start is not documented, but the expectation of at
827
87
  // least the android libc is that it points to the elf header too.
828
87
  // __dso_handle symbol is passed to cxa_finalize as a marker to identify
829
87
  // each DSO. The address of the symbol doesn't matter as long as they are
830
87
  // different in different DSOs, so we chose the start address of the DSO.
831
87
  for (const char *Name :
832
87
       {"__ehdr_start", "__executable_start", "__dso_handle"})
833
261
    addOptionalRegular<ELFT>(Name, Out::ElfHeader, 0, STV_HIDDEN);
834
87
835
87
  // If linker script do layout we do not need to create any standart symbols.
836
87
  if (Script->Opt.HasSections)
837
7
    return;
838
80
839
80
  auto Add = [](StringRef S, int64_t Pos) {
840
80
    return addOptionalRegular<ELFT>(S, Out::ElfHeader, Pos, STV_DEFAULT);
841
80
  };
842
80
843
80
  ElfSym::Bss = Add("__bss_start", 0);
844
80
  ElfSym::End1 = Add("end", -1);
845
80
  ElfSym::End2 = Add("_end", -1);
846
80
  ElfSym::Etext1 = Add("etext", -1);
847
80
  ElfSym::Etext2 = Add("_etext", -1);
848
80
  ElfSym::Edata1 = Add("edata", -1);
849
80
  ElfSym::Edata2 = Add("_edata", -1);
850
80
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addReservedSymbols()
Line
Count
Source
783
1.22k
template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
784
1.22k
  if (
Config->EMachine == EM_MIPS1.22k
) {
785
2
    // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
786
2
    // so that it points to an absolute address which by default is relative
787
2
    // to GOT. Default offset is 0x7ff0.
788
2
    // See "Global Data Symbols" in Chapter 6 in the following document:
789
2
    // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
790
2
    ElfSym::MipsGp = Symtab->addAbsolute<ELFT>("_gp", STV_HIDDEN, STB_LOCAL);
791
2
792
2
    // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
793
2
    // start of function and 'gp' pointer into GOT.
794
2
    if (Symtab->find("_gp_disp"))
795
0
      ElfSym::MipsGpDisp =
796
0
          Symtab->addAbsolute<ELFT>("_gp_disp", STV_HIDDEN, STB_LOCAL);
797
2
798
2
    // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
799
2
    // pointer. This symbol is used in the code generated by .cpload pseudo-op
800
2
    // in case of using -mno-shared option.
801
2
    // https://sourceware.org/ml/binutils/2004-12/msg00094.html
802
2
    if (Symtab->find("__gnu_local_gp"))
803
0
      ElfSym::MipsLocalGp =
804
0
          Symtab->addAbsolute<ELFT>("__gnu_local_gp", STV_HIDDEN, STB_LOCAL);
805
2
  }
806
1.22k
807
1.22k
  // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
808
1.22k
  // be at some offset from the base of the .got section, usually 0 or the end
809
1.22k
  // of the .got
810
2
  InputSection *GotSection = InX::MipsGot ? cast<InputSection>(InX::MipsGot)
811
1.21k
                                          : cast<InputSection>(InX::Got);
812
1.22k
  ElfSym::GlobalOffsetTable = addOptionalRegular<ELFT>(
813
1.22k
      "_GLOBAL_OFFSET_TABLE_", GotSection, Target->GotBaseSymOff);
814
1.22k
815
1.22k
  // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
816
1.22k
  // static linking the linker is required to optimize away any references to
817
1.22k
  // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
818
1.22k
  // to avoid the undefined symbol error.
819
1.22k
  if (!InX::DynSymTab)
820
605
    Symtab->addIgnored<ELFT>("__tls_get_addr");
821
1.22k
822
1.22k
  // __ehdr_start is the location of ELF file headers. Note that we define
823
1.22k
  // this symbol unconditionally even when using a linker script, which
824
1.22k
  // differs from the behavior implemented by GNU linker which only define
825
1.22k
  // this symbol if ELF headers are in the memory mapped segment.
826
1.22k
  // __executable_start is not documented, but the expectation of at
827
1.22k
  // least the android libc is that it points to the elf header too.
828
1.22k
  // __dso_handle symbol is passed to cxa_finalize as a marker to identify
829
1.22k
  // each DSO. The address of the symbol doesn't matter as long as they are
830
1.22k
  // different in different DSOs, so we chose the start address of the DSO.
831
1.22k
  for (const char *Name :
832
1.22k
       {"__ehdr_start", "__executable_start", "__dso_handle"})
833
3.66k
    addOptionalRegular<ELFT>(Name, Out::ElfHeader, 0, STV_HIDDEN);
834
1.22k
835
1.22k
  // If linker script do layout we do not need to create any standart symbols.
836
1.22k
  if (Script->Opt.HasSections)
837
266
    return;
838
955
839
955
  auto Add = [](StringRef S, int64_t Pos) {
840
955
    return addOptionalRegular<ELFT>(S, Out::ElfHeader, Pos, STV_DEFAULT);
841
955
  };
842
955
843
955
  ElfSym::Bss = Add("__bss_start", 0);
844
955
  ElfSym::End1 = Add("end", -1);
845
955
  ElfSym::End2 = Add("_end", -1);
846
955
  ElfSym::Etext1 = Add("etext", -1);
847
955
  ElfSym::Etext2 = Add("_etext", -1);
848
955
  ElfSym::Edata1 = Add("edata", -1);
849
955
  ElfSym::Edata2 = Add("_edata", -1);
850
955
}
851
852
// Sort input sections by section name suffixes for
853
// __attribute__((init_priority(N))).
854
2.60k
static void sortInitFini(OutputSection *Cmd) {
855
2.60k
  if (Cmd)
856
9
    Cmd->sortInitFini();
857
2.60k
}
858
859
// Sort input sections by the special rule for .ctors and .dtors.
860
2.60k
static void sortCtorsDtors(OutputSection *Cmd) {
861
2.60k
  if (Cmd)
862
8
    Cmd->sortCtorsDtors();
863
2.60k
}
864
865
// Sort input sections using the list provided by --symbol-ordering-file.
866
1.30k
static void sortBySymbolsOrder() {
867
1.30k
  if (Config->SymbolOrderingFile.empty())
868
1.29k
    return;
869
5
870
5
  // Sort sections by priority.
871
5
  DenseMap<SectionBase *, int> SectionOrder = buildSectionOrder();
872
5
  for (BaseCommand *Base : Script->Opt.Commands)
873
81
    
if (auto *81
Sec81
= dyn_cast<OutputSection>(Base))
874
103
      
Sec->sort([&](InputSectionBase *S) 76
{ return SectionOrder.lookup(S); }103
);
875
1.30k
}
876
877
template <class ELFT>
878
1.53k
void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
879
1.53k
  // Scan all relocations. Each relocation goes through a series
880
1.53k
  // of tests to determine if it needs special treatment, such as
881
1.53k
  // creating GOT, PLT, copy relocations, etc.
882
1.53k
  // Note that relocations for non-alloc sections are directly
883
1.53k
  // processed by InputSection::relocateNonAlloc.
884
1.53k
  for (InputSectionBase *IS : InputSections)
885
227k
    
if (227k
IS->Live && 227k
isa<InputSection>(IS)227k
&&
(IS->Flags & SHF_ALLOC)227k
)
886
90.3k
      Fn(*IS);
887
1.53k
  for (EhInputSection *ES : In<ELFT>::EhFrame->Sections)
888
95
    Fn(*ES);
889
1.53k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::forEachRelSec(std::__1::function<void (lld::elf::InputSectionBase&)>)
Line
Count
Source
878
87
void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
879
87
  // Scan all relocations. Each relocation goes through a series
880
87
  // of tests to determine if it needs special treatment, such as
881
87
  // creating GOT, PLT, copy relocations, etc.
882
87
  // Note that relocations for non-alloc sections are directly
883
87
  // processed by InputSection::relocateNonAlloc.
884
87
  for (InputSectionBase *IS : InputSections)
885
2.37k
    
if (2.37k
IS->Live && 2.37k
isa<InputSection>(IS)2.14k
&&
(IS->Flags & SHF_ALLOC)2.14k
)
886
1.79k
      Fn(*IS);
887
87
  for (EhInputSection *ES : In<ELFT>::EhFrame->Sections)
888
1
    Fn(*ES);
889
87
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::forEachRelSec(std::__1::function<void (lld::elf::InputSectionBase&)>)
Line
Count
Source
878
43
void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
879
43
  // Scan all relocations. Each relocation goes through a series
880
43
  // of tests to determine if it needs special treatment, such as
881
43
  // creating GOT, PLT, copy relocations, etc.
882
43
  // Note that relocations for non-alloc sections are directly
883
43
  // processed by InputSection::relocateNonAlloc.
884
43
  for (InputSectionBase *IS : InputSections)
885
1.06k
    
if (1.06k
IS->Live && 1.06k
isa<InputSection>(IS)1.00k
&&
(IS->Flags & SHF_ALLOC)1.00k
)
886
828
      Fn(*IS);
887
43
  for (EhInputSection *ES : In<ELFT>::EhFrame->Sections)
888
3
    Fn(*ES);
889
43
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::forEachRelSec(std::__1::function<void (lld::elf::InputSectionBase&)>)
Line
Count
Source
878
1.22k
void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
879
1.22k
  // Scan all relocations. Each relocation goes through a series
880
1.22k
  // of tests to determine if it needs special treatment, such as
881
1.22k
  // creating GOT, PLT, copy relocations, etc.
882
1.22k
  // Note that relocations for non-alloc sections are directly
883
1.22k
  // processed by InputSection::relocateNonAlloc.
884
1.22k
  for (InputSectionBase *IS : InputSections)
885
220k
    
if (220k
IS->Live && 220k
isa<InputSection>(IS)220k
&&
(IS->Flags & SHF_ALLOC)220k
)
886
84.5k
      Fn(*IS);
887
1.22k
  for (EhInputSection *ES : In<ELFT>::EhFrame->Sections)
888
87
    Fn(*ES);
889
1.22k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::forEachRelSec(std::__1::function<void (lld::elf::InputSectionBase&)>)
Line
Count
Source
878
187
void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
879
187
  // Scan all relocations. Each relocation goes through a series
880
187
  // of tests to determine if it needs special treatment, such as
881
187
  // creating GOT, PLT, copy relocations, etc.
882
187
  // Note that relocations for non-alloc sections are directly
883
187
  // processed by InputSection::relocateNonAlloc.
884
187
  for (InputSectionBase *IS : InputSections)
885
3.90k
    
if (3.90k
IS->Live && 3.90k
isa<InputSection>(IS)3.86k
&&
(IS->Flags & SHF_ALLOC)3.86k
)
886
3.10k
      Fn(*IS);
887
187
  for (EhInputSection *ES : In<ELFT>::EhFrame->Sections)
888
4
    Fn(*ES);
889
187
}
890
891
1.30k
template <class ELFT> void Writer<ELFT>::createSections() {
892
1.30k
  std::vector<BaseCommand *> Old = Script->Opt.Commands;
893
1.30k
  Script->Opt.Commands.clear();
894
1.30k
  for (InputSectionBase *IS : InputSections)
895
92.3k
    
if (92.3k
IS92.3k
)
896
92.3k
      Factory.addInputSec(IS, getOutputSectionName(IS->Name));
897
1.30k
  Script->Opt.Commands.insert(Script->Opt.Commands.end(), Old.begin(),
898
1.30k
                              Old.end());
899
1.30k
900
1.30k
  Script->fabricateDefaultCommands();
901
1.30k
  sortBySymbolsOrder();
902
1.30k
  sortInitFini(findSection(".init_array"));
903
1.30k
  sortInitFini(findSection(".fini_array"));
904
1.30k
  sortCtorsDtors(findSection(".ctors"));
905
1.30k
  sortCtorsDtors(findSection(".dtors"));
906
1.30k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::createSections()
Line
Count
Source
891
42
template <class ELFT> void Writer<ELFT>::createSections() {
892
42
  std::vector<BaseCommand *> Old = Script->Opt.Commands;
893
42
  Script->Opt.Commands.clear();
894
42
  for (InputSectionBase *IS : InputSections)
895
1.02k
    
if (1.02k
IS1.02k
)
896
1.02k
      Factory.addInputSec(IS, getOutputSectionName(IS->Name));
897
42
  Script->Opt.Commands.insert(Script->Opt.Commands.end(), Old.begin(),
898
42
                              Old.end());
899
42
900
42
  Script->fabricateDefaultCommands();
901
42
  sortBySymbolsOrder();
902
42
  sortInitFini(findSection(".init_array"));
903
42
  sortInitFini(findSection(".fini_array"));
904
42
  sortCtorsDtors(findSection(".ctors"));
905
42
  sortCtorsDtors(findSection(".dtors"));
906
42
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::createSections()
Line
Count
Source
891
174
template <class ELFT> void Writer<ELFT>::createSections() {
892
174
  std::vector<BaseCommand *> Old = Script->Opt.Commands;
893
174
  Script->Opt.Commands.clear();
894
174
  for (InputSectionBase *IS : InputSections)
895
3.60k
    
if (3.60k
IS3.60k
)
896
3.60k
      Factory.addInputSec(IS, getOutputSectionName(IS->Name));
897
174
  Script->Opt.Commands.insert(Script->Opt.Commands.end(), Old.begin(),
898
174
                              Old.end());
899
174
900
174
  Script->fabricateDefaultCommands();
901
174
  sortBySymbolsOrder();
902
174
  sortInitFini(findSection(".init_array"));
903
174
  sortInitFini(findSection(".fini_array"));
904
174
  sortCtorsDtors(findSection(".ctors"));
905
174
  sortCtorsDtors(findSection(".dtors"));
906
174
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::createSections()
Line
Count
Source
891
999
template <class ELFT> void Writer<ELFT>::createSections() {
892
999
  std::vector<BaseCommand *> Old = Script->Opt.Commands;
893
999
  Script->Opt.Commands.clear();
894
999
  for (InputSectionBase *IS : InputSections)
895
85.3k
    
if (85.3k
IS85.3k
)
896
85.3k
      Factory.addInputSec(IS, getOutputSectionName(IS->Name));
897
999
  Script->Opt.Commands.insert(Script->Opt.Commands.end(), Old.begin(),
898
999
                              Old.end());
899
999
900
999
  Script->fabricateDefaultCommands();
901
999
  sortBySymbolsOrder();
902
999
  sortInitFini(findSection(".init_array"));
903
999
  sortInitFini(findSection(".fini_array"));
904
999
  sortCtorsDtors(findSection(".ctors"));
905
999
  sortCtorsDtors(findSection(".dtors"));
906
999
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::createSections()
Line
Count
Source
891
88
template <class ELFT> void Writer<ELFT>::createSections() {
892
88
  std::vector<BaseCommand *> Old = Script->Opt.Commands;
893
88
  Script->Opt.Commands.clear();
894
88
  for (InputSectionBase *IS : InputSections)
895
2.35k
    
if (2.35k
IS2.35k
)
896
2.35k
      Factory.addInputSec(IS, getOutputSectionName(IS->Name));
897
88
  Script->Opt.Commands.insert(Script->Opt.Commands.end(), Old.begin(),
898
88
                              Old.end());
899
88
900
88
  Script->fabricateDefaultCommands();
901
88
  sortBySymbolsOrder();
902
88
  sortInitFini(findSection(".init_array"));
903
88
  sortInitFini(findSection(".fini_array"));
904
88
  sortCtorsDtors(findSection(".ctors"));
905
88
  sortCtorsDtors(findSection(".dtors"));
906
88
}
907
908
// This function generates assignments for predefined symbols (e.g. _end or
909
// _etext) and inserts them into the commands sequence to be processed at the
910
// appropriate time. This ensures that the value is going to be correct by the
911
// time any references to these symbols are processed and is equivalent to
912
// defining these symbols explicitly in the linker script.
913
1.53k
template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
914
1.53k
  PhdrEntry *Last = nullptr;
915
1.53k
  PhdrEntry *LastRO = nullptr;
916
1.53k
  PhdrEntry *LastRW = nullptr;
917
1.53k
918
8.13k
  for (PhdrEntry *P : Phdrs) {
919
8.13k
    if (P->p_type != PT_LOAD)
920
4.51k
      continue;
921
3.62k
    Last = P;
922
3.62k
    if (P->p_flags & PF_W)
923
992
      LastRW = P;
924
3.62k
    else
925
2.63k
      LastRO = P;
926
8.13k
  }
927
1.53k
928
1.53k
  // _end is the first location after the uninitialized data region.
929
1.53k
  if (
Last1.53k
) {
930
1.46k
    if (ElfSym::End1)
931
3
      ElfSym::End1->Section = Last->LastSec;
932
1.46k
    if (ElfSym::End2)
933
8
      ElfSym::End2->Section = Last->LastSec;
934
1.46k
  }
935
1.53k
936
1.53k
  // _etext is the first location after the last read-only loadable segment.
937
1.53k
  if (
LastRO1.53k
) {
938
1.45k
    if (ElfSym::Etext1)
939
0
      ElfSym::Etext1->Section = LastRO->LastSec;
940
1.45k
    if (ElfSym::Etext2)
941
1
      ElfSym::Etext2->Section = LastRO->LastSec;
942
1.45k
  }
943
1.53k
944
1.53k
  // _edata points to the end of the last non SHT_NOBITS section.
945
1.53k
  if (
LastRW1.53k
) {
946
978
    size_t I = 0;
947
70.6k
    for (; 
I < OutputSections.size()70.6k
;
++I69.6k
)
948
70.6k
      
if (70.6k
OutputSections[I] == LastRW->FirstSec70.6k
)
949
968
        break;
950
978
951
5.36k
    for (; 
I < OutputSections.size()5.36k
;
++I4.38k
) {
952
4.62k
      if (OutputSections[I]->Type != SHT_NOBITS)
953
4.38k
        continue;
954
242
      break;
955
242
    }
956
978
    if (ElfSym::Edata1)
957
0
      ElfSym::Edata1->Section = OutputSections[I - 1];
958
978
    if (ElfSym::Edata2)
959
3
      ElfSym::Edata2->Section = OutputSections[I - 1];
960
978
  }
961
1.53k
962
1.53k
  if (ElfSym::Bss)
963
3
    ElfSym::Bss->Section = findSection(".bss");
964
1.53k
965
1.53k
  // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
966
1.53k
  // be equal to the _gp symbol's value.
967
1.53k
  if (
ElfSym::MipsGp1.53k
) {
968
127
    // Find GP-relative section with the lowest address
969
127
    // and use this address to calculate default _gp value.
970
1.01k
    for (OutputSection *OS : OutputSections) {
971
1.01k
      if (
OS->Flags & SHF_MIPS_GPREL1.01k
) {
972
127
        ElfSym::MipsGp->Section = OS;
973
127
        ElfSym::MipsGp->Value = 0x7ff0;
974
127
        break;
975
127
      }
976
1.53k
    }
977
127
  }
978
1.53k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::setReservedSymbolSections()
Line
Count
Source
913
93
template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
914
93
  PhdrEntry *Last = nullptr;
915
93
  PhdrEntry *LastRO = nullptr;
916
93
  PhdrEntry *LastRW = nullptr;
917
93
918
489
  for (PhdrEntry *P : Phdrs) {
919
489
    if (P->p_type != PT_LOAD)
920
240
      continue;
921
249
    Last = P;
922
249
    if (P->p_flags & PF_W)
923
85
      LastRW = P;
924
249
    else
925
164
      LastRO = P;
926
489
  }
927
93
928
93
  // _end is the first location after the uninitialized data region.
929
93
  if (
Last93
) {
930
86
    if (ElfSym::End1)
931
0
      ElfSym::End1->Section = Last->LastSec;
932
86
    if (ElfSym::End2)
933
0
      ElfSym::End2->Section = Last->LastSec;
934
86
  }
935
93
936
93
  // _etext is the first location after the last read-only loadable segment.
937
93
  if (
LastRO93
) {
938
86
    if (ElfSym::Etext1)
939
0
      ElfSym::Etext1->Section = LastRO->LastSec;
940
86
    if (ElfSym::Etext2)
941
0
      ElfSym::Etext2->Section = LastRO->LastSec;
942
86
  }
943
93
944
93
  // _edata points to the end of the last non SHT_NOBITS section.
945
93
  if (
LastRW93
) {
946
85
    size_t I = 0;
947
578
    for (; 
I < OutputSections.size()578
;
++I493
)
948
578
      
if (578
OutputSections[I] == LastRW->FirstSec578
)
949
85
        break;
950
85
951
296
    for (; 
I < OutputSections.size()296
;
++I211
) {
952
292
      if (OutputSections[I]->Type != SHT_NOBITS)
953
211
        continue;
954
81
      break;
955
81
    }
956
85
    if (ElfSym::Edata1)
957
0
      ElfSym::Edata1->Section = OutputSections[I - 1];
958
85
    if (ElfSym::Edata2)
959
0
      ElfSym::Edata2->Section = OutputSections[I - 1];
960
85
  }
961
93
962
93
  if (ElfSym::Bss)
963
0
    ElfSym::Bss->Section = findSection(".bss");
964
93
965
93
  // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
966
93
  // be equal to the _gp symbol's value.
967
93
  if (
ElfSym::MipsGp93
) {
968
84
    // Find GP-relative section with the lowest address
969
84
    // and use this address to calculate default _gp value.
970
675
    for (OutputSection *OS : OutputSections) {
971
675
      if (
OS->Flags & SHF_MIPS_GPREL675
) {
972
84
        ElfSym::MipsGp->Section = OS;
973
84
        ElfSym::MipsGp->Value = 0x7ff0;
974
84
        break;
975
84
      }
976
93
    }
977
84
  }
978
93
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::setReservedSymbolSections()
Line
Count
Source
913
189
template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
914
189
  PhdrEntry *Last = nullptr;
915
189
  PhdrEntry *LastRO = nullptr;
916
189
  PhdrEntry *LastRW = nullptr;
917
189
918
1.08k
  for (PhdrEntry *P : Phdrs) {
919
1.08k
    if (P->p_type != PT_LOAD)
920
610
      continue;
921
471
    Last = P;
922
471
    if (P->p_flags & PF_W)
923
132
      LastRW = P;
924
471
    else
925
339
      LastRO = P;
926
1.08k
  }
927
189
928
189
  // _end is the first location after the uninitialized data region.
929
189
  if (
Last189
) {
930
182
    if (ElfSym::End1)
931
0
      ElfSym::End1->Section = Last->LastSec;
932
182
    if (ElfSym::End2)
933
0
      ElfSym::End2->Section = Last->LastSec;
934
182
  }
935
189
936
189
  // _etext is the first location after the last read-only loadable segment.
937
189
  if (
LastRO189
) {
938
180
    if (ElfSym::Etext1)
939
0
      ElfSym::Etext1->Section = LastRO->LastSec;
940
180
    if (ElfSym::Etext2)
941
0
      ElfSym::Etext2->Section = LastRO->LastSec;
942
180
  }
943
189
944
189
  // _edata points to the end of the last non SHT_NOBITS section.
945
189
  if (
LastRW189
) {
946
129
    size_t I = 0;
947
760
    for (; 
I < OutputSections.size()760
;
++I631
)
948
759
      
if (759
OutputSections[I] == LastRW->FirstSec759
)
949
128
        break;
950
129
951
711
    for (; 
I < OutputSections.size()711
;
++I582
) {
952
617
      if (OutputSections[I]->Type != SHT_NOBITS)
953
582
        continue;
954
35
      break;
955
35
    }
956
129
    if (ElfSym::Edata1)
957
0
      ElfSym::Edata1->Section = OutputSections[I - 1];
958
129
    if (ElfSym::Edata2)
959
0
      ElfSym::Edata2->Section = OutputSections[I - 1];
960
129
  }
961
189
962
189
  if (ElfSym::Bss)
963
0
    ElfSym::Bss->Section = findSection(".bss");
964
189
965
189
  // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
966
189
  // be equal to the _gp symbol's value.
967
189
  if (
ElfSym::MipsGp189
) {
968
14
    // Find GP-relative section with the lowest address
969
14
    // and use this address to calculate default _gp value.
970
108
    for (OutputSection *OS : OutputSections) {
971
108
      if (
OS->Flags & SHF_MIPS_GPREL108
) {
972
14
        ElfSym::MipsGp->Section = OS;
973
14
        ElfSym::MipsGp->Value = 0x7ff0;
974
14
        break;
975
14
      }
976
189
    }
977
14
  }
978
189
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::setReservedSymbolSections()
Line
Count
Source
913
1.20k
template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
914
1.20k
  PhdrEntry *Last = nullptr;
915
1.20k
  PhdrEntry *LastRO = nullptr;
916
1.20k
  PhdrEntry *LastRW = nullptr;
917
1.20k
918
6.30k
  for (PhdrEntry *P : Phdrs) {
919
6.30k
    if (P->p_type != PT_LOAD)
920
3.52k
      continue;
921
2.78k
    Last = P;
922
2.78k
    if (P->p_flags & PF_W)
923
735
      LastRW = P;
924
2.78k
    else
925
2.04k
      LastRO = P;
926
6.30k
  }
927
1.20k
928
1.20k
  // _end is the first location after the uninitialized data region.
929
1.20k
  if (
Last1.20k
) {
930
1.15k
    if (ElfSym::End1)
931
3
      ElfSym::End1->Section = Last->LastSec;
932
1.15k
    if (ElfSym::End2)
933
8
      ElfSym::End2->Section = Last->LastSec;
934
1.15k
  }
935
1.20k
936
1.20k
  // _etext is the first location after the last read-only loadable segment.
937
1.20k
  if (
LastRO1.20k
) {
938
1.14k
    if (ElfSym::Etext1)
939
0
      ElfSym::Etext1->Section = LastRO->LastSec;
940
1.14k
    if (ElfSym::Etext2)
941
1
      ElfSym::Etext2->Section = LastRO->LastSec;
942
1.14k
  }
943
1.20k
944
1.20k
  // _edata points to the end of the last non SHT_NOBITS section.
945
1.20k
  if (
LastRW1.20k
) {
946
724
    size_t I = 0;
947
69.0k
    for (; 
I < OutputSections.size()69.0k
;
++I68.3k
)
948
69.0k
      
if (69.0k
OutputSections[I] == LastRW->FirstSec69.0k
)
949
715
        break;
950
724
951
4.17k
    for (; 
I < OutputSections.size()4.17k
;
++I3.44k
) {
952
3.54k
      if (OutputSections[I]->Type != SHT_NOBITS)
953
3.44k
        continue;
954
99
      break;
955
99
    }
956
724
    if (ElfSym::Edata1)
957
0
      ElfSym::Edata1->Section = OutputSections[I - 1];
958
724
    if (ElfSym::Edata2)
959
3
      ElfSym::Edata2->Section = OutputSections[I - 1];
960
724
  }
961
1.20k
962
1.20k
  if (ElfSym::Bss)
963
3
    ElfSym::Bss->Section = findSection(".bss");
964
1.20k
965
1.20k
  // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
966
1.20k
  // be equal to the _gp symbol's value.
967
1.20k
  if (
ElfSym::MipsGp1.20k
) {
968
2
    // Find GP-relative section with the lowest address
969
2
    // and use this address to calculate default _gp value.
970
10
    for (OutputSection *OS : OutputSections) {
971
10
      if (
OS->Flags & SHF_MIPS_GPREL10
) {
972
2
        ElfSym::MipsGp->Section = OS;
973
2
        ElfSym::MipsGp->Value = 0x7ff0;
974
2
        break;
975
2
      }
976
1.20k
    }
977
2
  }
978
1.20k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::setReservedSymbolSections()
Line
Count
Source
913
44
template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
914
44
  PhdrEntry *Last = nullptr;
915
44
  PhdrEntry *LastRO = nullptr;
916
44
  PhdrEntry *LastRW = nullptr;
917
44
918
260
  for (PhdrEntry *P : Phdrs) {
919
260
    if (P->p_type != PT_LOAD)
920
136
      continue;
921
124
    Last = P;
922
124
    if (P->p_flags & PF_W)
923
40
      LastRW = P;
924
124
    else
925
84
      LastRO = P;
926
260
  }
927
44
928
44
  // _end is the first location after the uninitialized data region.
929
44
  if (
Last44
) {
930
43
    if (ElfSym::End1)
931
0
      ElfSym::End1->Section = Last->LastSec;
932
43
    if (ElfSym::End2)
933
0
      ElfSym::End2->Section = Last->LastSec;
934
43
  }
935
44
936
44
  // _etext is the first location after the last read-only loadable segment.
937
44
  if (
LastRO44
) {
938
43
    if (ElfSym::Etext1)
939
0
      ElfSym::Etext1->Section = LastRO->LastSec;
940
43
    if (ElfSym::Etext2)
941
0
      ElfSym::Etext2->Section = LastRO->LastSec;
942
43
  }
943
44
944
44
  // _edata points to the end of the last non SHT_NOBITS section.
945
44
  if (
LastRW44
) {
946
40
    size_t I = 0;
947
264
    for (; 
I < OutputSections.size()264
;
++I224
)
948
264
      
if (264
OutputSections[I] == LastRW->FirstSec264
)
949
40
        break;
950
40
951
185
    for (; 
I < OutputSections.size()185
;
++I145
) {
952
172
      if (OutputSections[I]->Type != SHT_NOBITS)
953
145
        continue;
954
27
      break;
955
27
    }
956
40
    if (ElfSym::Edata1)
957
0
      ElfSym::Edata1->Section = OutputSections[I - 1];
958
40
    if (ElfSym::Edata2)
959
0
      ElfSym::Edata2->Section = OutputSections[I - 1];
960
40
  }
961
44
962
44
  if (ElfSym::Bss)
963
0
    ElfSym::Bss->Section = findSection(".bss");
964
44
965
44
  // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
966
44
  // be equal to the _gp symbol's value.
967
44
  if (
ElfSym::MipsGp44
) {
968
27
    // Find GP-relative section with the lowest address
969
27
    // and use this address to calculate default _gp value.
970
219
    for (OutputSection *OS : OutputSections) {
971
219
      if (
OS->Flags & SHF_MIPS_GPREL219
) {
972
27
        ElfSym::MipsGp->Section = OS;
973
27
        ElfSym::MipsGp->Value = 0x7ff0;
974
27
        break;
975
27
      }
976
44
    }
977
27
  }
978
44
}
979
980
// We want to find how similar two ranks are.
981
// The more branches in getSectionRank that match, the more similar they are.
982
// Since each branch corresponds to a bit flag, we can just use
983
// countLeadingZeros.
984
396k
static int getRankProximityAux(OutputSection *A, OutputSection *B) {
985
396k
  return countLeadingZeros(A->SortRank ^ B->SortRank);
986
396k
}
987
988
396k
static int getRankProximity(OutputSection *A, BaseCommand *B) {
989
396k
  if (auto *Sec = dyn_cast<OutputSection>(B))
990
396k
    
if (396k
Sec->Live396k
)
991
396k
      return getRankProximityAux(A, Sec);
992
229
  return -1;
993
229
}
994
995
// When placing orphan sections, we want to place them after symbol assignments
996
// so that an orphan after
997
//   begin_foo = .;
998
//   foo : { *(foo) }
999
//   end_foo = .;
1000
// doesn't break the intended meaning of the begin/end symbols.
1001
// We don't want to go over sections since findOrphanPos is the
1002
// one in charge of deciding the order of the sections.
1003
// We don't want to go over changes to '.', since doing so in
1004
//  rx_sec : { *(rx_sec) }
1005
//  . = ALIGN(0x1000);
1006
//  /* The RW PT_LOAD starts here*/
1007
//  rw_sec : { *(rw_sec) }
1008
// would mean that the RW PT_LOAD would become unaligned.
1009
414
static bool shouldSkip(BaseCommand *Cmd) {
1010
414
  if (isa<OutputSection>(Cmd))
1011
245
    return false;
1012
169
  
if (auto *169
Assign169
= dyn_cast<SymbolAssignment>(Cmd))
1013
167
    return Assign->Name != ".";
1014
2
  return true;
1015
2
}
1016
1017
// We want to place orphan sections so that they share as much
1018
// characteristics with their neighbors as possible. For example, if
1019
// both are rw, or both are tls.
1020
template <typename ELFT>
1021
static std::vector<BaseCommand *>::iterator
1022
findOrphanPos(std::vector<BaseCommand *>::iterator B,
1023
616
              std::vector<BaseCommand *>::iterator E) {
1024
616
  OutputSection *Sec = cast<OutputSection>(*E);
1025
616
1026
616
  // Find the first element that has as close a rank as possible.
1027
132k
  auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
1028
132k
    return getRankProximity(Sec, A) < getRankProximity(Sec, B);
1029
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
1027
38
  auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
1028
38
    return getRankProximity(Sec, A) < getRankProximity(Sec, B);
1029
38
  });
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
1027
161
  auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
1028
161
    return getRankProximity(Sec, A) < getRankProximity(Sec, B);
1029
161
  });
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
1027
131k
  auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
1028
131k
    return getRankProximity(Sec, A) < getRankProximity(Sec, B);
1029
131k
  });
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
1027
160
  auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
1028
160
    return getRankProximity(Sec, A) < getRankProximity(Sec, B);
1029
160
  });
1030
616
  if (I == E)
1031
40
    return E;
1032
576
1033
576
  // Consider all existing sections with the same proximity.
1034
576
  int Proximity = getRankProximity(Sec, *I);
1035
132k
  for (; 
I != E132k
;
++I132k
) {
1036
132k
    auto *CurSec = dyn_cast<OutputSection>(*I);
1037
132k
    if (
!CurSec || 132k
!CurSec->Live132k
)
1038
159
      continue;
1039
132k
    
if (132k
getRankProximity(Sec, CurSec) != Proximity ||
1040
132k
        Sec->SortRank < CurSec->SortRank)
1041
43
      break;
1042
132k
  }
1043
576
  auto J = std::find_if(
1044
576
      llvm::make_reverse_iterator(I), llvm::make_reverse_iterator(B),
1045
602
      [](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
1045
7
      [](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
1045
38
      [](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
1045
524
      [](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
1045
33
      [](BaseCommand *Cmd) { return isa<OutputSection>(Cmd); });
1046
576
  I = J.base();
1047
576
1048
576
  // As a special case, if the orphan section is the last section, put
1049
576
  // it at the very end, past any other commands.
1050
576
  // This matches bfd's behavior and is convenient when the linker script fully
1051
576
  // specifies the start of the file, but doesn't care about the end (the non
1052
576
  // alloc sections for example).
1053
576
  auto NextSec = std::find_if(
1054
93
      I, E, [](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**>)::'lambda0'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1054
78
      I, E, [](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**>)::'lambda0'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1054
2
      I, E, [](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**>)::'lambda0'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1054
2
      I, E, [](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**>)::'lambda0'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1054
11
      I, E, [](BaseCommand *Cmd) { return isa<OutputSection>(Cmd); });
1055
576
  if (NextSec == E)
1056
533
    return E;
1057
43
1058
48
  
while (43
I != E && 48
shouldSkip(*I)48
)
1059
5
    ++I;
1060
616
  return I;
1061
616
}
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
1023
39
              std::vector<BaseCommand *>::iterator E) {
1024
39
  OutputSection *Sec = cast<OutputSection>(*E);
1025
39
1026
39
  // Find the first element that has as close a rank as possible.
1027
39
  auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
1028
39
    return getRankProximity(Sec, A) < getRankProximity(Sec, B);
1029
39
  });
1030
39
  if (I == E)
1031
0
    return E;
1032
39
1033
39
  // Consider all existing sections with the same proximity.
1034
39
  int Proximity = getRankProximity(Sec, *I);
1035
213
  for (; 
I != E213
;
++I174
) {
1036
176
    auto *CurSec = dyn_cast<OutputSection>(*I);
1037
176
    if (
!CurSec || 176
!CurSec->Live176
)
1038
0
      continue;
1039
176
    
if (176
getRankProximity(Sec, CurSec) != Proximity ||
1040
175
        Sec->SortRank < CurSec->SortRank)
1041
2
      break;
1042
176
  }
1043
39
  auto J = std::find_if(
1044
39
      llvm::make_reverse_iterator(I), llvm::make_reverse_iterator(B),
1045
39
      [](BaseCommand *Cmd) { return isa<OutputSection>(Cmd); });
1046
39
  I = J.base();
1047
39
1048
39
  // As a special case, if the orphan section is the last section, put
1049
39
  // it at the very end, past any other commands.
1050
39
  // This matches bfd's behavior and is convenient when the linker script fully
1051
39
  // specifies the start of the file, but doesn't care about the end (the non
1052
39
  // alloc sections for example).
1053
39
  auto NextSec = std::find_if(
1054
39
      I, E, [](BaseCommand *Cmd) { return isa<OutputSection>(Cmd); });
1055
39
  if (NextSec == E)
1056
37
    return E;
1057
2
1058
2
  
while (2
I != E && 2
shouldSkip(*I)2
)
1059
0
    ++I;
1060
39
  return I;
1061
39
}
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
1023
8
              std::vector<BaseCommand *>::iterator E) {
1024
8
  OutputSection *Sec = cast<OutputSection>(*E);
1025
8
1026
8
  // Find the first element that has as close a rank as possible.
1027
8
  auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
1028
8
    return getRankProximity(Sec, A) < getRankProximity(Sec, B);
1029
8
  });
1030
8
  if (I == E)
1031
0
    return E;
1032
8
1033
8
  // Consider all existing sections with the same proximity.
1034
8
  int Proximity = getRankProximity(Sec, *I);
1035
35
  for (; 
I != E35
;
++I27
) {
1036
29
    auto *CurSec = dyn_cast<OutputSection>(*I);
1037
29
    if (
!CurSec || 29
!CurSec->Live29
)
1038
0
      continue;
1039
29
    
if (29
getRankProximity(Sec, CurSec) != Proximity ||
1040
29
        Sec->SortRank < CurSec->SortRank)
1041
2
      break;
1042
29
  }
1043
8
  auto J = std::find_if(
1044
8
      llvm::make_reverse_iterator(I), llvm::make_reverse_iterator(B),
1045
8
      [](BaseCommand *Cmd) { return isa<OutputSection>(Cmd); });
1046
8
  I = J.base();
1047
8
1048
8
  // As a special case, if the orphan section is the last section, put
1049
8
  // it at the very end, past any other commands.
1050
8
  // This matches bfd's behavior and is convenient when the linker script fully
1051
8
  // specifies the start of the file, but doesn't care about the end (the non
1052
8
  // alloc sections for example).
1053
8
  auto NextSec = std::find_if(
1054
8
      I, E, [](BaseCommand *Cmd) { return isa<OutputSection>(Cmd); });
1055
8
  if (NextSec == E)
1056
6
    return E;
1057
2
1058
2
  
while (2
I != E && 2
shouldSkip(*I)2
)
1059
0
    ++I;
1060
8
  return I;
1061
8
}
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
1023
31
              std::vector<BaseCommand *>::iterator E) {
1024
31
  OutputSection *Sec = cast<OutputSection>(*E);
1025
31
1026
31
  // Find the first element that has as close a rank as possible.
1027
31
  auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
1028
31
    return getRankProximity(Sec, A) < getRankProximity(Sec, B);
1029
31
  });
1030
31
  if (I == E)
1031
0
    return E;
1032
31
1033
31
  // Consider all existing sections with the same proximity.
1034
31
  int Proximity = getRankProximity(Sec, *I);
1035
131
  for (; 
I != E131
;
++I100
) {
1036
108
    auto *CurSec = dyn_cast<OutputSection>(*I);
1037
108
    if (
!CurSec || 108
!CurSec->Live102
)
1038
6
      continue;
1039
102
    
if (102
getRankProximity(Sec, CurSec) != Proximity ||
1040
99
        Sec->SortRank < CurSec->SortRank)
1041
8
      break;
1042
108
  }
1043
31
  auto J = std::find_if(
1044
31
      llvm::make_reverse_iterator(I), llvm::make_reverse_iterator(B),
1045
31
      [](BaseCommand *Cmd) { return isa<OutputSection>(Cmd); });
1046
31
  I = J.base();
1047
31
1048
31
  // As a special case, if the orphan section is the last section, put
1049
31
  // it at the very end, past any other commands.
1050
31
  // This matches bfd's behavior and is convenient when the linker script fully
1051
31
  // specifies the start of the file, but doesn't care about the end (the non
1052
31
  // alloc sections for example).
1053
31
  auto NextSec = std::find_if(
1054
31
      I, E, [](BaseCommand *Cmd) { return isa<OutputSection>(Cmd); });
1055
31
  if (NextSec == E)
1056
23
    return E;
1057
8
1058
11
  
while (8
I != E && 11
shouldSkip(*I)11
)
1059
3
    ++I;
1060
31
  return I;
1061
31
}
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
1023
538
              std::vector<BaseCommand *>::iterator E) {
1024
538
  OutputSection *Sec = cast<OutputSection>(*E);
1025
538
1026
538
  // Find the first element that has as close a rank as possible.
1027
538
  auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
1028
538
    return getRankProximity(Sec, A) < getRankProximity(Sec, B);
1029
538
  });
1030
538
  if (I == E)
1031
40
    return E;
1032
498
1033
498
  // Consider all existing sections with the same proximity.
1034
498
  int Proximity = getRankProximity(Sec, *I);
1035
132k
  for (; 
I != E132k
;
++I131k
) {
1036
131k
    auto *CurSec = dyn_cast<OutputSection>(*I);
1037
131k
    if (
!CurSec || 131k
!CurSec->Live131k
)
1038
153
      continue;
1039
131k
    
if (131k
getRankProximity(Sec, CurSec) != Proximity ||
1040
131k
        Sec->SortRank < CurSec->SortRank)
1041
31
      break;
1042
131k
  }
1043
498
  auto J = std::find_if(
1044
498
      llvm::make_reverse_iterator(I), llvm::make_reverse_iterator(B),
1045
498
      [](BaseCommand *Cmd) { return isa<OutputSection>(Cmd); });
1046
498
  I = J.base();
1047
498
1048
498
  // As a special case, if the orphan section is the last section, put
1049
498
  // it at the very end, past any other commands.
1050
498
  // This matches bfd's behavior and is convenient when the linker script fully
1051
498
  // specifies the start of the file, but doesn't care about the end (the non
1052
498
  // alloc sections for example).
1053
498
  auto NextSec = std::find_if(
1054
498
      I, E, [](BaseCommand *Cmd) { return isa<OutputSection>(Cmd); });
1055
498
  if (NextSec == E)
1056
467
    return E;
1057
31
1058
33
  
while (31
I != E && 33
shouldSkip(*I)33
)
1059
2
    ++I;
1060
538
  return I;
1061
538
}
1062
1063
1.53k
template <class ELFT> void Writer<ELFT>::sortSections() {
1064
1.53k
  if (Script->Opt.HasSections)
1065
287
    Script->adjustSectionsBeforeSorting();
1066
1.53k
1067
1.53k
  // Don't sort if using -r. It is not necessary and we want to preserve the
1068
1.53k
  // relative order for SHF_LINK_ORDER sections.
1069
1.53k
  if (Config->Relocatable)
1070
59
    return;
1071
1.47k
1072
1.47k
  for (BaseCommand *Base : Script->Opt.Commands)
1073
210k
    
if (auto *210k
Sec210k
= dyn_cast<OutputSection>(Base))
1074
208k
      Sec->SortRank = getSectionRank(Sec);
1075
1.47k
1076
1.47k
  if (
!Script->Opt.HasSections1.47k
) {
1077
1.18k
    // We know that all the OutputSections are contiguous in
1078
1.18k
    // this case.
1079
1.18k
    auto E = Script->Opt.Commands.end();
1080
1.18k
    auto I = Script->Opt.Commands.begin();
1081
3.58k
    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
1081
492
    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
1081
237
    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
1081
2.73k
    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
1081
123
    auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
1082
1.18k
    I = std::find_if(I, E, IsSection);
1083
1.18k
    E = std::find_if(llvm::make_reverse_iterator(E),
1084
1.18k
                     llvm::make_reverse_iterator(I), IsSection)
1085
1.18k
            .base();
1086
1.18k
    std::stable_sort(I, E, compareSections);
1087
1.18k
    return;
1088
1.18k
  }
1089
286
1090
286
  // Orphan sections are sections present in the input files which are
1091
286
  // not explicitly placed into the output file by the linker script.
1092
286
  //
1093
286
  // The sections in the linker script are already in the correct
1094
286
  // order. We have to figuere out where to insert the orphan
1095
286
  // sections.
1096
286
  //
1097
286
  // The order of the sections in the script is arbitrary and may not agree with
1098
286
  // compareSections. This means that we cannot easily define a strict weak
1099
286
  // ordering. To see why, consider a comparison of a section in the script and
1100
286
  // one not in the script. We have a two simple options:
1101
286
  // * Make them equivalent (a is not less than b, and b is not less than a).
1102
286
  //   The problem is then that equivalence has to be transitive and we can
1103
286
  //   have sections a, b and c with only b in a script and a less than c
1104
286
  //   which breaks this property.
1105
286
  // * Use compareSectionsNonScript. Given that the script order doesn't have
1106
286
  //   to match, we can end up with sections a, b, c, d where b and c are in the
1107
286
  //   script and c is compareSectionsNonScript less than b. In which case d
1108
286
  //   can be equivalent to c, a to b and d < a. As a concrete example:
1109
286
  //   .a (rx) # not in script
1110
286
  //   .b (rx) # in script
1111
286
  //   .c (ro) # in script
1112
286
  //   .d (ro) # not in script
1113
286
  //
1114
286
  // The way we define an order then is:
1115
286
  // *  Sort only the orphan sections. They are in the end right now.
1116
286
  // *  Move each orphan section to its preferred position. We try
1117
286
  //    to put each section in the last position where it it can share
1118
286
  //    a PT_LOAD.
1119
286
  //
1120
286
  // There is some ambiguity as to where exactly a new entry should be
1121
286
  // inserted, because Opt.Commands contains not only output section
1122
286
  // commands but also other types of commands such as symbol assignment
1123
286
  // expressions. There's no correct answer here due to the lack of the
1124
286
  // formal specification of the linker script. We use heuristics to
1125
286
  // determine whether a new output command should be added before or
1126
286
  // after another commands. For the details, look at shouldSkip
1127
286
  // function.
1128
286
1129
286
  auto I = Script->Opt.Commands.begin();
1130
286
  auto E = Script->Opt.Commands.end();
1131
968
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1132
968
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1133
729
      
return Sec->Live && 729
Sec->SectionIndex == INT_MAX701
;
1134
239
    return false;
1135
239
  });
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
1131
90
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1132
90
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1133
80
      
return Sec->Live && 80
Sec->SectionIndex == INT_MAX80
;
1134
10
    return false;
1135
10
  });
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
1131
6
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1132
6
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1133
5
      
return Sec->Live && 5
Sec->SectionIndex == INT_MAX5
;
1134
1
    return false;
1135
1
  });
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
1131
851
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1132
851
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1133
626
      
return Sec->Live && 626
Sec->SectionIndex == INT_MAX598
;
1134
225
    return false;
1135
225
  });
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
1131
21
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1132
21
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1133
18
      
return Sec->Live && 18
Sec->SectionIndex == INT_MAX18
;
1134
3
    return false;
1135
3
  });
1136
286
1137
286
  // Sort the orphan sections.
1138
286
  std::stable_sort(NonScriptI, E, compareSections);
1139
286
1140
286
  // As a horrible special case, skip the first . assignment if it is before any
1141
286
  // section. We do this because it is common to set a load address by starting
1142
286
  // the script with ". = 0xabcd" and the expectation is that every section is
1143
286
  // after that.
1144
286
  auto FirstSectionOrDotAssignment =
1145
366
      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
1145
338
      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
1145
2
      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
1145
19
      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
1145
7
      std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1146
286
  if (FirstSectionOrDotAssignment != E &&
1147
286
      isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1148
78
    ++FirstSectionOrDotAssignment;
1149
286
  I = FirstSectionOrDotAssignment;
1150
286
1151
902
  while (
NonScriptI != E902
) {
1152
616
    auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1153
616
    OutputSection *Orphan = cast<OutputSection>(*NonScriptI);
1154
616
1155
616
    // As an optimization, find all sections with the same sort rank
1156
616
    // and insert them with one rotate.
1157
616
    unsigned Rank = Orphan->SortRank;
1158
132k
    auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1159
132k
      return cast<OutputSection>(Cmd)->SortRank != Rank;
1160
132k
    });
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
1158
131k
    auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1159
131k
      return cast<OutputSection>(Cmd)->SortRank != Rank;
1160
131k
    });
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
1158
20
    auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1159
20
      return cast<OutputSection>(Cmd)->SortRank != Rank;
1160
20
    });
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
1158
104
    auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1159
104
      return cast<OutputSection>(Cmd)->SortRank != Rank;
1160
104
    });
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
1158
70
    auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1159
70
      return cast<OutputSection>(Cmd)->SortRank != Rank;
1160
70
    });
1161
616
    std::rotate(Pos, NonScriptI, End);
1162
616
    NonScriptI = End;
1163
616
  }
1164
1.53k
1165
1.53k
  Script->adjustSectionsAfterSorting();
1166
1.53k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::sortSections()
Line
Count
Source
1063
189
template <class ELFT> void Writer<ELFT>::sortSections() {
1064
189
  if (Script->Opt.HasSections)
1065
19
    Script->adjustSectionsBeforeSorting();
1066
189
1067
189
  // Don't sort if using -r. It is not necessary and we want to preserve the
1068
189
  // relative order for SHF_LINK_ORDER sections.
1069
189
  if (Config->Relocatable)
1070
6
    return;
1071
183
1072
183
  for (BaseCommand *Base : Script->Opt.Commands)
1073
1.90k
    
if (auto *1.90k
Sec1.90k
= dyn_cast<OutputSection>(Base))
1074
1.73k
      Sec->SortRank = getSectionRank(Sec);
1075
183
1076
183
  if (
!Script->Opt.HasSections183
) {
1077
164
    // We know that all the OutputSections are contiguous in
1078
164
    // this case.
1079
164
    auto E = Script->Opt.Commands.end();
1080
164
    auto I = Script->Opt.Commands.begin();
1081
164
    auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
1082
164
    I = std::find_if(I, E, IsSection);
1083
164
    E = std::find_if(llvm::make_reverse_iterator(E),
1084
164
                     llvm::make_reverse_iterator(I), IsSection)
1085
164
            .base();
1086
164
    std::stable_sort(I, E, compareSections);
1087
164
    return;
1088
164
  }
1089
19
1090
19
  // Orphan sections are sections present in the input files which are
1091
19
  // not explicitly placed into the output file by the linker script.
1092
19
  //
1093
19
  // The sections in the linker script are already in the correct
1094
19
  // order. We have to figuere out where to insert the orphan
1095
19
  // sections.
1096
19
  //
1097
19
  // The order of the sections in the script is arbitrary and may not agree with
1098
19
  // compareSections. This means that we cannot easily define a strict weak
1099
19
  // ordering. To see why, consider a comparison of a section in the script and
1100
19
  // one not in the script. We have a two simple options:
1101
19
  // * Make them equivalent (a is not less than b, and b is not less than a).
1102
19
  //   The problem is then that equivalence has to be transitive and we can
1103
19
  //   have sections a, b and c with only b in a script and a less than c
1104
19
  //   which breaks this property.
1105
19
  // * Use compareSectionsNonScript. Given that the script order doesn't have
1106
19
  //   to match, we can end up with sections a, b, c, d where b and c are in the
1107
19
  //   script and c is compareSectionsNonScript less than b. In which case d
1108
19
  //   can be equivalent to c, a to b and d < a. As a concrete example:
1109
19
  //   .a (rx) # not in script
1110
19
  //   .b (rx) # in script
1111
19
  //   .c (ro) # in script
1112
19
  //   .d (ro) # not in script
1113
19
  //
1114
19
  // The way we define an order then is:
1115
19
  // *  Sort only the orphan sections. They are in the end right now.
1116
19
  // *  Move each orphan section to its preferred position. We try
1117
19
  //    to put each section in the last position where it it can share
1118
19
  //    a PT_LOAD.
1119
19
  //
1120
19
  // There is some ambiguity as to where exactly a new entry should be
1121
19
  // inserted, because Opt.Commands contains not only output section
1122
19
  // commands but also other types of commands such as symbol assignment
1123
19
  // expressions. There's no correct answer here due to the lack of the
1124
19
  // formal specification of the linker script. We use heuristics to
1125
19
  // determine whether a new output command should be added before or
1126
19
  // after another commands. For the details, look at shouldSkip
1127
19
  // function.
1128
19
1129
19
  auto I = Script->Opt.Commands.begin();
1130
19
  auto E = Script->Opt.Commands.end();
1131
19
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1132
19
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1133
19
      return Sec->Live && Sec->SectionIndex == INT_MAX;
1134
19
    return false;
1135
19
  });
1136
19
1137
19
  // Sort the orphan sections.
1138
19
  std::stable_sort(NonScriptI, E, compareSections);
1139
19
1140
19
  // As a horrible special case, skip the first . assignment if it is before any
1141
19
  // section. We do this because it is common to set a load address by starting
1142
19
  // the script with ". = 0xabcd" and the expectation is that every section is
1143
19
  // after that.
1144
19
  auto FirstSectionOrDotAssignment =
1145
19
      std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1146
19
  if (FirstSectionOrDotAssignment != E &&
1147
19
      isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1148
10
    ++FirstSectionOrDotAssignment;
1149
19
  I = FirstSectionOrDotAssignment;
1150
19
1151
58
  while (
NonScriptI != E58
) {
1152
39
    auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1153
39
    OutputSection *Orphan = cast<OutputSection>(*NonScriptI);
1154
39
1155
39
    // As an optimization, find all sections with the same sort rank
1156
39
    // and insert them with one rotate.
1157
39
    unsigned Rank = Orphan->SortRank;
1158
39
    auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1159
39
      return cast<OutputSection>(Cmd)->SortRank != Rank;
1160
39
    });
1161
39
    std::rotate(Pos, NonScriptI, End);
1162
39
    NonScriptI = End;
1163
39
  }
1164
189
1165
189
  Script->adjustSectionsAfterSorting();
1166
189
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::sortSections()
Line
Count
Source
1063
93
template <class ELFT> void Writer<ELFT>::sortSections() {
1064
93
  if (Script->Opt.HasSections)
1065
7
    Script->adjustSectionsBeforeSorting();
1066
93
1067
93
  // Don't sort if using -r. It is not necessary and we want to preserve the
1068
93
  // relative order for SHF_LINK_ORDER sections.
1069
93
  if (Config->Relocatable)
1070
7
    return;
1071
86
1072
86
  for (BaseCommand *Base : Script->Opt.Commands)
1073
1.20k
    
if (auto *1.20k
Sec1.20k
= dyn_cast<OutputSection>(Base))
1074
1.12k
      Sec->SortRank = getSectionRank(Sec);
1075
86
1076
86
  if (
!Script->Opt.HasSections86
) {
1077
79
    // We know that all the OutputSections are contiguous in
1078
79
    // this case.
1079
79
    auto E = Script->Opt.Commands.end();
1080
79
    auto I = Script->Opt.Commands.begin();
1081
79
    auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
1082
79
    I = std::find_if(I, E, IsSection);
1083
79
    E = std::find_if(llvm::make_reverse_iterator(E),
1084
79
                     llvm::make_reverse_iterator(I), IsSection)
1085
79
            .base();
1086
79
    std::stable_sort(I, E, compareSections);
1087
79
    return;
1088
79
  }
1089
7
1090
7
  // Orphan sections are sections present in the input files which are
1091
7
  // not explicitly placed into the output file by the linker script.
1092
7
  //
1093
7
  // The sections in the linker script are already in the correct
1094
7
  // order. We have to figuere out where to insert the orphan
1095
7
  // sections.
1096
7
  //
1097
7
  // The order of the sections in the script is arbitrary and may not agree with
1098
7
  // compareSections. This means that we cannot easily define a strict weak
1099
7
  // ordering. To see why, consider a comparison of a section in the script and
1100
7
  // one not in the script. We have a two simple options:
1101
7
  // * Make them equivalent (a is not less than b, and b is not less than a).
1102
7
  //   The problem is then that equivalence has to be transitive and we can
1103
7
  //   have sections a, b and c with only b in a script and a less than c
1104
7
  //   which breaks this property.
1105
7
  // * Use compareSectionsNonScript. Given that the script order doesn't have
1106
7
  //   to match, we can end up with sections a, b, c, d where b and c are in the
1107
7
  //   script and c is compareSectionsNonScript less than b. In which case d
1108
7
  //   can be equivalent to c, a to b and d < a. As a concrete example:
1109
7
  //   .a (rx) # not in script
1110
7
  //   .b (rx) # in script
1111
7
  //   .c (ro) # in script
1112
7
  //   .d (ro) # not in script
1113
7
  //
1114
7
  // The way we define an order then is:
1115
7
  // *  Sort only the orphan sections. They are in the end right now.
1116
7
  // *  Move each orphan section to its preferred position. We try
1117
7
  //    to put each section in the last position where it it can share
1118
7
  //    a PT_LOAD.
1119
7
  //
1120
7
  // There is some ambiguity as to where exactly a new entry should be
1121
7
  // inserted, because Opt.Commands contains not only output section
1122
7
  // commands but also other types of commands such as symbol assignment
1123
7
  // expressions. There's no correct answer here due to the lack of the
1124
7
  // formal specification of the linker script. We use heuristics to
1125
7
  // determine whether a new output command should be added before or
1126
7
  // after another commands. For the details, look at shouldSkip
1127
7
  // function.
1128
7
1129
7
  auto I = Script->Opt.Commands.begin();
1130
7
  auto E = Script->Opt.Commands.end();
1131
7
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1132
7
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1133
7
      return Sec->Live && Sec->SectionIndex == INT_MAX;
1134
7
    return false;
1135
7
  });
1136
7
1137
7
  // Sort the orphan sections.
1138
7
  std::stable_sort(NonScriptI, E, compareSections);
1139
7
1140
7
  // As a horrible special case, skip the first . assignment if it is before any
1141
7
  // section. We do this because it is common to set a load address by starting
1142
7
  // the script with ". = 0xabcd" and the expectation is that every section is
1143
7
  // after that.
1144
7
  auto FirstSectionOrDotAssignment =
1145
7
      std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1146
7
  if (FirstSectionOrDotAssignment != E &&
1147
7
      isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1148
0
    ++FirstSectionOrDotAssignment;
1149
7
  I = FirstSectionOrDotAssignment;
1150
7
1151
38
  while (
NonScriptI != E38
) {
1152
31
    auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1153
31
    OutputSection *Orphan = cast<OutputSection>(*NonScriptI);
1154
31
1155
31
    // As an optimization, find all sections with the same sort rank
1156
31
    // and insert them with one rotate.
1157
31
    unsigned Rank = Orphan->SortRank;
1158
31
    auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1159
31
      return cast<OutputSection>(Cmd)->SortRank != Rank;
1160
31
    });
1161
31
    std::rotate(Pos, NonScriptI, End);
1162
31
    NonScriptI = End;
1163
31
  }
1164
93
1165
93
  Script->adjustSectionsAfterSorting();
1166
93
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::sortSections()
Line
Count
Source
1063
1.20k
template <class ELFT> void Writer<ELFT>::sortSections() {
1064
1.20k
  if (Script->Opt.HasSections)
1065
259
    Script->adjustSectionsBeforeSorting();
1066
1.20k
1067
1.20k
  // Don't sort if using -r. It is not necessary and we want to preserve the
1068
1.20k
  // relative order for SHF_LINK_ORDER sections.
1069
1.20k
  if (Config->Relocatable)
1070
45
    return;
1071
1.16k
1072
1.16k
  for (BaseCommand *Base : Script->Opt.Commands)
1073
206k
    
if (auto *206k
Sec206k
= dyn_cast<OutputSection>(Base))
1074
205k
      Sec->SortRank = getSectionRank(Sec);
1075
1.16k
1076
1.16k
  if (
!Script->Opt.HasSections1.16k
) {
1077
904
    // We know that all the OutputSections are contiguous in
1078
904
    // this case.
1079
904
    auto E = Script->Opt.Commands.end();
1080
904
    auto I = Script->Opt.Commands.begin();
1081
904
    auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
1082
904
    I = std::find_if(I, E, IsSection);
1083
904
    E = std::find_if(llvm::make_reverse_iterator(E),
1084
904
                     llvm::make_reverse_iterator(I), IsSection)
1085
904
            .base();
1086
904
    std::stable_sort(I, E, compareSections);
1087
904
    return;
1088
904
  }
1089
258
1090
258
  // Orphan sections are sections present in the input files which are
1091
258
  // not explicitly placed into the output file by the linker script.
1092
258
  //
1093
258
  // The sections in the linker script are already in the correct
1094
258
  // order. We have to figuere out where to insert the orphan
1095
258
  // sections.
1096
258
  //
1097
258
  // The order of the sections in the script is arbitrary and may not agree with
1098
258
  // compareSections. This means that we cannot easily define a strict weak
1099
258
  // ordering. To see why, consider a comparison of a section in the script and
1100
258
  // one not in the script. We have a two simple options:
1101
258
  // * Make them equivalent (a is not less than b, and b is not less than a).
1102
258
  //   The problem is then that equivalence has to be transitive and we can
1103
258
  //   have sections a, b and c with only b in a script and a less than c
1104
258
  //   which breaks this property.
1105
258
  // * Use compareSectionsNonScript. Given that the script order doesn't have
1106
258
  //   to match, we can end up with sections a, b, c, d where b and c are in the
1107
258
  //   script and c is compareSectionsNonScript less than b. In which case d
1108
258
  //   can be equivalent to c, a to b and d < a. As a concrete example:
1109
258
  //   .a (rx) # not in script
1110
258
  //   .b (rx) # in script
1111
258
  //   .c (ro) # in script
1112
258
  //   .d (ro) # not in script
1113
258
  //
1114
258
  // The way we define an order then is:
1115
258
  // *  Sort only the orphan sections. They are in the end right now.
1116
258
  // *  Move each orphan section to its preferred position. We try
1117
258
  //    to put each section in the last position where it it can share
1118
258
  //    a PT_LOAD.
1119
258
  //
1120
258
  // There is some ambiguity as to where exactly a new entry should be
1121
258
  // inserted, because Opt.Commands contains not only output section
1122
258
  // commands but also other types of commands such as symbol assignment
1123
258
  // expressions. There's no correct answer here due to the lack of the
1124
258
  // formal specification of the linker script. We use heuristics to
1125
258
  // determine whether a new output command should be added before or
1126
258
  // after another commands. For the details, look at shouldSkip
1127
258
  // function.
1128
258
1129
258
  auto I = Script->Opt.Commands.begin();
1130
258
  auto E = Script->Opt.Commands.end();
1131
258
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1132
258
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1133
258
      return Sec->Live && Sec->SectionIndex == INT_MAX;
1134
258
    return false;
1135
258
  });
1136
258
1137
258
  // Sort the orphan sections.
1138
258
  std::stable_sort(NonScriptI, E, compareSections);
1139
258
1140
258
  // As a horrible special case, skip the first . assignment if it is before any
1141
258
  // section. We do this because it is common to set a load address by starting
1142
258
  // the script with ". = 0xabcd" and the expectation is that every section is
1143
258
  // after that.
1144
258
  auto FirstSectionOrDotAssignment =
1145
258
      std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1146
258
  if (FirstSectionOrDotAssignment != E &&
1147
258
      isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1148
67
    ++FirstSectionOrDotAssignment;
1149
258
  I = FirstSectionOrDotAssignment;
1150
258
1151
796
  while (
NonScriptI != E796
) {
1152
538
    auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1153
538
    OutputSection *Orphan = cast<OutputSection>(*NonScriptI);
1154
538
1155
538
    // As an optimization, find all sections with the same sort rank
1156
538
    // and insert them with one rotate.
1157
538
    unsigned Rank = Orphan->SortRank;
1158
538
    auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1159
538
      return cast<OutputSection>(Cmd)->SortRank != Rank;
1160
538
    });
1161
538
    std::rotate(Pos, NonScriptI, End);
1162
538
    NonScriptI = End;
1163
538
  }
1164
1.20k
1165
1.20k
  Script->adjustSectionsAfterSorting();
1166
1.20k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::sortSections()
Line
Count
Source
1063
44
template <class ELFT> void Writer<ELFT>::sortSections() {
1064
44
  if (Script->Opt.HasSections)
1065
2
    Script->adjustSectionsBeforeSorting();
1066
44
1067
44
  // Don't sort if using -r. It is not necessary and we want to preserve the
1068
44
  // relative order for SHF_LINK_ORDER sections.
1069
44
  if (Config->Relocatable)
1070
1
    return;
1071
43
1072
43
  for (BaseCommand *Base : Script->Opt.Commands)
1073
561
    
if (auto *561
Sec561
= dyn_cast<OutputSection>(Base))
1074
519
      Sec->SortRank = getSectionRank(Sec);
1075
43
1076
43
  if (
!Script->Opt.HasSections43
) {
1077
41
    // We know that all the OutputSections are contiguous in
1078
41
    // this case.
1079
41
    auto E = Script->Opt.Commands.end();
1080
41
    auto I = Script->Opt.Commands.begin();
1081
41
    auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
1082
41
    I = std::find_if(I, E, IsSection);
1083
41
    E = std::find_if(llvm::make_reverse_iterator(E),
1084
41
                     llvm::make_reverse_iterator(I), IsSection)
1085
41
            .base();
1086
41
    std::stable_sort(I, E, compareSections);
1087
41
    return;
1088
41
  }
1089
2
1090
2
  // Orphan sections are sections present in the input files which are
1091
2
  // not explicitly placed into the output file by the linker script.
1092
2
  //
1093
2
  // The sections in the linker script are already in the correct
1094
2
  // order. We have to figuere out where to insert the orphan
1095
2
  // sections.
1096
2
  //
1097
2
  // The order of the sections in the script is arbitrary and may not agree with
1098
2
  // compareSections. This means that we cannot easily define a strict weak
1099
2
  // ordering. To see why, consider a comparison of a section in the script and
1100
2
  // one not in the script. We have a two simple options:
1101
2
  // * Make them equivalent (a is not less than b, and b is not less than a).
1102
2
  //   The problem is then that equivalence has to be transitive and we can
1103
2
  //   have sections a, b and c with only b in a script and a less than c
1104
2
  //   which breaks this property.
1105
2
  // * Use compareSectionsNonScript. Given that the script order doesn't have
1106
2
  //   to match, we can end up with sections a, b, c, d where b and c are in the
1107
2
  //   script and c is compareSectionsNonScript less than b. In which case d
1108
2
  //   can be equivalent to c, a to b and d < a. As a concrete example:
1109
2
  //   .a (rx) # not in script
1110
2
  //   .b (rx) # in script
1111
2
  //   .c (ro) # in script
1112
2
  //   .d (ro) # not in script
1113
2
  //
1114
2
  // The way we define an order then is:
1115
2
  // *  Sort only the orphan sections. They are in the end right now.
1116
2
  // *  Move each orphan section to its preferred position. We try
1117
2
  //    to put each section in the last position where it it can share
1118
2
  //    a PT_LOAD.
1119
2
  //
1120
2
  // There is some ambiguity as to where exactly a new entry should be
1121
2
  // inserted, because Opt.Commands contains not only output section
1122
2
  // commands but also other types of commands such as symbol assignment
1123
2
  // expressions. There's no correct answer here due to the lack of the
1124
2
  // formal specification of the linker script. We use heuristics to
1125
2
  // determine whether a new output command should be added before or
1126
2
  // after another commands. For the details, look at shouldSkip
1127
2
  // function.
1128
2
1129
2
  auto I = Script->Opt.Commands.begin();
1130
2
  auto E = Script->Opt.Commands.end();
1131
2
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1132
2
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1133
2
      return Sec->Live && Sec->SectionIndex == INT_MAX;
1134
2
    return false;
1135
2
  });
1136
2
1137
2
  // Sort the orphan sections.
1138
2
  std::stable_sort(NonScriptI, E, compareSections);
1139
2
1140
2
  // As a horrible special case, skip the first . assignment if it is before any
1141
2
  // section. We do this because it is common to set a load address by starting
1142
2
  // the script with ". = 0xabcd" and the expectation is that every section is
1143
2
  // after that.
1144
2
  auto FirstSectionOrDotAssignment =
1145
2
      std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1146
2
  if (FirstSectionOrDotAssignment != E &&
1147
2
      isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1148
1
    ++FirstSectionOrDotAssignment;
1149
2
  I = FirstSectionOrDotAssignment;
1150
2
1151
10
  while (
NonScriptI != E10
) {
1152
8
    auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1153
8
    OutputSection *Orphan = cast<OutputSection>(*NonScriptI);
1154
8
1155
8
    // As an optimization, find all sections with the same sort rank
1156
8
    // and insert them with one rotate.
1157
8
    unsigned Rank = Orphan->SortRank;
1158
8
    auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1159
8
      return cast<OutputSection>(Cmd)->SortRank != Rank;
1160
8
    });
1161
8
    std::rotate(Pos, NonScriptI, End);
1162
8
    NonScriptI = End;
1163
8
  }
1164
44
1165
44
  Script->adjustSectionsAfterSorting();
1166
44
}
1167
1168
static void applySynthetic(const std::vector<SyntheticSection *> &Sections,
1169
4.68k
                           std::function<void(SyntheticSection *)> Fn) {
1170
4.68k
  for (SyntheticSection *SS : Sections)
1171
41.4k
    
if (41.4k
SS && 41.4k
SS->getParent()32.2k
&&
!SS->empty()29.9k
)
1172
13.2k
      Fn(SS);
1173
4.68k
}
1174
1175
// We need to add input synthetic sections early in createSyntheticSections()
1176
// to make them visible from linkescript side. But not all sections are always
1177
// required to be in output. For example we don't need dynamic section content
1178
// sometimes. This function filters out such unused sections from the output.
1179
1.53k
static void removeUnusedSyntheticSections() {
1180
1.53k
  // All input synthetic sections that can be empty are placed after
1181
1.53k
  // all regular ones. We iterate over them all and exit at first
1182
1.53k
  // non-synthetic.
1183
28.6k
  for (InputSectionBase *S : llvm::reverse(InputSections)) {
1184
28.6k
    SyntheticSection *SS = dyn_cast<SyntheticSection>(S);
1185
28.6k
    if (!SS)
1186
1.52k
      return;
1187
27.1k
    OutputSection *OS = SS->getParent();
1188
27.1k
    if (
!SS->empty() || 27.1k
!OS16.6k
)
1189
10.5k
      continue;
1190
16.6k
1191
16.6k
    std::vector<BaseCommand *>::iterator Empty = OS->Commands.end();
1192
33.2k
    for (auto I = OS->Commands.begin(), E = OS->Commands.end(); 
I != E33.2k
;
++I16.6k
) {
1193
16.6k
      BaseCommand *B = *I;
1194
16.6k
      if (auto *
ISD16.6k
= dyn_cast<InputSectionDescription>(B)) {
1195
16.6k
        llvm::erase_if(ISD->Sections,
1196
21.4k
                       [=](InputSection *IS) { return IS == SS; });
1197
16.6k
        if (ISD->Sections.empty())
1198
11.8k
          Empty = I;
1199
16.6k
      }
1200
16.6k
    }
1201
16.6k
    if (Empty != OS->Commands.end())
1202
11.8k
      OS->Commands.erase(Empty);
1203
16.6k
1204
16.6k
    // If there are no other sections in the output section, remove it from the
1205
16.6k
    // output.
1206
16.6k
    if (OS->Commands.empty())
1207
11.8k
      llvm::erase_if(Script->Opt.Commands,
1208
1.34M
                     [&](BaseCommand *Cmd) { return Cmd == OS; });
1209
28.6k
  }
1210
1.53k
}
1211
1212
// Returns true if a symbol can be replaced at load-time by a symbol
1213
// with the same name defined in other ELF executable or DSO.
1214
4.65k
static bool computeIsPreemptible(const SymbolBody &B) {
1215
4.65k
  assert(!B.isLocal());
1216
4.65k
  // Only symbols that appear in dynsym can be preempted.
1217
4.65k
  if (!B.symbol()->includeInDynsym())
1218
3.06k
    return false;
1219
1.58k
1220
1.58k
  // Only default visibility symbols can be preempted.
1221
1.58k
  
if (1.58k
B.symbol()->Visibility != STV_DEFAULT1.58k
)
1222
17
    return false;
1223
1.57k
1224
1.57k
  // At this point copy relocations have not been created yet, so any
1225
1.57k
  // symbol that is not defined locally is preemptible.
1226
1.57k
  
if (1.57k
!B.isInCurrentDSO()1.57k
)
1227
688
    return true;
1228
882
1229
882
  // If we have a dynamic list it specifies which local symbols are preemptible.
1230
882
  
if (882
Config->HasDynamicList882
)
1231
17
    return false;
1232
865
1233
865
  
if (865
!Config->Shared865
)
1234
64
    return false;
1235
801
1236
801
  // -Bsymbolic means that definitions are not preempted.
1237
801
  
if (801
Config->Bsymbolic || 801
(Config->BsymbolicFunctions && 792
B.isFunc()3
))
1238
12
    return false;
1239
789
  return true;
1240
789
}
1241
1242
// Create output section objects and add them to OutputSections.
1243
1.59k
template <class ELFT> void Writer<ELFT>::finalizeSections() {
1244
1.59k
  Out::DebugInfo = findSection(".debug_info");
1245
1.59k
  Out::PreinitArray = findSection(".preinit_array");
1246
1.59k
  Out::InitArray = findSection(".init_array");
1247
1.59k
  Out::FiniArray = findSection(".fini_array");
1248
1.59k
1249
1.59k
  // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1250
1.59k
  // symbols for sections, so that the runtime can get the start and end
1251
1.59k
  // addresses of each section by section name. Add such symbols.
1252
1.59k
  if (
!Config->Relocatable1.59k
) {
1253
1.53k
    addStartEndSymbols();
1254
1.53k
    for (BaseCommand *Base : Script->Opt.Commands)
1255
222k
      
if (auto *222k
Sec222k
= dyn_cast<OutputSection>(Base))
1256
221k
        addStartStopSymbols(Sec);
1257
1.53k
  }
1258
1.59k
1259
1.59k
  // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1260
1.59k
  // It should be okay as no one seems to care about the type.
1261
1.59k
  // Even the author of gold doesn't remember why gold behaves that way.
1262
1.59k
  // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1263
1.59k
  if (InX::DynSymTab)
1264
805
    addRegular<ELFT>("_DYNAMIC", InX::Dynamic, 0);
1265
1.59k
1266
1.59k
  // Define __rel[a]_iplt_{start,end} symbols if needed.
1267
1.59k
  addRelIpltSymbols();
1268
1.59k
1269
1.59k
  // This responsible for splitting up .eh_frame section into
1270
1.59k
  // pieces. The relocation scan uses those pieces, so this has to be
1271
1.59k
  // earlier.
1272
1.59k
  applySynthetic({In<ELFT>::EhFrame},
1273
81
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::finalizeSections()::'lambda'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1273
3
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::finalizeSections()::'lambda'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1273
74
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::finalizeSections()::'lambda'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1273
1
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::finalizeSections()::'lambda'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1273
3
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1274
1.59k
1275
1.59k
  for (Symbol *S : Symtab->getSymbols())
1276
4.65k
    S->body()->IsPreemptible |= computeIsPreemptible(*S->body());
1277
1.59k
1278
1.59k
  // Scan relocations. This must be done after every symbol is declared so that
1279
1.59k
  // we can correctly decide if a dynamic relocation is needed.
1280
1.59k
  if (!Config->Relocatable)
1281
1.53k
    forEachRelSec(scanRelocations<ELFT>);
1282
1.59k
1283
1.59k
  if (
InX::Plt && 1.59k
!InX::Plt->empty()1.59k
)
1284
132
    InX::Plt->addSymbols();
1285
1.59k
  if (
InX::Iplt && 1.59k
!InX::Iplt->empty()1.59k
)
1286
15
    InX::Iplt->addSymbols();
1287
1.59k
1288
1.59k
  // Now that we have defined all possible global symbols including linker-
1289
1.59k
  // synthesized ones. Visit all symbols to give the finishing touches.
1290
4.65k
  for (Symbol *S : Symtab->getSymbols()) {
1291
4.65k
    SymbolBody *Body = S->body();
1292
4.65k
1293
4.65k
    if (!includeInSymtab(*Body))
1294
356
      continue;
1295
4.29k
    
if (4.29k
InX::SymTab4.29k
)
1296
4.29k
      InX::SymTab->addSymbol(Body);
1297
4.29k
1298
4.29k
    if (
InX::DynSymTab && 4.29k
S->includeInDynsym()2.59k
) {
1299
1.30k
      InX::DynSymTab->addSymbol(Body);
1300
1.30k
      if (auto *SS = dyn_cast<SharedSymbol>(Body))
1301
236
        
if (236
cast<SharedFile<ELFT>>(S->File)->isNeeded()236
)
1302
233
          In<ELFT>::VerNeed->addSymbol(SS);
1303
1.30k
    }
1304
4.65k
  }
1305
1.59k
1306
1.59k
  // Do not proceed if there was an undefined symbol.
1307
1.59k
  if (ErrorCount)
1308
65
    return;
1309
1.53k
1310
1.53k
  addPredefinedSections();
1311
1.53k
  removeUnusedSyntheticSections();
1312
1.53k
1313
1.53k
  sortSections();
1314
1.53k
1315
1.53k
  // Now that we have the final list, create a list of all the
1316
1.53k
  // OutputSections for convenience.
1317
1.53k
  for (BaseCommand *Base : Script->Opt.Commands)
1318
210k
    
if (auto *210k
Sec210k
= dyn_cast<OutputSection>(Base))
1319
209k
      OutputSections.push_back(Sec);
1320
1.53k
1321
1.53k
  // Prefer command line supplied address over other constraints.
1322
209k
  for (OutputSection *Sec : OutputSections) {
1323
209k
    auto I = Config->SectionStartMap.find(Sec->Name);
1324
209k
    if (I != Config->SectionStartMap.end())
1325
42
      
Sec->AddrExpr = [=] 41
{ return I->second; }42
;
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, false> >::finalizeSections()::'lambda'()::operator()() const
Line
Count
Source
1325
6
      Sec->AddrExpr = [=] { return I->second; };
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::finalizeSections()::'lambda'()::operator()() const
Line
Count
Source
1325
34
      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
1325
2
      Sec->AddrExpr = [=] { return I->second; };
1326
209k
  }
1327
1.53k
1328
1.53k
  // This is a bit of a hack. A value of 0 means undef, so we set it
1329
1.53k
  // to 1 t make __ehdr_start defined. The section number is not
1330
1.53k
  // particularly relevant.
1331
1.53k
  Out::ElfHeader->SectionIndex = 1;
1332
1.53k
1333
1.53k
  unsigned I = 1;
1334
209k
  for (OutputSection *Sec : OutputSections) {
1335
209k
    Sec->SectionIndex = I++;
1336
209k
    Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1337
209k
  }
1338
1.53k
1339
1.53k
  // Binary and relocatable output does not have PHDRS.
1340
1.53k
  // The headers have to be created before finalize as that can influence the
1341
1.53k
  // image base and the dynamic section on mips includes the image base.
1342
1.53k
  if (
!Config->Relocatable && 1.53k
!Config->OFormatBinary1.47k
) {
1343
1.46k
    Phdrs = Script->hasPhdrsCommands() ? 
Script->createPhdrs()23
:
createPhdrs()1.44k
;
1344
1.46k
    addPtArmExid(Phdrs);
1345
1.46k
    Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1346
1.46k
  }
1347
1.53k
1348
1.53k
  // Some symbols are defined in term of program headers. Now that we
1349
1.53k
  // have the headers, we can find out which sections they point to.
1350
1.53k
  setReservedSymbolSections();
1351
1.53k
1352
1.53k
  // Dynamic section must be the last one in this list and dynamic
1353
1.53k
  // symbol table section (DynSymTab) must be the first one.
1354
1.53k
  applySynthetic({InX::DynSymTab,    InX::Bss,
1355
1.53k
                  InX::BssRelRo,     InX::GnuHashTab,
1356
1.53k
                  InX::HashTab,      InX::SymTab,
1357
1.53k
                  InX::ShStrTab,     InX::StrTab,
1358
1.53k
                  In<ELFT>::VerDef,  InX::DynStrTab,
1359
1.53k
                  InX::Got,          InX::MipsGot,
1360
1.53k
                  InX::IgotPlt,      InX::GotPlt,
1361
1.53k
                  In<ELFT>::RelaDyn, In<ELFT>::RelaIplt,
1362
1.53k
                  In<ELFT>::RelaPlt, InX::Plt,
1363
1.53k
                  InX::Iplt,         In<ELFT>::EhFrameHdr,
1364
1.53k
                  In<ELFT>::VerSym,  In<ELFT>::VerNeed,
1365
1.53k
                  InX::Dynamic},
1366
8.56k
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::finalizeSections()::'lambda0'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1366
604
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::finalizeSections()::'lambda0'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1366
6.51k
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::finalizeSections()::'lambda0'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1366
285
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::finalizeSections()::'lambda0'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1366
1.16k
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1367
1.53k
1368
1.53k
  if (
!Script->Opt.HasSections && 1.53k
!Config->Relocatable1.24k
)
1369
1.18k
    fixSectionAlignments();
1370
1.53k
1371
1.53k
  // Some architectures use small displacements for jump instructions.
1372
1.53k
  // It is linker's responsibility to create thunks containing long
1373
1.53k
  // jump instructions if jump targets are too far. Create thunks.
1374
1.53k
  if (
Target->NeedsThunks1.53k
) {
1375
215
    // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented,
1376
215
    // these
1377
215
    // do not require address information. To support range extension Thunks
1378
215
    // we need to assign addresses so that we can tell if jump instructions
1379
215
    // are out of range. This will need to turn into a loop that converges
1380
215
    // when no more Thunks are added
1381
215
    ThunkCreator TC;
1382
215
    Script->assignAddresses();
1383
215
    if (
TC.createThunks(OutputSections)215
) {
1384
16
      applySynthetic({InX::MipsGot},
1385
7
                     [](SyntheticSection *SS) { SS->updateAllocSize(); });
Unexecuted instantiation: Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::finalizeSections()::'lambda1'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::finalizeSections()::'lambda1'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1385
7
                     [](SyntheticSection *SS) { SS->updateAllocSize(); });
Unexecuted instantiation: Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::finalizeSections()::'lambda1'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Unexecuted instantiation: Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::finalizeSections()::'lambda1'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
1386
16
      if (TC.createThunks(OutputSections))
1387
0
        fatal("All non-range thunks should be created in first call");
1388
1.53k
    }
1389
215
  }
1390
1.53k
1391
1.53k
  // Fill other section headers. The dynamic table is finalized
1392
1.53k
  // at the end because some tags like RELSZ depend on result
1393
1.53k
  // of finalizing other sections.
1394
1.53k
  for (OutputSection *Sec : OutputSections)
1395
209k
    Sec->finalize<ELFT>();
1396
1.53k
1397
1.53k
  // createThunks may have added local symbols to the static symbol table
1398
1.53k
  applySynthetic({InX::SymTab, InX::ShStrTab, InX::StrTab},
1399
4.59k
                 [](SyntheticSection *SS) { SS->postThunkContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::finalizeSections()::'lambda2'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1399
567
                 [](SyntheticSection *SS) { SS->postThunkContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::finalizeSections()::'lambda2'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1399
132
                 [](SyntheticSection *SS) { SS->postThunkContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::finalizeSections()::'lambda2'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1399
3.61k
                 [](SyntheticSection *SS) { SS->postThunkContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::finalizeSections()::'lambda2'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1399
279
                 [](SyntheticSection *SS) { SS->postThunkContents(); });
1400
1.59k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::finalizeSections()
Line
Count
Source
1243
193
template <class ELFT> void Writer<ELFT>::finalizeSections() {
1244
193
  Out::DebugInfo = findSection(".debug_info");
1245
193
  Out::PreinitArray = findSection(".preinit_array");
1246
193
  Out::InitArray = findSection(".init_array");
1247
193
  Out::FiniArray = findSection(".fini_array");
1248
193
1249
193
  // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1250
193
  // symbols for sections, so that the runtime can get the start and end
1251
193
  // addresses of each section by section name. Add such symbols.
1252
193
  if (
!Config->Relocatable193
) {
1253
187
    addStartEndSymbols();
1254
187
    for (BaseCommand *Base : Script->Opt.Commands)
1255
3.42k
      
if (auto *3.42k
Sec3.42k
= dyn_cast<OutputSection>(Base))
1256
3.24k
        addStartStopSymbols(Sec);
1257
187
  }
1258
193
1259
193
  // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1260
193
  // It should be okay as no one seems to care about the type.
1261
193
  // Even the author of gold doesn't remember why gold behaves that way.
1262
193
  // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1263
193
  if (InX::DynSymTab)
1264
108
    addRegular<ELFT>("_DYNAMIC", InX::Dynamic, 0);
1265
193
1266
193
  // Define __rel[a]_iplt_{start,end} symbols if needed.
1267
193
  addRelIpltSymbols();
1268
193
1269
193
  // This responsible for splitting up .eh_frame section into
1270
193
  // pieces. The relocation scan uses those pieces, so this has to be
1271
193
  // earlier.
1272
193
  applySynthetic({In<ELFT>::EhFrame},
1273
193
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1274
193
1275
193
  for (Symbol *S : Symtab->getSymbols())
1276
635
    S->body()->IsPreemptible |= computeIsPreemptible(*S->body());
1277
193
1278
193
  // Scan relocations. This must be done after every symbol is declared so that
1279
193
  // we can correctly decide if a dynamic relocation is needed.
1280
193
  if (!Config->Relocatable)
1281
187
    forEachRelSec(scanRelocations<ELFT>);
1282
193
1283
193
  if (
InX::Plt && 193
!InX::Plt->empty()193
)
1284
24
    InX::Plt->addSymbols();
1285
193
  if (
InX::Iplt && 193
!InX::Iplt->empty()193
)
1286
6
    InX::Iplt->addSymbols();
1287
193
1288
193
  // Now that we have defined all possible global symbols including linker-
1289
193
  // synthesized ones. Visit all symbols to give the finishing touches.
1290
635
  for (Symbol *S : Symtab->getSymbols()) {
1291
635
    SymbolBody *Body = S->body();
1292
635
1293
635
    if (!includeInSymtab(*Body))
1294
31
      continue;
1295
604
    
if (604
InX::SymTab604
)
1296
604
      InX::SymTab->addSymbol(Body);
1297
604
1298
604
    if (
InX::DynSymTab && 604
S->includeInDynsym()380
) {
1299
195
      InX::DynSymTab->addSymbol(Body);
1300
195
      if (auto *SS = dyn_cast<SharedSymbol>(Body))
1301
52
        
if (52
cast<SharedFile<ELFT>>(S->File)->isNeeded()52
)
1302
50
          In<ELFT>::VerNeed->addSymbol(SS);
1303
195
    }
1304
635
  }
1305
193
1306
193
  // Do not proceed if there was an undefined symbol.
1307
193
  if (ErrorCount)
1308
4
    return;
1309
189
1310
189
  addPredefinedSections();
1311
189
  removeUnusedSyntheticSections();
1312
189
1313
189
  sortSections();
1314
189
1315
189
  // Now that we have the final list, create a list of all the
1316
189
  // OutputSections for convenience.
1317
189
  for (BaseCommand *Base : Script->Opt.Commands)
1318
1.96k
    
if (auto *1.96k
Sec1.96k
= dyn_cast<OutputSection>(Base))
1319
1.78k
      OutputSections.push_back(Sec);
1320
189
1321
189
  // Prefer command line supplied address over other constraints.
1322
1.78k
  for (OutputSection *Sec : OutputSections) {
1323
1.78k
    auto I = Config->SectionStartMap.find(Sec->Name);
1324
1.78k
    if (I != Config->SectionStartMap.end())
1325
6
      Sec->AddrExpr = [=] { return I->second; };
1326
1.78k
  }
1327
189
1328
189
  // This is a bit of a hack. A value of 0 means undef, so we set it
1329
189
  // to 1 t make __ehdr_start defined. The section number is not
1330
189
  // particularly relevant.
1331
189
  Out::ElfHeader->SectionIndex = 1;
1332
189
1333
189
  unsigned I = 1;
1334
1.78k
  for (OutputSection *Sec : OutputSections) {
1335
1.78k
    Sec->SectionIndex = I++;
1336
1.78k
    Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1337
1.78k
  }
1338
189
1339
189
  // Binary and relocatable output does not have PHDRS.
1340
189
  // The headers have to be created before finalize as that can influence the
1341
189
  // image base and the dynamic section on mips includes the image base.
1342
189
  if (
!Config->Relocatable && 189
!Config->OFormatBinary183
) {
1343
183
    Phdrs = Script->hasPhdrsCommands() ? 
Script->createPhdrs()5
:
createPhdrs()178
;
1344
183
    addPtArmExid(Phdrs);
1345
183
    Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1346
183
  }
1347
189
1348
189
  // Some symbols are defined in term of program headers. Now that we
1349
189
  // have the headers, we can find out which sections they point to.
1350
189
  setReservedSymbolSections();
1351
189
1352
189
  // Dynamic section must be the last one in this list and dynamic
1353
189
  // symbol table section (DynSymTab) must be the first one.
1354
189
  applySynthetic({InX::DynSymTab,    InX::Bss,
1355
189
                  InX::BssRelRo,     InX::GnuHashTab,
1356
189
                  InX::HashTab,      InX::SymTab,
1357
189
                  InX::ShStrTab,     InX::StrTab,
1358
189
                  In<ELFT>::VerDef,  InX::DynStrTab,
1359
189
                  InX::Got,          InX::MipsGot,
1360
189
                  InX::IgotPlt,      InX::GotPlt,
1361
189
                  In<ELFT>::RelaDyn, In<ELFT>::RelaIplt,
1362
189
                  In<ELFT>::RelaPlt, InX::Plt,
1363
189
                  InX::Iplt,         In<ELFT>::EhFrameHdr,
1364
189
                  In<ELFT>::VerSym,  In<ELFT>::VerNeed,
1365
189
                  InX::Dynamic},
1366
189
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1367
189
1368
189
  if (
!Script->Opt.HasSections && 189
!Config->Relocatable170
)
1369
164
    fixSectionAlignments();
1370
189
1371
189
  // Some architectures use small displacements for jump instructions.
1372
189
  // It is linker's responsibility to create thunks containing long
1373
189
  // jump instructions if jump targets are too far. Create thunks.
1374
189
  if (
Target->NeedsThunks189
) {
1375
94
    // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented,
1376
94
    // these
1377
94
    // do not require address information. To support range extension Thunks
1378
94
    // we need to assign addresses so that we can tell if jump instructions
1379
94
    // are out of range. This will need to turn into a loop that converges
1380
94
    // when no more Thunks are added
1381
94
    ThunkCreator TC;
1382
94
    Script->assignAddresses();
1383
94
    if (
TC.createThunks(OutputSections)94
) {
1384
9
      applySynthetic({InX::MipsGot},
1385
9
                     [](SyntheticSection *SS) { SS->updateAllocSize(); });
1386
9
      if (TC.createThunks(OutputSections))
1387
0
        fatal("All non-range thunks should be created in first call");
1388
189
    }
1389
94
  }
1390
189
1391
189
  // Fill other section headers. The dynamic table is finalized
1392
189
  // at the end because some tags like RELSZ depend on result
1393
189
  // of finalizing other sections.
1394
189
  for (OutputSection *Sec : OutputSections)
1395
1.78k
    Sec->finalize<ELFT>();
1396
193
1397
193
  // createThunks may have added local symbols to the static symbol table
1398
193
  applySynthetic({InX::SymTab, InX::ShStrTab, InX::StrTab},
1399
193
                 [](SyntheticSection *SS) { SS->postThunkContents(); });
1400
193
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::finalizeSections()
Line
Count
Source
1243
95
template <class ELFT> void Writer<ELFT>::finalizeSections() {
1244
95
  Out::DebugInfo = findSection(".debug_info");
1245
95
  Out::PreinitArray = findSection(".preinit_array");
1246
95
  Out::InitArray = findSection(".init_array");
1247
95
  Out::FiniArray = findSection(".fini_array");
1248
95
1249
95
  // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1250
95
  // symbols for sections, so that the runtime can get the start and end
1251
95
  // addresses of each section by section name. Add such symbols.
1252
95
  if (
!Config->Relocatable95
) {
1253
87
    addStartEndSymbols();
1254
87
    for (BaseCommand *Base : Script->Opt.Commands)
1255
1.79k
      
if (auto *1.79k
Sec1.79k
= dyn_cast<OutputSection>(Base))
1256
1.71k
        addStartStopSymbols(Sec);
1257
87
  }
1258
95
1259
95
  // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1260
95
  // It should be okay as no one seems to care about the type.
1261
95
  // Even the author of gold doesn't remember why gold behaves that way.
1262
95
  // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1263
95
  if (InX::DynSymTab)
1264
54
    addRegular<ELFT>("_DYNAMIC", InX::Dynamic, 0);
1265
95
1266
95
  // Define __rel[a]_iplt_{start,end} symbols if needed.
1267
95
  addRelIpltSymbols();
1268
95
1269
95
  // This responsible for splitting up .eh_frame section into
1270
95
  // pieces. The relocation scan uses those pieces, so this has to be
1271
95
  // earlier.
1272
95
  applySynthetic({In<ELFT>::EhFrame},
1273
95
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1274
95
1275
95
  for (Symbol *S : Symtab->getSymbols())
1276
457
    S->body()->IsPreemptible |= computeIsPreemptible(*S->body());
1277
95
1278
95
  // Scan relocations. This must be done after every symbol is declared so that
1279
95
  // we can correctly decide if a dynamic relocation is needed.
1280
95
  if (!Config->Relocatable)
1281
87
    forEachRelSec(scanRelocations<ELFT>);
1282
95
1283
95
  if (
InX::Plt && 95
!InX::Plt->empty()95
)
1284
6
    InX::Plt->addSymbols();
1285
95
  if (
InX::Iplt && 95
!InX::Iplt->empty()95
)
1286
0
    InX::Iplt->addSymbols();
1287
95
1288
95
  // Now that we have defined all possible global symbols including linker-
1289
95
  // synthesized ones. Visit all symbols to give the finishing touches.
1290
457
  for (Symbol *S : Symtab->getSymbols()) {
1291
457
    SymbolBody *Body = S->body();
1292
457
1293
457
    if (!includeInSymtab(*Body))
1294
41
      continue;
1295
416
    
if (416
InX::SymTab416
)
1296
416
      InX::SymTab->addSymbol(Body);
1297
416
1298
416
    if (
InX::DynSymTab && 416
S->includeInDynsym()255
) {
1299
123
      InX::DynSymTab->addSymbol(Body);
1300
123
      if (auto *SS = dyn_cast<SharedSymbol>(Body))
1301
20
        
if (20
cast<SharedFile<ELFT>>(S->File)->isNeeded()20
)
1302
20
          In<ELFT>::VerNeed->addSymbol(SS);
1303
123
    }
1304
457
  }
1305
95
1306
95
  // Do not proceed if there was an undefined symbol.
1307
95
  if (ErrorCount)
1308
2
    return;
1309
93
1310
93
  addPredefinedSections();
1311
93
  removeUnusedSyntheticSections();
1312
93
1313
93
  sortSections();
1314
93
1315
93
  // Now that we have the final list, create a list of all the
1316
93
  // OutputSections for convenience.
1317
93
  for (BaseCommand *Base : Script->Opt.Commands)
1318
1.27k
    
if (auto *1.27k
Sec1.27k
= dyn_cast<OutputSection>(Base))
1319
1.19k
      OutputSections.push_back(Sec);
1320
93
1321
93
  // Prefer command line supplied address over other constraints.
1322
1.19k
  for (OutputSection *Sec : OutputSections) {
1323
1.19k
    auto I = Config->SectionStartMap.find(Sec->Name);
1324
1.19k
    if (I != Config->SectionStartMap.end())
1325
0
      Sec->AddrExpr = [=] { return I->second; };
1326
1.19k
  }
1327
93
1328
93
  // This is a bit of a hack. A value of 0 means undef, so we set it
1329
93
  // to 1 t make __ehdr_start defined. The section number is not
1330
93
  // particularly relevant.
1331
93
  Out::ElfHeader->SectionIndex = 1;
1332
93
1333
93
  unsigned I = 1;
1334
1.19k
  for (OutputSection *Sec : OutputSections) {
1335
1.19k
    Sec->SectionIndex = I++;
1336
1.19k
    Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1337
1.19k
  }
1338
93
1339
93
  // Binary and relocatable output does not have PHDRS.
1340
93
  // The headers have to be created before finalize as that can influence the
1341
93
  // image base and the dynamic section on mips includes the image base.
1342
93
  if (
!Config->Relocatable && 93
!Config->OFormatBinary86
) {
1343
86
    Phdrs = Script->hasPhdrsCommands() ? 
Script->createPhdrs()0
:
createPhdrs()86
;
1344
86
    addPtArmExid(Phdrs);
1345
86
    Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1346
86
  }
1347
93
1348
93
  // Some symbols are defined in term of program headers. Now that we
1349
93
  // have the headers, we can find out which sections they point to.
1350
93
  setReservedSymbolSections();
1351
93
1352
93
  // Dynamic section must be the last one in this list and dynamic
1353
93
  // symbol table section (DynSymTab) must be the first one.
1354
93
  applySynthetic({InX::DynSymTab,    InX::Bss,
1355
93
                  InX::BssRelRo,     InX::GnuHashTab,
1356
93
                  InX::HashTab,      InX::SymTab,
1357
93
                  InX::ShStrTab,     InX::StrTab,
1358
93
                  In<ELFT>::VerDef,  InX::DynStrTab,
1359
93
                  InX::Got,          InX::MipsGot,
1360
93
                  InX::IgotPlt,      InX::GotPlt,
1361
93
                  In<ELFT>::RelaDyn, In<ELFT>::RelaIplt,
1362
93
                  In<ELFT>::RelaPlt, InX::Plt,
1363
93
                  InX::Iplt,         In<ELFT>::EhFrameHdr,
1364
93
                  In<ELFT>::VerSym,  In<ELFT>::VerNeed,
1365
93
                  InX::Dynamic},
1366
93
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1367
93
1368
93
  if (
!Script->Opt.HasSections && 93
!Config->Relocatable86
)
1369
79
    fixSectionAlignments();
1370
93
1371
93
  // Some architectures use small displacements for jump instructions.
1372
93
  // It is linker's responsibility to create thunks containing long
1373
93
  // jump instructions if jump targets are too far. Create thunks.
1374
93
  if (
Target->NeedsThunks93
) {
1375
91
    // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented,
1376
91
    // these
1377
91
    // do not require address information. To support range extension Thunks
1378
91
    // we need to assign addresses so that we can tell if jump instructions
1379
91
    // are out of range. This will need to turn into a loop that converges
1380
91
    // when no more Thunks are added
1381
91
    ThunkCreator TC;
1382
91
    Script->assignAddresses();
1383
91
    if (
TC.createThunks(OutputSections)91
) {
1384
7
      applySynthetic({InX::MipsGot},
1385
7
                     [](SyntheticSection *SS) { SS->updateAllocSize(); });
1386
7
      if (TC.createThunks(OutputSections))
1387
0
        fatal("All non-range thunks should be created in first call");
1388
93
    }
1389
91
  }
1390
93
1391
93
  // Fill other section headers. The dynamic table is finalized
1392
93
  // at the end because some tags like RELSZ depend on result
1393
93
  // of finalizing other sections.
1394
93
  for (OutputSection *Sec : OutputSections)
1395
1.19k
    Sec->finalize<ELFT>();
1396
95
1397
95
  // createThunks may have added local symbols to the static symbol table
1398
95
  applySynthetic({InX::SymTab, InX::ShStrTab, InX::StrTab},
1399
95
                 [](SyntheticSection *SS) { SS->postThunkContents(); });
1400
95
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::finalizeSections()
Line
Count
Source
1243
1.26k
template <class ELFT> void Writer<ELFT>::finalizeSections() {
1244
1.26k
  Out::DebugInfo = findSection(".debug_info");
1245
1.26k
  Out::PreinitArray = findSection(".preinit_array");
1246
1.26k
  Out::InitArray = findSection(".init_array");
1247
1.26k
  Out::FiniArray = findSection(".fini_array");
1248
1.26k
1249
1.26k
  // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1250
1.26k
  // symbols for sections, so that the runtime can get the start and end
1251
1.26k
  // addresses of each section by section name. Add such symbols.
1252
1.26k
  if (
!Config->Relocatable1.26k
) {
1253
1.22k
    addStartEndSymbols();
1254
1.22k
    for (BaseCommand *Base : Script->Opt.Commands)
1255
216k
      
if (auto *216k
Sec216k
= dyn_cast<OutputSection>(Base))
1256
215k
        addStartStopSymbols(Sec);
1257
1.22k
  }
1258
1.26k
1259
1.26k
  // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1260
1.26k
  // It should be okay as no one seems to care about the type.
1261
1.26k
  // Even the author of gold doesn't remember why gold behaves that way.
1262
1.26k
  // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1263
1.26k
  if (InX::DynSymTab)
1264
618
    addRegular<ELFT>("_DYNAMIC", InX::Dynamic, 0);
1265
1.26k
1266
1.26k
  // Define __rel[a]_iplt_{start,end} symbols if needed.
1267
1.26k
  addRelIpltSymbols();
1268
1.26k
1269
1.26k
  // This responsible for splitting up .eh_frame section into
1270
1.26k
  // pieces. The relocation scan uses those pieces, so this has to be
1271
1.26k
  // earlier.
1272
1.26k
  applySynthetic({In<ELFT>::EhFrame},
1273
1.26k
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1274
1.26k
1275
1.26k
  for (Symbol *S : Symtab->getSymbols())
1276
3.37k
    S->body()->IsPreemptible |= computeIsPreemptible(*S->body());
1277
1.26k
1278
1.26k
  // Scan relocations. This must be done after every symbol is declared so that
1279
1.26k
  // we can correctly decide if a dynamic relocation is needed.
1280
1.26k
  if (!Config->Relocatable)
1281
1.22k
    forEachRelSec(scanRelocations<ELFT>);
1282
1.26k
1283
1.26k
  if (
InX::Plt && 1.26k
!InX::Plt->empty()1.26k
)
1284
100
    InX::Plt->addSymbols();
1285
1.26k
  if (
InX::Iplt && 1.26k
!InX::Iplt->empty()1.26k
)
1286
9
    InX::Iplt->addSymbols();
1287
1.26k
1288
1.26k
  // Now that we have defined all possible global symbols including linker-
1289
1.26k
  // synthesized ones. Visit all symbols to give the finishing touches.
1290
3.37k
  for (Symbol *S : Symtab->getSymbols()) {
1291
3.37k
    SymbolBody *Body = S->body();
1292
3.37k
1293
3.37k
    if (!includeInSymtab(*Body))
1294
275
      continue;
1295
3.10k
    
if (3.10k
InX::SymTab3.10k
)
1296
3.10k
      InX::SymTab->addSymbol(Body);
1297
3.10k
1298
3.10k
    if (
InX::DynSymTab && 3.10k
S->includeInDynsym()1.85k
) {
1299
935
      InX::DynSymTab->addSymbol(Body);
1300
935
      if (auto *SS = dyn_cast<SharedSymbol>(Body))
1301
156
        
if (156
cast<SharedFile<ELFT>>(S->File)->isNeeded()156
)
1302
155
          In<ELFT>::VerNeed->addSymbol(SS);
1303
935
    }
1304
3.37k
  }
1305
1.26k
1306
1.26k
  // Do not proceed if there was an undefined symbol.
1307
1.26k
  if (ErrorCount)
1308
59
    return;
1309
1.20k
1310
1.20k
  addPredefinedSections();
1311
1.20k
  removeUnusedSyntheticSections();
1312
1.20k
1313
1.20k
  sortSections();
1314
1.20k
1315
1.20k
  // Now that we have the final list, create a list of all the
1316
1.20k
  // OutputSections for convenience.
1317
1.20k
  for (BaseCommand *Base : Script->Opt.Commands)
1318
206k
    
if (auto *206k
Sec206k
= dyn_cast<OutputSection>(Base))
1319
205k
      OutputSections.push_back(Sec);
1320
1.20k
1321
1.20k
  // Prefer command line supplied address over other constraints.
1322
205k
  for (OutputSection *Sec : OutputSections) {
1323
205k
    auto I = Config->SectionStartMap.find(Sec->Name);
1324
205k
    if (I != Config->SectionStartMap.end())
1325
34
      Sec->AddrExpr = [=] { return I->second; };
1326
205k
  }
1327
1.20k
1328
1.20k
  // This is a bit of a hack. A value of 0 means undef, so we set it
1329
1.20k
  // to 1 t make __ehdr_start defined. The section number is not
1330
1.20k
  // particularly relevant.
1331
1.20k
  Out::ElfHeader->SectionIndex = 1;
1332
1.20k
1333
1.20k
  unsigned I = 1;
1334
205k
  for (OutputSection *Sec : OutputSections) {
1335
205k
    Sec->SectionIndex = I++;
1336
205k
    Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1337
205k
  }
1338
1.20k
1339
1.20k
  // Binary and relocatable output does not have PHDRS.
1340
1.20k
  // The headers have to be created before finalize as that can influence the
1341
1.20k
  // image base and the dynamic section on mips includes the image base.
1342
1.20k
  if (
!Config->Relocatable && 1.20k
!Config->OFormatBinary1.16k
) {
1343
1.15k
    Phdrs = Script->hasPhdrsCommands() ? 
Script->createPhdrs()18
:
createPhdrs()1.13k
;
1344
1.15k
    addPtArmExid(Phdrs);
1345
1.15k
    Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1346
1.15k
  }
1347
1.20k
1348
1.20k
  // Some symbols are defined in term of program headers. Now that we
1349
1.20k
  // have the headers, we can find out which sections they point to.
1350
1.20k
  setReservedSymbolSections();
1351
1.20k
1352
1.20k
  // Dynamic section must be the last one in this list and dynamic
1353
1.20k
  // symbol table section (DynSymTab) must be the first one.
1354
1.20k
  applySynthetic({InX::DynSymTab,    InX::Bss,
1355
1.20k
                  InX::BssRelRo,     InX::GnuHashTab,
1356
1.20k
                  InX::HashTab,      InX::SymTab,
1357
1.20k
                  InX::ShStrTab,     InX::StrTab,
1358
1.20k
                  In<ELFT>::VerDef,  InX::DynStrTab,
1359
1.20k
                  InX::Got,          InX::MipsGot,
1360
1.20k
                  InX::IgotPlt,      InX::GotPlt,
1361
1.20k
                  In<ELFT>::RelaDyn, In<ELFT>::RelaIplt,
1362
1.20k
                  In<ELFT>::RelaPlt, InX::Plt,
1363
1.20k
                  InX::Iplt,         In<ELFT>::EhFrameHdr,
1364
1.20k
                  In<ELFT>::VerSym,  In<ELFT>::VerNeed,
1365
1.20k
                  InX::Dynamic},
1366
1.20k
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1367
1.20k
1368
1.20k
  if (
!Script->Opt.HasSections && 1.20k
!Config->Relocatable948
)
1369
904
    fixSectionAlignments();
1370
1.20k
1371
1.20k
  // Some architectures use small displacements for jump instructions.
1372
1.20k
  // It is linker's responsibility to create thunks containing long
1373
1.20k
  // jump instructions if jump targets are too far. Create thunks.
1374
1.20k
  if (
Target->NeedsThunks1.20k
) {
1375
2
    // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented,
1376
2
    // these
1377
2
    // do not require address information. To support range extension Thunks
1378
2
    // we need to assign addresses so that we can tell if jump instructions
1379
2
    // are out of range. This will need to turn into a loop that converges
1380
2
    // when no more Thunks are added
1381
2
    ThunkCreator TC;
1382
2
    Script->assignAddresses();
1383
2
    if (
TC.createThunks(OutputSections)2
) {
1384
0
      applySynthetic({InX::MipsGot},
1385
0
                     [](SyntheticSection *SS) { SS->updateAllocSize(); });
1386
0
      if (TC.createThunks(OutputSections))
1387
0
        fatal("All non-range thunks should be created in first call");
1388
1.20k
    }
1389
2
  }
1390
1.20k
1391
1.20k
  // Fill other section headers. The dynamic table is finalized
1392
1.20k
  // at the end because some tags like RELSZ depend on result
1393
1.20k
  // of finalizing other sections.
1394
1.20k
  for (OutputSection *Sec : OutputSections)
1395
205k
    Sec->finalize<ELFT>();
1396
1.26k
1397
1.26k
  // createThunks may have added local symbols to the static symbol table
1398
1.26k
  applySynthetic({InX::SymTab, InX::ShStrTab, InX::StrTab},
1399
1.26k
                 [](SyntheticSection *SS) { SS->postThunkContents(); });
1400
1.26k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::finalizeSections()
Line
Count
Source
1243
44
template <class ELFT> void Writer<ELFT>::finalizeSections() {
1244
44
  Out::DebugInfo = findSection(".debug_info");
1245
44
  Out::PreinitArray = findSection(".preinit_array");
1246
44
  Out::InitArray = findSection(".init_array");
1247
44
  Out::FiniArray = findSection(".fini_array");
1248
44
1249
44
  // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1250
44
  // symbols for sections, so that the runtime can get the start and end
1251
44
  // addresses of each section by section name. Add such symbols.
1252
44
  if (
!Config->Relocatable44
) {
1253
43
    addStartEndSymbols();
1254
43
    for (BaseCommand *Base : Script->Opt.Commands)
1255
858
      
if (auto *858
Sec858
= dyn_cast<OutputSection>(Base))
1256
816
        addStartStopSymbols(Sec);
1257
43
  }
1258
44
1259
44
  // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1260
44
  // It should be okay as no one seems to care about the type.
1261
44
  // Even the author of gold doesn't remember why gold behaves that way.
1262
44
  // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1263
44
  if (InX::DynSymTab)
1264
25
    addRegular<ELFT>("_DYNAMIC", InX::Dynamic, 0);
1265
44
1266
44
  // Define __rel[a]_iplt_{start,end} symbols if needed.
1267
44
  addRelIpltSymbols();
1268
44
1269
44
  // This responsible for splitting up .eh_frame section into
1270
44
  // pieces. The relocation scan uses those pieces, so this has to be
1271
44
  // earlier.
1272
44
  applySynthetic({In<ELFT>::EhFrame},
1273
44
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1274
44
1275
44
  for (Symbol *S : Symtab->getSymbols())
1276
180
    S->body()->IsPreemptible |= computeIsPreemptible(*S->body());
1277
44
1278
44
  // Scan relocations. This must be done after every symbol is declared so that
1279
44
  // we can correctly decide if a dynamic relocation is needed.
1280
44
  if (!Config->Relocatable)
1281
43
    forEachRelSec(scanRelocations<ELFT>);
1282
44
1283
44
  if (
InX::Plt && 44
!InX::Plt->empty()44
)
1284
2
    InX::Plt->addSymbols();
1285
44
  if (
InX::Iplt && 44
!InX::Iplt->empty()44
)
1286
0
    InX::Iplt->addSymbols();
1287
44
1288
44
  // Now that we have defined all possible global symbols including linker-
1289
44
  // synthesized ones. Visit all symbols to give the finishing touches.
1290
180
  for (Symbol *S : Symtab->getSymbols()) {
1291
180
    SymbolBody *Body = S->body();
1292
180
1293
180
    if (!includeInSymtab(*Body))
1294
9
      continue;
1295
171
    
if (171
InX::SymTab171
)
1296
171
      InX::SymTab->addSymbol(Body);
1297
171
1298
171
    if (
InX::DynSymTab && 171
S->includeInDynsym()106
) {
1299
47
      InX::DynSymTab->addSymbol(Body);
1300
47
      if (auto *SS = dyn_cast<SharedSymbol>(Body))
1301
8
        
if (8
cast<SharedFile<ELFT>>(S->File)->isNeeded()8
)
1302
8
          In<ELFT>::VerNeed->addSymbol(SS);
1303
47
    }
1304
180
  }
1305
44
1306
44
  // Do not proceed if there was an undefined symbol.
1307
44
  if (ErrorCount)
1308
0
    return;
1309
44
1310
44
  addPredefinedSections();
1311
44
  removeUnusedSyntheticSections();
1312
44
1313
44
  sortSections();
1314
44
1315
44
  // Now that we have the final list, create a list of all the
1316
44
  // OutputSections for convenience.
1317
44
  for (BaseCommand *Base : Script->Opt.Commands)
1318
572
    
if (auto *572
Sec572
= dyn_cast<OutputSection>(Base))
1319
529
      OutputSections.push_back(Sec);
1320
44
1321
44
  // Prefer command line supplied address over other constraints.
1322
529
  for (OutputSection *Sec : OutputSections) {
1323
529
    auto I = Config->SectionStartMap.find(Sec->Name);
1324
529
    if (I != Config->SectionStartMap.end())
1325
1
      Sec->AddrExpr = [=] { return I->second; };
1326
529
  }
1327
44
1328
44
  // This is a bit of a hack. A value of 0 means undef, so we set it
1329
44
  // to 1 t make __ehdr_start defined. The section number is not
1330
44
  // particularly relevant.
1331
44
  Out::ElfHeader->SectionIndex = 1;
1332
44
1333
44
  unsigned I = 1;
1334
529
  for (OutputSection *Sec : OutputSections) {
1335
529
    Sec->SectionIndex = I++;
1336
529
    Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1337
529
  }
1338
44
1339
44
  // Binary and relocatable output does not have PHDRS.
1340
44
  // The headers have to be created before finalize as that can influence the
1341
44
  // image base and the dynamic section on mips includes the image base.
1342
44
  if (
!Config->Relocatable && 44
!Config->OFormatBinary43
) {
1343
43
    Phdrs = Script->hasPhdrsCommands() ? 
Script->createPhdrs()0
:
createPhdrs()43
;
1344
43
    addPtArmExid(Phdrs);
1345
43
    Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1346
43
  }
1347
44
1348
44
  // Some symbols are defined in term of program headers. Now that we
1349
44
  // have the headers, we can find out which sections they point to.
1350
44
  setReservedSymbolSections();
1351
44
1352
44
  // Dynamic section must be the last one in this list and dynamic
1353
44
  // symbol table section (DynSymTab) must be the first one.
1354
44
  applySynthetic({InX::DynSymTab,    InX::Bss,
1355
44
                  InX::BssRelRo,     InX::GnuHashTab,
1356
44
                  InX::HashTab,      InX::SymTab,
1357
44
                  InX::ShStrTab,     InX::StrTab,
1358
44
                  In<ELFT>::VerDef,  InX::DynStrTab,
1359
44
                  InX::Got,          InX::MipsGot,
1360
44
                  InX::IgotPlt,      InX::GotPlt,
1361
44
                  In<ELFT>::RelaDyn, In<ELFT>::RelaIplt,
1362
44
                  In<ELFT>::RelaPlt, InX::Plt,
1363
44
                  InX::Iplt,         In<ELFT>::EhFrameHdr,
1364
44
                  In<ELFT>::VerSym,  In<ELFT>::VerNeed,
1365
44
                  InX::Dynamic},
1366
44
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1367
44
1368
44
  if (
!Script->Opt.HasSections && 44
!Config->Relocatable42
)
1369
41
    fixSectionAlignments();
1370
44
1371
44
  // Some architectures use small displacements for jump instructions.
1372
44
  // It is linker's responsibility to create thunks containing long
1373
44
  // jump instructions if jump targets are too far. Create thunks.
1374
44
  if (
Target->NeedsThunks44
) {
1375
28
    // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented,
1376
28
    // these
1377
28
    // do not require address information. To support range extension Thunks
1378
28
    // we need to assign addresses so that we can tell if jump instructions
1379
28
    // are out of range. This will need to turn into a loop that converges
1380
28
    // when no more Thunks are added
1381
28
    ThunkCreator TC;
1382
28
    Script->assignAddresses();
1383
28
    if (
TC.createThunks(OutputSections)28
) {
1384
0
      applySynthetic({InX::MipsGot},
1385
0
                     [](SyntheticSection *SS) { SS->updateAllocSize(); });
1386
0
      if (TC.createThunks(OutputSections))
1387
0
        fatal("All non-range thunks should be created in first call");
1388
44
    }
1389
28
  }
1390
44
1391
44
  // Fill other section headers. The dynamic table is finalized
1392
44
  // at the end because some tags like RELSZ depend on result
1393
</