Coverage Report

Created: 2017-09-21 03:39

/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.81k
      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.58k
static bool needsInterpSection() {
119
199
  return !SharedFiles.empty() && !Config->DynamicLinker.empty() &&
120
5
         !Script->ignoreInterpSection();
121
1.58k
}
122
123
1.58k
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.25k
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
191
template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
124
125
1.52k
template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
126
7.85k
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
127
7.85k
    if (P->p_type != PT_LOAD)
128
4.25k
      return false;
129
3.59k
    
if (3.59k
!P->FirstSec3.59k
)
130
14
      return true;
131
3.58k
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
132
3.58k
    return Size == 0;
133
3.58k
  });
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.05k
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
127
1.05k
    if (P->p_type != PT_LOAD)
128
588
      return false;
129
467
    
if (467
!P->FirstSec467
)
130
3
      return true;
131
464
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
132
464
    return Size == 0;
133
464
  });
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.06k
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
127
6.06k
    if (P->p_type != PT_LOAD)
128
3.30k
      return false;
129
2.75k
    
if (2.75k
!P->FirstSec2.75k
)
130
11
      return true;
131
2.74k
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
132
2.74k
    return Size == 0;
133
2.74k
  });
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
187
template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
126
187
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
127
187
    if (P->p_type != PT_LOAD)
128
187
      return false;
129
187
    if (!P->FirstSec)
130
187
      return true;
131
187
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
132
187
    return Size == 0;
133
187
  });
134
187
}
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.19k
template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
126
1.19k
  llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
127
1.19k
    if (P->p_type != PT_LOAD)
128
1.19k
      return false;
129
1.19k
    if (!P->FirstSec)
130
1.19k
      return true;
131
1.19k
    uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
132
1.19k
    return Size == 0;
133
1.19k
  });
134
1.19k
}
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.52k
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->Live92
)
140
227k
      continue;
141
92
142
92
    In<ELFT>::EhFrame->addSection(ES);
143
92
    S = nullptr;
144
92
  }
145
1.52k
146
1.52k
  std::vector<InputSectionBase *> &V = InputSections;
147
1.52k
  V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
148
1.52k
}
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)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
}
Writer.cpp:void combineEhFrameSections<llvm::object::ELFType<(llvm::support::endianness)1, true> >()
Line
Count
Source
136
1.21k
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->Live84
)
140
220k
      continue;
141
84
142
84
    In<ELFT>::EhFrame->addSection(ES);
143
84
    S = nullptr;
144
84
  }
145
1.21k
146
1.21k
  std::vector<InputSectionBase *> &V = InputSections;
147
1.21k
  V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
148
1.21k
}
Writer.cpp:void combineEhFrameSections<llvm::object::ELFType<(llvm::support::endianness)1, false> >()
Line
Count
Source
136
185
template <class ELFT> static void combineEhFrameSections() {
137
3.86k
  for (InputSectionBase *&S : InputSections) {
138
3.86k
    EhInputSection *ES = dyn_cast<EhInputSection>(S);
139
3.86k
    if (
!ES || 3.86k
!ES->Live4
)
140
3.85k
      continue;
141
4
142
4
    In<ELFT>::EhFrame->addSection(ES);
143
4
    S = nullptr;
144
4
  }
145
185
146
185
  std::vector<InputSectionBase *> &V = InputSections;
147
185
  V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
148
185
}
149
150
// The main function of the writer.
151
1.58k
template <class ELFT> void Writer<ELFT>::run() {
152
1.58k
  // Create linker-synthesized sections such as .got or .plt.
153
1.58k
  // Such sections are of type input section.
154
1.58k
  createSyntheticSections();
155
1.58k
156
1.58k
  if (!Config->Relocatable)
157
1.52k
    combineEhFrameSections<ELFT>();
158
1.58k
159
1.58k
  // We need to create some reserved symbols such as _end. Create them.
160
1.58k
  if (!Config->Relocatable)
161
1.52k
    addReservedSymbols();
162
1.58k
163
1.58k
  // Create output sections.
164
1.58k
  if (
Script->Opt.HasSections1.58k
) {
165
291
    // If linker script contains SECTIONS commands, let it create sections.
166
291
    Script->processCommands(Factory);
167
291
168
291
    // Linker scripts may have left some input sections unassigned.
169
291
    // Assign such sections using the default rule.
170
291
    Script->addOrphanSections(Factory);
171
1.58k
  } else {
172
1.29k
    // If linker script does not contain SECTIONS commands, create
173
1.29k
    // output sections by default rules. We still need to give the
174
1.29k
    // linker script a chance to run, because it might contain
175
1.29k
    // non-SECTIONS commands such as ASSERT.
176
1.29k
    Script->processCommands(Factory);
177
1.29k
    createSections();
178
1.29k
  }
179
1.58k
180
1.58k
  if (Config->Discard != DiscardPolicy::All)
181
1.58k
    copyLocalSymbols();
182
1.58k
183
1.58k
  if (Config->CopyRelocs)
184
72
    addSectionSymbols();
185
1.58k
186
1.58k
  // Now that we have a complete set of output sections. This function
187
1.58k
  // completes section contents. For example, we need to add strings
188
1.58k
  // to the string table, and add entries to .got and .plt.
189
1.58k
  // finalizeSections does that.
190
1.58k
  finalizeSections();
191
1.58k
  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)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)1, false> >::run()::'lambda'(lld::elf::OutputSection*)::operator()(lld::elf::OutputSection*) const
Line
Count
Source
198
1.76k
                  [](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.51k
    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.51k
  // Write the result down to a file.
224
1.51k
  openFile();
225
1.51k
  if (ErrorCount)
226
1
    return;
227
1.51k
228
1.51k
  
if (1.51k
!Config->OFormatBinary1.51k
) {
229
1.50k
    writeTrapInstr();
230
1.50k
    writeHeader();
231
1.50k
    writeSections();
232
1.51k
  } else {
233
5
    writeSectionsBinary();
234
5
  }
235
1.51k
236
1.51k
  // Backfill .note.gnu.build-id section content. This is done at last
237
1.51k
  // because the content is usually a hash value of the entire output file.
238
1.51k
  writeBuildId();
239
1.51k
  if (ErrorCount)
240
34
    return;
241
1.47k
242
1.47k
  // Handle -Map option.
243
1.47k
  writeMapFile<ELFT>();
244
1.47k
  if (ErrorCount)
245
0
    return;
246
1.47k
247
1.47k
  
if (auto 1.47k
EC1.47k
= Buffer->commit())
248
0
    error("failed to write to the output file: " + EC.message());
249
1.47k
250
1.47k
  // Flush the output streams and exit immediately. A full shutdown
251
1.47k
  // is a good test that we are keeping track of all allocated memory,
252
1.47k
  // but actually freeing it is a waste of time in a regular linker run.
253
1.47k
  if (Config->ExitEarly)
254
0
    exitLld(0);
255
1.47k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::run()
Line
Count
Source
151
191
template <class ELFT> void Writer<ELFT>::run() {
152
191
  // Create linker-synthesized sections such as .got or .plt.
153
191
  // Such sections are of type input section.
154
191
  createSyntheticSections();
155
191
156
191
  if (!Config->Relocatable)
157
185
    combineEhFrameSections<ELFT>();
158
191
159
191
  // We need to create some reserved symbols such as _end. Create them.
160
191
  if (!Config->Relocatable)
161
185
    addReservedSymbols();
162
191
163
191
  // Create output sections.
164
191
  if (
Script->Opt.HasSections191
) {
165
17
    // If linker script contains SECTIONS commands, let it create sections.
166
17
    Script->processCommands(Factory);
167
17
168
17
    // Linker scripts may have left some input sections unassigned.
169
17
    // Assign such sections using the default rule.
170
17
    Script->addOrphanSections(Factory);
171
191
  } 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
191
180
191
  if (Config->Discard != DiscardPolicy::All)
181
191
    copyLocalSymbols();
182
191
183
191
  if (Config->CopyRelocs)
184
7
    addSectionSymbols();
185
191
186
191
  // Now that we have a complete set of output sections. This function
187
191
  // completes section contents. For example, we need to add strings
188
191
  // to the string table, and add entries to .got and .plt.
189
191
  // finalizeSections does that.
190
191
  finalizeSections();
191
191
  if (ErrorCount)
192
4
    return;
193
187
194
187
  // If -compressed-debug-sections is specified, we need to compress
195
187
  // .debug_* sections. Do it right now because it changes the size of
196
187
  // output sections.
197
187
  parallelForEach(OutputSections,
198
187
                  [](OutputSection *Sec) { Sec->maybeCompress<ELFT>(); });
199
187
200
187
  Script->assignAddresses();
201
187
  Script->allocateHeaders(Phdrs);
202
187
203
187
  // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
204
187
  // 0 sized region. This has to be done late since only after assignAddresses
205
187
  // we know the size of the sections.
206
187
  removeEmptyPTLoad();
207
187
208
187
  if (!Config->OFormatBinary)
209
187
    assignFileOffsets();
210
187
  else
211
0
    assignFileOffsetsBinary();
212
187
213
187
  setPhdrs();
214
187
215
187
  if (
Config->Relocatable187
) {
216
6
    for (OutputSection *Sec : OutputSections)
217
50
      Sec->Addr = 0;
218
6
  }
219
187
220
187
  // It does not make sense try to open the file if we have error already.
221
187
  if (ErrorCount)
222
0
    return;
223
187
  // Write the result down to a file.
224
187
  openFile();
225
187
  if (ErrorCount)
226
1
    return;
227
186
228
186
  
if (186
!Config->OFormatBinary186
) {
229
186
    writeTrapInstr();
230
186
    writeHeader();
231
186
    writeSections();
232
186
  } else {
233
0
    writeSectionsBinary();
234
0
  }
235
186
236
186
  // Backfill .note.gnu.build-id section content. This is done at last
237
186
  // because the content is usually a hash value of the entire output file.
238
186
  writeBuildId();
239
186
  if (ErrorCount)
240
6
    return;
241
180
242
180
  // Handle -Map option.
243
180
  writeMapFile<ELFT>();
244
180
  if (ErrorCount)
245
0
    return;
246
180
247
180
  
if (auto 180
EC180
= Buffer->commit())
248
0
    error("failed to write to the output file: " + EC.message());
249
180
250
180
  // Flush the output streams and exit immediately. A full shutdown
251
180
  // is a good test that we are keeping track of all allocated memory,
252
180
  // but actually freeing it is a waste of time in a regular linker run.
253
180
  if (Config->ExitEarly)
254
0
    exitLld(0);
255
180
}
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, true> >::run()
Line
Count
Source
151
1.25k
template <class ELFT> void Writer<ELFT>::run() {
152
1.25k
  // Create linker-synthesized sections such as .got or .plt.
153
1.25k
  // Such sections are of type input section.
154
1.25k
  createSyntheticSections();
155
1.25k
156
1.25k
  if (!Config->Relocatable)
157
1.21k
    combineEhFrameSections<ELFT>();
158
1.25k
159
1.25k
  // We need to create some reserved symbols such as _end. Create them.
160
1.25k
  if (!Config->Relocatable)
161
1.21k
    addReservedSymbols();
162
1.25k
163
1.25k
  // Create output sections.
164
1.25k
  if (
Script->Opt.HasSections1.25k
) {
165
265
    // If linker script contains SECTIONS commands, let it create sections.
166
265
    Script->processCommands(Factory);
167
265
168
265
    // Linker scripts may have left some input sections unassigned.
169
265
    // Assign such sections using the default rule.
170
265
    Script->addOrphanSections(Factory);
171
1.25k
  } else {
172
994
    // If linker script does not contain SECTIONS commands, create
173
994
    // output sections by default rules. We still need to give the
174
994
    // linker script a chance to run, because it might contain
175
994
    // non-SECTIONS commands such as ASSERT.
176
994
    Script->processCommands(Factory);
177
994
    createSections();
178
994
  }
179
1.25k
180
1.25k
  if (Config->Discard != DiscardPolicy::All)
181
1.25k
    copyLocalSymbols();
182
1.25k
183
1.25k
  if (Config->CopyRelocs)
184
56
    addSectionSymbols();
185
1.25k
186
1.25k
  // Now that we have a complete set of output sections. This function
187
1.25k
  // completes section contents. For example, we need to add strings
188
1.25k
  // to the string table, and add entries to .got and .plt.
189
1.25k
  // finalizeSections does that.
190
1.25k
  finalizeSections();
191
1.25k
  if (ErrorCount)
192
63
    return;
193
1.19k
194
1.19k
  // If -compressed-debug-sections is specified, we need to compress
195
1.19k
  // .debug_* sections. Do it right now because it changes the size of
196
1.19k
  // output sections.
197
1.19k
  parallelForEach(OutputSections,
198
1.19k
                  [](OutputSection *Sec) { Sec->maybeCompress<ELFT>(); });
199
1.19k
200
1.19k
  Script->assignAddresses();
201
1.19k
  Script->allocateHeaders(Phdrs);
202
1.19k
203
1.19k
  // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
204
1.19k
  // 0 sized region. This has to be done late since only after assignAddresses
205
1.19k
  // we know the size of the sections.
206
1.19k
  removeEmptyPTLoad();
207
1.19k
208
1.19k
  if (!Config->OFormatBinary)
209
1.19k
    assignFileOffsets();
210
1.19k
  else
211
5
    assignFileOffsetsBinary();
212
1.19k
213
1.19k
  setPhdrs();
214
1.19k
215
1.19k
  if (
Config->Relocatable1.19k
) {
216
45
    for (OutputSection *Sec : OutputSections)
217
271
      Sec->Addr = 0;
218
45
  }
219
1.19k
220
1.19k
  // It does not make sense try to open the file if we have error already.
221
1.19k
  if (ErrorCount)
222
8
    return;
223
1.18k
  // Write the result down to a file.
224
1.18k
  openFile();
225
1.18k
  if (ErrorCount)
226
0
    return;
227
1.18k
228
1.18k
  
if (1.18k
!Config->OFormatBinary1.18k
) {
229
1.18k
    writeTrapInstr();
230
1.18k
    writeHeader();
231
1.18k
    writeSections();
232
1.18k
  } else {
233
5
    writeSectionsBinary();
234
5
  }
235
1.18k
236
1.18k
  // Backfill .note.gnu.build-id section content. This is done at last
237
1.18k
  // because the content is usually a hash value of the entire output file.
238
1.18k
  writeBuildId();
239
1.18k
  if (ErrorCount)
240
23
    return;
241
1.16k
242
1.16k
  // Handle -Map option.
243
1.16k
  writeMapFile<ELFT>();
244
1.16k
  if (ErrorCount)
245
0
    return;
246
1.16k
247
1.16k
  
if (auto 1.16k
EC1.16k
= Buffer->commit())
248
0
    error("failed to write to the output file: " + EC.message());
249
1.16k
250
1.16k
  // Flush the output streams and exit immediately. A full shutdown
251
1.16k
  // is a good test that we are keeping track of all allocated memory,
252
1.16k
  // but actually freeing it is a waste of time in a regular linker run.
253
1.16k
  if (Config->ExitEarly)
254
0
    exitLld(0);
255
1.16k
}
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
}
256
257
// Initialize Out members.
258
1.58k
template <class ELFT> void Writer<ELFT>::createSyntheticSections() {
259
1.58k
  // Initialize all pointers with NULL. This is needed because
260
1.58k
  // you can call lld::elf::main more than once as a library.
261
1.58k
  memset(&Out::First, 0, sizeof(Out));
262
1.58k
263
26.6k
  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, false> >::createSyntheticSections()::'lambda'(lld::elf::InputSectionBase*)::operator()(lld::elf::InputSectionBase*) const
Line
Count
Source
263
3.25k
  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.7k
  auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
264
1.58k
265
1.58k
  InX::DynStrTab = make<StringTableSection>(".dynstr", true);
266
1.58k
  InX::Dynamic = make<DynamicSection<ELFT>>();
267
1.58k
  In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>(
268
1.58k
      Config->IsRela ? 
".rela.dyn"1.30k
:
".rel.dyn"282
, Config->ZCombreloc);
269
1.58k
  InX::ShStrTab = make<StringTableSection>(".shstrtab", false);
270
1.58k
271
1.58k
  Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
272
1.58k
  Out::ElfHeader->Size = sizeof(Elf_Ehdr);
273
1.58k
  Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
274
1.58k
  Out::ProgramHeaders->updateAlignment(Config->Wordsize);
275
1.58k
276
1.58k
  if (
needsInterpSection()1.58k
) {
277
4
    InX::Interp = createInterpSection();
278
4
    Add(InX::Interp);
279
1.58k
  } else {
280
1.58k
    InX::Interp = nullptr;
281
1.58k
  }
282
1.58k
283
1.58k
  if (
Config->Strip != StripPolicy::All1.58k
) {
284
1.58k
    InX::StrTab = make<StringTableSection>(".strtab", false);
285
1.58k
    InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab);
286
1.58k
  }
287
1.58k
288
1.58k
  if (
Config->BuildId != BuildIdKind::None1.58k
) {
289
12
    InX::BuildId = make<BuildIdSection>();
290
12
    Add(InX::BuildId);
291
12
  }
292
1.58k
293
1.58k
  for (InputSection *S : createCommonSections())
294
84
    Add(S);
295
1.58k
296
1.58k
  InX::Bss = make<BssSection>(".bss");
297
1.58k
  Add(InX::Bss);
298
1.58k
  InX::BssRelRo = make<BssSection>(".bss.rel.ro");
299
1.58k
  Add(InX::BssRelRo);
300
1.58k
301
1.58k
  // Add MIPS-specific sections.
302
1.58k
  if (
Config->EMachine == EM_MIPS1.58k
) {
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.58k
315
1.58k
  if (
Config->HasDynSymTab1.58k
) {
316
802
    InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab);
317
802
    Add(InX::DynSymTab);
318
802
319
802
    In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
320
802
    Add(In<ELFT>::VerSym);
321
802
322
802
    if (
!Config->VersionDefinitions.empty()802
) {
323
36
      In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
324
36
      Add(In<ELFT>::VerDef);
325
36
    }
326
802
327
802
    In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
328
802
    Add(In<ELFT>::VerNeed);
329
802
330
802
    if (
Config->GnuHash802
) {
331
5
      InX::GnuHashTab = make<GnuHashTableSection>();
332
5
      Add(InX::GnuHashTab);
333
5
    }
334
802
335
802
    if (
Config->SysvHash802
) {
336
798
      In<ELFT>::HashTab = make<HashTableSection<ELFT>>();
337
798
      Add(In<ELFT>::HashTab);
338
798
    }
339
802
340
802
    Add(InX::Dynamic);
341
802
    Add(InX::DynStrTab);
342
802
    Add(In<ELFT>::RelaDyn);
343
802
  }
344
1.58k
345
1.58k
  // Add .got. MIPS' .got is so different from the other archs,
346
1.58k
  // it has its own class.
347
1.58k
  if (
Config->EMachine == EM_MIPS1.58k
) {
348
137
    InX::MipsGot = make<MipsGotSection>();
349
137
    Add(InX::MipsGot);
350
1.58k
  } else {
351
1.45k
    InX::Got = make<GotSection>();
352
1.45k
    Add(InX::Got);
353
1.45k
  }
354
1.58k
355
1.58k
  InX::GotPlt = make<GotPltSection>();
356
1.58k
  Add(InX::GotPlt);
357
1.58k
  InX::IgotPlt = make<IgotPltSection>();
358
1.58k
  Add(InX::IgotPlt);
359
1.58k
360
1.58k
  if (
Config->GdbIndex1.58k
) {
361
9
    InX::GdbIndex = createGdbIndex<ELFT>();
362
9
    Add(InX::GdbIndex);
363
9
  }
364
1.58k
365
1.58k
  // We always need to add rel[a].plt to output if it has entries.
366
1.58k
  // Even for static linking it can contain R_[*]_IRELATIVE relocations.
367
1.58k
  In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>(
368
1.58k
      Config->IsRela ? 
".rela.plt"1.30k
:
".rel.plt"282
, false /*Sort*/);
369
1.58k
  Add(In<ELFT>::RelaPlt);
370
1.58k
371
1.58k
  // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
372
1.58k
  // that the IRelative relocations are processed last by the dynamic loader
373
1.58k
  In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>(
374
1.58k
      (Config->EMachine == EM_ARM) ? 
".rel.dyn"80
:
In<ELFT>::RelaPlt->Name1.50k
,
375
1.58k
      false /*Sort*/);
376
1.58k
  Add(In<ELFT>::RelaIplt);
377
1.58k
378
1.58k
  InX::Plt = make<PltSection>(Target->PltHeaderSize);
379
1.58k
  Add(InX::Plt);
380
1.58k
  InX::Iplt = make<PltSection>(0);
381
1.58k
  Add(InX::Iplt);
382
1.58k
383
1.58k
  if (
!Config->Relocatable1.58k
) {
384
1.52k
    if (
Config->EhFrameHdr1.52k
) {
385
16
      In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>();
386
16
      Add(In<ELFT>::EhFrameHdr);
387
16
    }
388
1.52k
    In<ELFT>::EhFrame = make<EhFrameSection<ELFT>>();
389
1.52k
    Add(In<ELFT>::EhFrame);
390
1.52k
  }
391
1.58k
392
1.58k
  if (InX::SymTab)
393
1.58k
    Add(InX::SymTab);
394
1.58k
  Add(InX::ShStrTab);
395
1.58k
  if (InX::StrTab)
396
1.58k
    Add(InX::StrTab);
397
1.58k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::createSyntheticSections()
Line
Count
Source
258
1.25k
template <class ELFT> void Writer<ELFT>::createSyntheticSections() {
259
1.25k
  // Initialize all pointers with NULL. This is needed because
260
1.25k
  // you can call lld::elf::main more than once as a library.
261
1.25k
  memset(&Out::First, 0, sizeof(Out));
262
1.25k
263
1.25k
  auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
264
1.25k
265
1.25k
  InX::DynStrTab = make<StringTableSection>(".dynstr", true);
266
1.25k
  InX::Dynamic = make<DynamicSection<ELFT>>();
267
1.25k
  In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>(
268
1.25k
      Config->IsRela ? 
".rela.dyn"1.25k
:
".rel.dyn"0
, Config->ZCombreloc);
269
1.25k
  InX::ShStrTab = make<StringTableSection>(".shstrtab", false);
270
1.25k
271
1.25k
  Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
272
1.25k
  Out::ElfHeader->Size = sizeof(Elf_Ehdr);
273
1.25k
  Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
274
1.25k
  Out::ProgramHeaders->updateAlignment(Config->Wordsize);
275
1.25k
276
1.25k
  if (
needsInterpSection()1.25k
) {
277
2
    InX::Interp = createInterpSection();
278
2
    Add(InX::Interp);
279
1.25k
  } else {
280
1.25k
    InX::Interp = nullptr;
281
1.25k
  }
282
1.25k
283
1.25k
  if (
Config->Strip != StripPolicy::All1.25k
) {
284
1.25k
    InX::StrTab = make<StringTableSection>(".strtab", false);
285
1.25k
    InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab);
286
1.25k
  }
287
1.25k
288
1.25k
  if (
Config->BuildId != BuildIdKind::None1.25k
) {
289
12
    InX::BuildId = make<BuildIdSection>();
290
12
    Add(InX::BuildId);
291
12
  }
292
1.25k
293
1.25k
  for (InputSection *S : createCommonSections())
294
76
    Add(S);
295
1.25k
296
1.25k
  InX::Bss = make<BssSection>(".bss");
297
1.25k
  Add(InX::Bss);
298
1.25k
  InX::BssRelRo = make<BssSection>(".bss.rel.ro");
299
1.25k
  Add(InX::BssRelRo);
300
1.25k
301
1.25k
  // Add MIPS-specific sections.
302
1.25k
  if (
Config->EMachine == EM_MIPS1.25k
) {
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.25k
315
1.25k
  if (
Config->HasDynSymTab1.25k
) {
316
617
    InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab);
317
617
    Add(InX::DynSymTab);
318
617
319
617
    In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
320
617
    Add(In<ELFT>::VerSym);
321
617
322
617
    if (
!Config->VersionDefinitions.empty()617
) {
323
36
      In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
324
36
      Add(In<ELFT>::VerDef);
325
36
    }
326
617
327
617
    In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
328
617
    Add(In<ELFT>::VerNeed);
329
617
330
617
    if (
Config->GnuHash617
) {
331
2
      InX::GnuHashTab = make<GnuHashTableSection>();
332
2
      Add(InX::GnuHashTab);
333
2
    }
334
617
335
617
    if (
Config->SysvHash617
) {
336
615
      In<ELFT>::HashTab = make<HashTableSection<ELFT>>();
337
615
      Add(In<ELFT>::HashTab);
338
615
    }
339
617
340
617
    Add(InX::Dynamic);
341
617
    Add(InX::DynStrTab);
342
617
    Add(In<ELFT>::RelaDyn);
343
617
  }
344
1.25k
345
1.25k
  // Add .got. MIPS' .got is so different from the other archs,
346
1.25k
  // it has its own class.
347
1.25k
  if (
Config->EMachine == EM_MIPS1.25k
) {
348
2
    InX::MipsGot = make<MipsGotSection>();
349
2
    Add(InX::MipsGot);
350
1.25k
  } else {
351
1.25k
    InX::Got = make<GotSection>();
352
1.25k
    Add(InX::Got);
353
1.25k
  }
354
1.25k
355
1.25k
  InX::GotPlt = make<GotPltSection>();
356
1.25k
  Add(InX::GotPlt);
357
1.25k
  InX::IgotPlt = make<IgotPltSection>();
358
1.25k
  Add(InX::IgotPlt);
359
1.25k
360
1.25k
  if (
Config->GdbIndex1.25k
) {
361
8
    InX::GdbIndex = createGdbIndex<ELFT>();
362
8
    Add(InX::GdbIndex);
363
8
  }
364
1.25k
365
1.25k
  // We always need to add rel[a].plt to output if it has entries.
366
1.25k
  // Even for static linking it can contain R_[*]_IRELATIVE relocations.
367
1.25k
  In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>(
368
1.25k
      Config->IsRela ? 
".rela.plt"1.25k
:
".rel.plt"0
, false /*Sort*/);
369
1.25k
  Add(In<ELFT>::RelaPlt);
370
1.25k
371
1.25k
  // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
372
1.25k
  // that the IRelative relocations are processed last by the dynamic loader
373
1.25k
  In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>(
374
1.25k
      (Config->EMachine == EM_ARM) ? 
".rel.dyn"0
:
In<ELFT>::RelaPlt->Name1.25k
,
375
1.25k
      false /*Sort*/);
376
1.25k
  Add(In<ELFT>::RelaIplt);
377
1.25k
378
1.25k
  InX::Plt = make<PltSection>(Target->PltHeaderSize);
379
1.25k
  Add(InX::Plt);
380
1.25k
  InX::Iplt = make<PltSection>(0);
381
1.25k
  Add(InX::Iplt);
382
1.25k
383
1.25k
  if (
!Config->Relocatable1.25k
) {
384
1.21k
    if (
Config->EhFrameHdr1.21k
) {
385
12
      In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>();
386
12
      Add(In<ELFT>::EhFrameHdr);
387
12
    }
388
1.21k
    In<ELFT>::EhFrame = make<EhFrameSection<ELFT>>();
389
1.21k
    Add(In<ELFT>::EhFrame);
390
1.21k
  }
391
1.25k
392
1.25k
  if (InX::SymTab)
393
1.25k
    Add(InX::SymTab);
394
1.25k
  Add(InX::ShStrTab);
395
1.25k
  if (InX::StrTab)
396
1.25k
    Add(InX::StrTab);
397
1.25k
}
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
      In<ELFT>::HashTab = make<HashTableSection<ELFT>>();
337
25
      Add(In<ELFT>::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, false> >::createSyntheticSections()
Line
Count
Source
258
191
template <class ELFT> void Writer<ELFT>::createSyntheticSections() {
259
191
  // Initialize all pointers with NULL. This is needed because
260
191
  // you can call lld::elf::main more than once as a library.
261
191
  memset(&Out::First, 0, sizeof(Out));
262
191
263
191
  auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
264
191
265
191
  InX::DynStrTab = make<StringTableSection>(".dynstr", true);
266
191
  InX::Dynamic = make<DynamicSection<ELFT>>();
267
191
  In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>(
268
191
      Config->IsRela ? 
".rela.dyn"3
:
".rel.dyn"188
, Config->ZCombreloc);
269
191
  InX::ShStrTab = make<StringTableSection>(".shstrtab", false);
270
191
271
191
  Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
272
191
  Out::ElfHeader->Size = sizeof(Elf_Ehdr);
273
191
  Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
274
191
  Out::ProgramHeaders->updateAlignment(Config->Wordsize);
275
191
276
191
  if (
needsInterpSection()191
) {
277
1
    InX::Interp = createInterpSection();
278
1
    Add(InX::Interp);
279
191
  } else {
280
190
    InX::Interp = nullptr;
281
190
  }
282
191
283
191
  if (
Config->Strip != StripPolicy::All191
) {
284
191
    InX::StrTab = make<StringTableSection>(".strtab", false);
285
191
    InX::SymTab = make<SymbolTableSection<ELFT>>(*InX::StrTab);
286
191
  }
287
191
288
191
  if (
Config->BuildId != BuildIdKind::None191
) {
289
0
    InX::BuildId = make<BuildIdSection>();
290
0
    Add(InX::BuildId);
291
0
  }
292
191
293
191
  for (InputSection *S : createCommonSections())
294
6
    Add(S);
295
191
296
191
  InX::Bss = make<BssSection>(".bss");
297
191
  Add(InX::Bss);
298
191
  InX::BssRelRo = make<BssSection>(".bss.rel.ro");
299
191
  Add(InX::BssRelRo);
300
191
301
191
  // Add MIPS-specific sections.
302
191
  if (
Config->EMachine == EM_MIPS191
) {
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
191
315
191
  if (
Config->HasDynSymTab191
) {
316
106
    InX::DynSymTab = make<SymbolTableSection<ELFT>>(*InX::DynStrTab);
317
106
    Add(InX::DynSymTab);
318
106
319
106
    In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
320
106
    Add(In<ELFT>::VerSym);
321
106
322
106
    if (
!Config->VersionDefinitions.empty()106
) {
323
0
      In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
324
0
      Add(In<ELFT>::VerDef);
325
0
    }
326
106
327
106
    In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
328
106
    Add(In<ELFT>::VerNeed);
329
106
330
106
    if (
Config->GnuHash106
) {
331
2
      InX::GnuHashTab = make<GnuHashTableSection>();
332
2
      Add(InX::GnuHashTab);
333
2
    }
334
106
335
106
    if (
Config->SysvHash106
) {
336
104
      In<ELFT>::HashTab = make<HashTableSection<ELFT>>();
337
104
      Add(In<ELFT>::HashTab);
338
104
    }
339
106
340
106
    Add(InX::Dynamic);
341
106
    Add(InX::DynStrTab);
342
106
    Add(In<ELFT>::RelaDyn);
343
106
  }
344
191
345
191
  // Add .got. MIPS' .got is so different from the other archs,
346
191
  // it has its own class.
347
191
  if (
Config->EMachine == EM_MIPS191
) {
348
14
    InX::MipsGot = make<MipsGotSection>();
349
14
    Add(InX::MipsGot);
350
191
  } else {
351
177
    InX::Got = make<GotSection>();
352
177
    Add(InX::Got);
353
177
  }
354
191
355
191
  InX::GotPlt = make<GotPltSection>();
356
191
  Add(InX::GotPlt);
357
191
  InX::IgotPlt = make<IgotPltSection>();
358
191
  Add(InX::IgotPlt);
359
191
360
191
  if (
Config->GdbIndex191
) {
361
1
    InX::GdbIndex = createGdbIndex<ELFT>();
362
1
    Add(InX::GdbIndex);
363
1
  }
364
191
365
191
  // We always need to add rel[a].plt to output if it has entries.
366
191
  // Even for static linking it can contain R_[*]_IRELATIVE relocations.
367
191
  In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>(
368
191
      Config->IsRela ? 
".rela.plt"3
:
".rel.plt"188
, false /*Sort*/);
369
191
  Add(In<ELFT>::RelaPlt);
370
191
371
191
  // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
372
191
  // that the IRelative relocations are processed last by the dynamic loader
373
191
  In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>(
374
191
      (Config->EMachine == EM_ARM) ? 
".rel.dyn"80
:
In<ELFT>::RelaPlt->Name111
,
375
191
      false /*Sort*/);
376
191
  Add(In<ELFT>::RelaIplt);
377
191
378
191
  InX::Plt = make<PltSection>(Target->PltHeaderSize);
379
191
  Add(InX::Plt);
380
191
  InX::Iplt = make<PltSection>(0);
381
191
  Add(InX::Iplt);
382
191
383
191
  if (
!Config->Relocatable191
) {
384
185
    if (
Config->EhFrameHdr185
) {
385
0
      In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>();
386
0
      Add(In<ELFT>::EhFrameHdr);
387
0
    }
388
185
    In<ELFT>::EhFrame = make<EhFrameSection<ELFT>>();
389
185
    Add(In<ELFT>::EhFrame);
390
185
  }
391
191
392
191
  if (InX::SymTab)
393
191
    Add(InX::SymTab);
394
191
  Add(InX::ShStrTab);
395
191
  if (InX::StrTab)
396
191
    Add(InX::StrTab);
397
191
}
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
      In<ELFT>::HashTab = make<HashTableSection<ELFT>>();
337
54
      Add(In<ELFT>::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.20k
                               const SymbolBody &B) {
401
1.20k
  if (
B.isFile() || 1.20k
B.isSection()1.07k
)
402
541
    return false;
403
662
404
662
  // If sym references a section in a discarded group, don't keep it.
405
662
  
if (662
Sec == &InputSection::Discarded662
)
406
0
    return false;
407
662
408
662
  
if (662
Config->Discard == DiscardPolicy::None662
)
409
43
    return true;
410
619
411
619
  // In ELF assembly .L symbols are normally discarded by the assembler.
412
619
  // If the assembler fails to do so, the linker discards them if
413
619
  // * --discard-locals is used.
414
619
  // * The symbol is in a SHF_MERGE section, which is normally the reason for
415
619
  //   the assembler keeping the .L symbol.
416
619
  
if (619
!SymName.startswith(".L") && 619
!SymName.empty()611
)
417
609
    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.20k
}
424
425
5.92k
static bool includeInSymtab(const SymbolBody &B) {
426
5.92k
  if (
!B.isLocal() && 5.92k
!B.symbol()->IsUsedInRegularObj4.63k
)
427
333
    return false;
428
5.58k
429
5.58k
  
if (auto *5.58k
D5.58k
= dyn_cast<DefinedRegular>(&B)) {
430
5.00k
    // Always include absolute symbols.
431
5.00k
    SectionBase *Sec = D->Section;
432
5.00k
    if (!Sec)
433
543
      return true;
434
4.46k
    
if (auto *4.46k
IS4.46k
= dyn_cast<InputSectionBase>(Sec)) {
435
4.33k
      Sec = IS->Repl;
436
4.33k
      IS = cast<InputSectionBase>(Sec);
437
4.33k
      // Exclude symbols pointing to garbage-collected sections.
438
4.33k
      if (!IS->Live)
439
97
        return false;
440
4.36k
    }
441
4.36k
    
if (auto *4.36k
S4.36k
= dyn_cast<MergeInputSection>(Sec))
442
46
      
if (46
!S->getSectionPiece(D->Value)->Live46
)
443
6
        return false;
444
4.35k
    return true;
445
4.35k
  }
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.58k
template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
455
1.58k
  if (!InX::SymTab)
456
3
    return;
457
1.58k
  
for (InputFile *File : ObjectFiles) 1.58k
{
458
1.89k
    ObjFile<ELFT> *F = cast<ObjFile<ELFT>>(File);
459
1.29k
    for (SymbolBody *B : F->getLocalSymbols()) {
460
1.29k
      if (!B->IsLocal)
461
0
        fatal(toString(F) +
462
0
              ": broken object: getLocalSymbols returns a non-local symbol");
463
1.29k
      auto *DR = dyn_cast<DefinedRegular>(B);
464
1.29k
465
1.29k
      // No reason to keep local undefined symbol in symtab.
466
1.29k
      if (!DR)
467
4
        continue;
468
1.29k
      
if (1.29k
!includeInSymtab(*B)1.29k
)
469
87
        continue;
470
1.20k
471
1.20k
      SectionBase *Sec = DR->Section;
472
1.20k
      if (!shouldKeepInSymtab(Sec, B->getName(), *B))
473
549
        continue;
474
654
      InX::SymTab->addSymbol(B);
475
654
    }
476
1.89k
  }
477
1.58k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::copyLocalSymbols()
Line
Count
Source
454
1.25k
template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
455
1.25k
  if (!InX::SymTab)
456
3
    return;
457
1.25k
  
for (InputFile *File : ObjectFiles) 1.25k
{
458
1.50k
    ObjFile<ELFT> *F = cast<ObjFile<ELFT>>(File);
459
801
    for (SymbolBody *B : F->getLocalSymbols()) {
460
801
      if (!B->IsLocal)
461
0
        fatal(toString(F) +
462
0
              ": broken object: getLocalSymbols returns a non-local symbol");
463
801
      auto *DR = dyn_cast<DefinedRegular>(B);
464
801
465
801
      // No reason to keep local undefined symbol in symtab.
466
801
      if (!DR)
467
4
        continue;
468
797
      
if (797
!includeInSymtab(*B)797
)
469
73
        continue;
470
724
471
724
      SectionBase *Sec = DR->Section;
472
724
      if (!shouldKeepInSymtab(Sec, B->getName(), *B))
473
382
        continue;
474
342
      InX::SymTab->addSymbol(B);
475
342
    }
476
1.50k
  }
477
1.25k
}
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
}
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
191
template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
455
191
  if (!InX::SymTab)
456
0
    return;
457
191
  
for (InputFile *File : ObjectFiles) 191
{
458
219
    ObjFile<ELFT> *F = cast<ObjFile<ELFT>>(File);
459
337
    for (SymbolBody *B : F->getLocalSymbols()) {
460
337
      if (!B->IsLocal)
461
0
        fatal(toString(F) +
462
0
              ": broken object: getLocalSymbols returns a non-local symbol");
463
337
      auto *DR = dyn_cast<DefinedRegular>(B);
464
337
465
337
      // No reason to keep local undefined symbol in symtab.
466
337
      if (!DR)
467
0
        continue;
468
337
      
if (337
!includeInSymtab(*B)337
)
469
8
        continue;
470
329
471
329
      SectionBase *Sec = DR->Section;
472
329
      if (!shouldKeepInSymtab(Sec, B->getName(), *B))
473
85
        continue;
474
244
      InX::SymTab->addSymbol(B);
475
244
    }
476
219
  }
477
191
}
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)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
    });
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)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
    });
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)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
}
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)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
}
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.32k
532
3.32k
  // .init_array, .preinit_array and .fini_array contain pointers to
533
3.32k
  // functions that are executed on process startup or exit. These
534
3.32k
  // pointers are set by the static linker, and they are not expected
535
3.32k
  // to change at runtime. But if you are an attacker, you could do
536
3.32k
  // interesting things by manipulating pointers in .fini_array, for
537
3.32k
  // example. So they are put into RELRO.
538
3.32k
  uint32_t Type = Sec->Type;
539
3.32k
  if (
Type == SHT_INIT_ARRAY || 3.32k
Type == SHT_FINI_ARRAY3.30k
||
540
3.29k
      Type == SHT_PREINIT_ARRAY)
541
44
    return true;
542
3.28k
543
3.28k
  // .got contains pointers to external symbols. They are resolved by
544
3.28k
  // the dynamic linker when a module is loaded into memory, and after
545
3.28k
  // that they are not expected to change. So, it can be in RELRO.
546
3.28k
  
if (3.28k
InX::Got && 3.28k
Sec == InX::Got->getParent()2.47k
)
547
190
    return true;
548
3.09k
549
3.09k
  // .got.plt contains pointers to external function symbols. They are
550
3.09k
  // by default resolved lazily, so we usually cannot put it into RELRO.
551
3.09k
  // However, if "-z now" is given, the lazy symbol resolution is
552
3.09k
  // disabled, which enables us to put it into RELRO.
553
3.09k
  
if (3.09k
Sec == InX::GotPlt->getParent()3.09k
)
554
272
    return Config->ZNow;
555
2.82k
556
2.82k
  // .dynamic section contains data for the dynamic linker, and
557
2.82k
  // there's no need to write to it at runtime, so it's better to put
558
2.82k
  // it into RELRO.
559
2.82k
  
if (2.82k
Sec == InX::Dynamic->getParent()2.82k
)
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.44k
||
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.1k
625
72.1k
  // Sort sections based on their access permission in the following
626
72.1k
  // order: R, RX, RWX, RW.  This order is based on the following
627
72.1k
  // considerations:
628
72.1k
  // * Read-only sections come first such that they go in the
629
72.1k
  //   PT_LOAD covering the program headers at the start of the file.
630
72.1k
  // * Read-only, executable sections come next, unless the
631
72.1k
  //   -no-rosegment option is used.
632
72.1k
  // * Writable, executable sections follow such that .plt on
633
72.1k
  //   architectures where it needs to be writable will be placed
634
72.1k
  //   between .text and .data.
635
72.1k
  // * Writable sections come last, such that .bss lands at the very
636
72.1k
  //   end of the last PT_LOAD.
637
72.1k
  bool IsExec = Sec->Flags & SHF_EXECINSTR;
638
72.1k
  bool IsWrite = Sec->Flags & SHF_WRITE;
639
72.1k
640
72.1k
  if (
IsExec72.1k
) {
641
1.75k
    if (IsWrite)
642
18
      Rank |= RF_EXEC_WRITE;
643
1.74k
    else 
if (1.74k
!Config->SingleRoRx1.74k
)
644
1.38k
      Rank |= RF_EXEC;
645
72.1k
  } else {
646
70.4k
    if (IsWrite)
647
1.75k
      Rank |= RF_WRITE;
648
70.4k
  }
649
72.1k
650
72.1k
  // If we got here we know that both A and B are in the same PT_LOAD.
651
72.1k
652
72.1k
  bool IsTls = Sec->Flags & SHF_TLS;
653
72.1k
  bool IsNoBits = Sec->Type == SHT_NOBITS;
654
72.1k
655
72.1k
  // The first requirement we have is to put (non-TLS) nobits sections last. The
656
72.1k
  // reason is that the only thing the dynamic linker will see about them is a
657
72.1k
  // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
658
72.1k
  // PT_LOAD, so that has to correspond to the nobits sections.
659
278
  bool IsNonTlsNoBits = IsNoBits && !IsTls;
660
72.1k
  if (IsNonTlsNoBits)
661
227
    Rank |= RF_NON_TLS_BSS;
662
72.1k
663
72.1k
  // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
664
72.1k
  // sections after r/w ones, so that the RelRo sections are contiguous.
665
72.1k
  bool IsRelRo = isRelroSection(Sec);
666
72.1k
  if (
IsNonTlsNoBits && 72.1k
!IsRelRo227
)
667
224
    Rank |= RF_NON_TLS_BSS_RO;
668
72.1k
  if (
!IsNonTlsNoBits && 72.1k
IsRelRo71.9k
)
669
907
    Rank |= RF_NON_TLS_BSS_RO;
670
72.1k
671
72.1k
  // The TLS initialization block needs to be a single contiguous block in a R/W
672
72.1k
  // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
673
72.1k
  // sections. The TLS NOBITS sections are placed here as they don't take up
674
72.1k
  // virtual address space in the PT_LOAD.
675
72.1k
  if (!IsTls)
676
72.0k
    Rank |= RF_NOT_TLS;
677
72.1k
678
72.1k
  // Within the TLS initialization block, the non-nobits sections need to appear
679
72.1k
  // first.
680
72.1k
  if (IsNoBits)
681
278
    Rank |= RF_BSS;
682
72.1k
683
72.1k
  // Some architectures have additional ordering restrictions for sections
684
72.1k
  // within the same PT_LOAD.
685
72.1k
  if (
Config->EMachine == EM_PPC6472.1k
) {
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.1k
  if (
Config->EMachine == EM_MIPS72.1k
) {
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
79.9k
    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.2k
void PhdrEntry::add(OutputSection *Sec) {
733
78.2k
  LastSec = Sec;
734
78.2k
  if (!FirstSec)
735
6.65k
    FirstSec = Sec;
736
78.2k
  p_align = std::max(p_align, Sec->Alignment);
737
78.2k
  if (p_type == PT_LOAD)
738
75.0k
    Sec->PtLoad = this;
739
78.2k
}
740
741
template <class ELFT>
742
static Symbol *addRegular(StringRef Name, SectionBase *Sec, uint64_t Value,
743
                          uint8_t StOther = STV_HIDDEN,
744
890
                          uint8_t Binding = STB_WEAK) {
745
890
  // The linker generated symbols are added as STB_WEAK to allow user defined
746
890
  // ones to override them.
747
890
  return Symtab->addRegular<ELFT>(Name, StOther, STT_NOTYPE, Value,
748
890
                                  /*Size=*/0, Binding, Sec,
749
890
                                  /*File=*/nullptr);
750
890
}
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
120
                          uint8_t Binding = STB_WEAK) {
745
120
  // The linker generated symbols are added as STB_WEAK to allow user defined
746
120
  // ones to override them.
747
120
  return Symtab->addRegular<ELFT>(Name, StOther, STT_NOTYPE, Value,
748
120
                                  /*Size=*/0, Binding, Sec,
749
120
                                  /*File=*/nullptr);
750
120
}
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)1, true> >(llvm::StringRef, lld::elf::SectionBase*, unsigned long long, unsigned char, unsigned char)
Line
Count
Source
744
690
                          uint8_t Binding = STB_WEAK) {
745
690
  // The linker generated symbols are added as STB_WEAK to allow user defined
746
690
  // ones to override them.
747
690
  return Symtab->addRegular<ELFT>(Name, StOther, STT_NOTYPE, Value,
748
690
                                  /*Size=*/0, Binding, Sec,
749
690
                                  /*File=*/nullptr);
750
690
}
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
415k
                   uint8_t StOther = STV_HIDDEN, uint8_t Binding = STB_GLOBAL) {
756
415k
  SymbolBody *S = Symtab->find(Name);
757
415k
  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, false> >(llvm::StringRef, lld::elf::SectionBase*, unsigned long long, unsigned char, unsigned char)
Line
Count
Source
755
3.07k
                   uint8_t StOther = STV_HIDDEN, uint8_t Binding = STB_GLOBAL) {
756
3.07k
  SymbolBody *S = Symtab->find(Name);
757
3.07k
  if (!S)
758
3.06k
    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
}
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)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, 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
}
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.58k
template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
772
1.58k
  if (!Config->Static)
773
1.56k
    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.58k
  addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
779
1.58k
}
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
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addRelIpltSymbols()
Line
Count
Source
771
1.25k
template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
772
1.25k
  if (!Config->Static)
773
1.24k
    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.25k
  addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
779
1.25k
}
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
191
template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
772
191
  if (!Config->Static)
773
185
    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
191
  addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
779
191
}
780
781
// The linker is expected to define some symbols depending on
782
// the linking result. This function defines such symbols.
783
1.52k
template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
784
1.52k
  if (
Config->EMachine == EM_MIPS1.52k
) {
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.52k
807
1.52k
  // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
808
1.52k
  // be at some offset from the base of the .got section, usually 0 or the end
809
1.52k
  // of the .got
810
128
  InputSection *GotSection = InX::MipsGot ? cast<InputSection>(InX::MipsGot)
811
1.40k
                                          : cast<InputSection>(InX::Got);
812
1.52k
  ElfSym::GlobalOffsetTable = addOptionalRegular<ELFT>(
813
1.52k
      "_GLOBAL_OFFSET_TABLE_", GotSection, Target->GotBaseSymOff);
814
1.52k
815
1.52k
  // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
816
1.52k
  // static linking the linker is required to optimize away any references to
817
1.52k
  // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
818
1.52k
  // to avoid the undefined symbol error.
819
1.52k
  if (!InX::DynSymTab)
820
729
    Symtab->addIgnored<ELFT>("__tls_get_addr");
821
1.52k
822
1.52k
  // __ehdr_start is the location of ELF file headers. Note that we define
823
1.52k
  // this symbol unconditionally even when using a linker script, which
824
1.52k
  // differs from the behavior implemented by GNU linker which only define
825
1.52k
  // this symbol if ELF headers are in the memory mapped segment.
826
1.52k
  // __executable_start is not documented, but the expectation of at
827
1.52k
  // least the android libc is that it points to the elf header too.
828
1.52k
  // __dso_handle symbol is passed to cxa_finalize as a marker to identify
829
1.52k
  // each DSO. The address of the symbol doesn't matter as long as they are
830
1.52k
  // different in different DSOs, so we chose the start address of the DSO.
831
1.52k
  for (const char *Name :
832
1.52k
       {"__ehdr_start", "__executable_start", "__dso_handle"})
833
4.58k
    addOptionalRegular<ELFT>(Name, Out::ElfHeader, 0, STV_HIDDEN);
834
1.52k
835
1.52k
  // If linker script do layout we do not need to create any standart symbols.
836
1.52k
  if (Script->Opt.HasSections)
837
290
    return;
838
1.23k
839
1.23k
  
auto Add = [](StringRef S, int64_t Pos) 1.23k
{
840
8.67k
    return addOptionalRegular<ELFT>(S, Out::ElfHeader, Pos, STV_DEFAULT);
841
8.67k
  };
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)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
  };
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.65k
  auto Add = [](StringRef S, int64_t Pos) {
840
6.65k
    return addOptionalRegular<ELFT>(S, Out::ElfHeader, Pos, STV_DEFAULT);
841
6.65k
  };
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
  };
842
1.52k
843
1.52k
  ElfSym::Bss = Add("__bss_start", 0);
844
1.52k
  ElfSym::End1 = Add("end", -1);
845
1.52k
  ElfSym::End2 = Add("_end", -1);
846
1.52k
  ElfSym::Etext1 = Add("etext", -1);
847
1.52k
  ElfSym::Etext2 = Add("_etext", -1);
848
1.52k
  ElfSym::Edata1 = Add("edata", -1);
849
1.52k
  ElfSym::Edata2 = Add("_edata", -1);
850
1.52k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::addReservedSymbols()
Line
Count
Source
783
1.21k
template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
784
1.21k
  if (
Config->EMachine == EM_MIPS1.21k
) {
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.21k
807
1.21k
  // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
808
1.21k
  // be at some offset from the base of the .got section, usually 0 or the end
809
1.21k
  // of the .got
810
2
  InputSection *GotSection = InX::MipsGot ? cast<InputSection>(InX::MipsGot)
811
1.21k
                                          : cast<InputSection>(InX::Got);
812
1.21k
  ElfSym::GlobalOffsetTable = addOptionalRegular<ELFT>(
813
1.21k
      "_GLOBAL_OFFSET_TABLE_", GotSection, Target->GotBaseSymOff);
814
1.21k
815
1.21k
  // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
816
1.21k
  // static linking the linker is required to optimize away any references to
817
1.21k
  // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
818
1.21k
  // to avoid the undefined symbol error.
819
1.21k
  if (!InX::DynSymTab)
820
599
    Symtab->addIgnored<ELFT>("__tls_get_addr");
821
1.21k
822
1.21k
  // __ehdr_start is the location of ELF file headers. Note that we define
823
1.21k
  // this symbol unconditionally even when using a linker script, which
824
1.21k
  // differs from the behavior implemented by GNU linker which only define
825
1.21k
  // this symbol if ELF headers are in the memory mapped segment.
826
1.21k
  // __executable_start is not documented, but the expectation of at
827
1.21k
  // least the android libc is that it points to the elf header too.
828
1.21k
  // __dso_handle symbol is passed to cxa_finalize as a marker to identify
829
1.21k
  // each DSO. The address of the symbol doesn't matter as long as they are
830
1.21k
  // different in different DSOs, so we chose the start address of the DSO.
831
1.21k
  for (const char *Name :
832
1.21k
       {"__ehdr_start", "__executable_start", "__dso_handle"})
833
3.64k
    addOptionalRegular<ELFT>(Name, Out::ElfHeader, 0, STV_HIDDEN);
834
1.21k
835
1.21k
  // If linker script do layout we do not need to create any standart symbols.
836
1.21k
  if (Script->Opt.HasSections)
837
264
    return;
838
950
839
950
  auto Add = [](StringRef S, int64_t Pos) {
840
950
    return addOptionalRegular<ELFT>(S, Out::ElfHeader, Pos, STV_DEFAULT);
841
950
  };
842
950
843
950
  ElfSym::Bss = Add("__bss_start", 0);
844
950
  ElfSym::End1 = Add("end", -1);
845
950
  ElfSym::End2 = Add("_end", -1);
846
950
  ElfSym::Etext1 = Add("etext", -1);
847
950
  ElfSym::Etext2 = Add("_etext", -1);
848
950
  ElfSym::Edata1 = Add("edata", -1);
849
950
  ElfSym::Edata2 = Add("_edata", -1);
850
950
}
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)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)1, false> >::addReservedSymbols()
Line
Count
Source
783
185
template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
784
185
  if (
Config->EMachine == EM_MIPS185
) {
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
185
807
185
  // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
808
185
  // be at some offset from the base of the .got section, usually 0 or the end
809
185
  // of the .got
810
14
  InputSection *GotSection = InX::MipsGot ? cast<InputSection>(InX::MipsGot)
811
171
                                          : cast<InputSection>(InX::Got);
812
185
  ElfSym::GlobalOffsetTable = addOptionalRegular<ELFT>(
813
185
      "_GLOBAL_OFFSET_TABLE_", GotSection, Target->GotBaseSymOff);
814
185
815
185
  // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
816
185
  // static linking the linker is required to optimize away any references to
817
185
  // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
818
185
  // to avoid the undefined symbol error.
819
185
  if (!InX::DynSymTab)
820
79
    Symtab->addIgnored<ELFT>("__tls_get_addr");
821
185
822
185
  // __ehdr_start is the location of ELF file headers. Note that we define
823
185
  // this symbol unconditionally even when using a linker script, which
824
185
  // differs from the behavior implemented by GNU linker which only define
825
185
  // this symbol if ELF headers are in the memory mapped segment.
826
185
  // __executable_start is not documented, but the expectation of at
827
185
  // least the android libc is that it points to the elf header too.
828
185
  // __dso_handle symbol is passed to cxa_finalize as a marker to identify
829
185
  // each DSO. The address of the symbol doesn't matter as long as they are
830
185
  // different in different DSOs, so we chose the start address of the DSO.
831
185
  for (const char *Name :
832
185
       {"__ehdr_start", "__executable_start", "__dso_handle"})
833
555
    addOptionalRegular<ELFT>(Name, Out::ElfHeader, 0, STV_HIDDEN);
834
185
835
185
  // If linker script do layout we do not need to create any standart symbols.
836
185
  if (Script->Opt.HasSections)
837
17
    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
}
851
852
// Sort input sections by section name suffixes for
853
// __attribute__((init_priority(N))).
854
2.59k
static void sortInitFini(OutputSection *Cmd) {
855
2.59k
  if (Cmd)
856
9
    Cmd->sortInitFini();
857
2.59k
}
858
859
// Sort input sections by the special rule for .ctors and .dtors.
860
2.59k
static void sortCtorsDtors(OutputSection *Cmd) {
861
2.59k
  if (Cmd)
862
8
    Cmd->sortCtorsDtors();
863
2.59k
}
864
865
// Sort input sections using the list provided by --symbol-ordering-file.
866
1.29k
static void sortBySymbolsOrder() {
867
1.29k
  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.29k
}
876
877
template <class ELFT>
878
1.52k
void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
879
1.52k
  // Scan all relocations. Each relocation goes through a series
880
1.52k
  // of tests to determine if it needs special treatment, such as
881
1.52k
  // creating GOT, PLT, copy relocations, etc.
882
1.52k
  // Note that relocations for non-alloc sections are directly
883
1.52k
  // processed by InputSection::relocateNonAlloc.
884
1.52k
  for (InputSectionBase *IS : InputSections)
885
227k
    
if (227k
IS->Live && 227k
isa<InputSection>(IS)226k
&&
(IS->Flags & SHF_ALLOC)226k
)
886
90.1k
      Fn(*IS);
887
1.52k
  for (EhInputSection *ES : In<ELFT>::EhFrame->Sections)
888
92
    Fn(*ES);
889
1.52k
}
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
185
void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
879
185
  // Scan all relocations. Each relocation goes through a series
880
185
  // of tests to determine if it needs special treatment, such as
881
185
  // creating GOT, PLT, copy relocations, etc.
882
185
  // Note that relocations for non-alloc sections are directly
883
185
  // processed by InputSection::relocateNonAlloc.
884
185
  for (InputSectionBase *IS : InputSections)
885
3.85k
    
if (3.85k
IS->Live && 3.85k
isa<InputSection>(IS)3.81k
&&
(IS->Flags & SHF_ALLOC)3.81k
)
886
3.06k
      Fn(*IS);
887
185
  for (EhInputSection *ES : In<ELFT>::EhFrame->Sections)
888
4
    Fn(*ES);
889
185
}
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)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)1, true> >::forEachRelSec(std::__1::function<void (lld::elf::InputSectionBase&)>)
Line
Count
Source
878
1.21k
void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
879
1.21k
  // Scan all relocations. Each relocation goes through a series
880
1.21k
  // of tests to determine if it needs special treatment, such as
881
1.21k
  // creating GOT, PLT, copy relocations, etc.
882
1.21k
  // Note that relocations for non-alloc sections are directly
883
1.21k
  // processed by InputSection::relocateNonAlloc.
884
1.21k
  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.21k
  for (EhInputSection *ES : In<ELFT>::EhFrame->Sections)
888
84
    Fn(*ES);
889
1.21k
}
890
891
1.29k
template <class ELFT> void Writer<ELFT>::createSections() {
892
1.29k
  std::vector<BaseCommand *> Old = Script->Opt.Commands;
893
1.29k
  Script->Opt.Commands.clear();
894
1.29k
  for (InputSectionBase *IS : InputSections)
895
92.2k
    
if (92.2k
IS92.2k
)
896
92.2k
      Factory.addInputSec(IS, getOutputSectionName(IS->Name));
897
1.29k
  Script->Opt.Commands.insert(Script->Opt.Commands.end(), Old.begin(),
898
1.29k
                              Old.end());
899
1.29k
900
1.29k
  Script->fabricateDefaultCommands();
901
1.29k
  sortBySymbolsOrder();
902
1.29k
  sortInitFini(findSection(".init_array"));
903
1.29k
  sortInitFini(findSection(".fini_array"));
904
1.29k
  sortCtorsDtors(findSection(".ctors"));
905
1.29k
  sortCtorsDtors(findSection(".dtors"));
906
1.29k
}
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
994
template <class ELFT> void Writer<ELFT>::createSections() {
892
994
  std::vector<BaseCommand *> Old = Script->Opt.Commands;
893
994
  Script->Opt.Commands.clear();
894
994
  for (InputSectionBase *IS : InputSections)
895
85.2k
    
if (85.2k
IS85.2k
)
896
85.2k
      Factory.addInputSec(IS, getOutputSectionName(IS->Name));
897
994
  Script->Opt.Commands.insert(Script->Opt.Commands.end(), Old.begin(),
898
994
                              Old.end());
899
994
900
994
  Script->fabricateDefaultCommands();
901
994
  sortBySymbolsOrder();
902
994
  sortInitFini(findSection(".init_array"));
903
994
  sortInitFini(findSection(".fini_array"));
904
994
  sortCtorsDtors(findSection(".ctors"));
905
994
  sortCtorsDtors(findSection(".dtors"));
906
994
}
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
}
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
}
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.52k
template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
914
1.52k
  PhdrEntry *Last = nullptr;
915
1.52k
  PhdrEntry *LastRO = nullptr;
916
1.52k
  PhdrEntry *LastRW = nullptr;
917
1.52k
918
8.09k
  for (PhdrEntry *P : Phdrs) {
919
8.09k
    if (P->p_type != PT_LOAD)
920
4.49k
      continue;
921
3.60k
    Last = P;
922
3.60k
    if (P->p_flags & PF_W)
923
988
      LastRW = P;
924
3.60k
    else
925
2.61k
      LastRO = P;
926
8.09k
  }
927
1.52k
928
1.52k
  // _end is the first location after the uninitialized data region.
929
1.52k
  if (
Last1.52k
) {
930
1.45k
    if (ElfSym::End1)
931
3
      ElfSym::End1->Section = Last->LastSec;
932
1.45k
    if (ElfSym::End2)
933
8
      ElfSym::End2->Section = Last->LastSec;
934
1.45k
  }
935
1.52k
936
1.52k
  // _etext is the first location after the last read-only loadable segment.
937
1.52k
  if (
LastRO1.52k
) {
938
1.44k
    if (ElfSym::Etext1)
939
0
      ElfSym::Etext1->Section = LastRO->LastSec;
940
1.44k
    if (ElfSym::Etext2)
941
1
      ElfSym::Etext2->Section = LastRO->LastSec;
942
1.44k
  }
943
1.52k
944
1.52k
  // _edata points to the end of the last non SHT_NOBITS section.
945
1.52k
  if (
LastRW1.52k
) {
946
974
    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
964
        break;
950
974
951
5.34k
    for (; 
I < OutputSections.size()5.34k
;
++I4.37k
) {
952
4.61k
      if (OutputSections[I]->Type != SHT_NOBITS)
953
4.37k
        continue;
954
241
      break;
955
241
    }
956
974
    if (ElfSym::Edata1)
957
0
      ElfSym::Edata1->Section = OutputSections[I - 1];
958
974
    if (ElfSym::Edata2)
959
3
      ElfSym::Edata2->Section = OutputSections[I - 1];
960
974
  }
961
1.52k
962
1.52k
  if (ElfSym::Bss)
963
3
    ElfSym::Bss->Section = findSection(".bss");
964
1.52k
965
1.52k
  // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
966
1.52k
  // be equal to the _gp symbol's value.
967
1.52k
  if (
ElfSym::MipsGp1.52k
) {
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.52k
    }
977
127
  }
978
1.52k
}
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, 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.28k
  for (PhdrEntry *P : Phdrs) {
919
6.28k
    if (P->p_type != PT_LOAD)
920
3.51k
      continue;
921
2.76k
    Last = P;
922
2.76k
    if (P->p_flags & PF_W)
923
733
      LastRW = P;
924
2.76k
    else
925
2.03k
      LastRO = P;
926
6.28k
  }
927
1.20k
928
1.20k
  // _end is the first location after the uninitialized data region.
929
1.20k
  if (
Last1.20k
) {
930
1.14k
    if (ElfSym::End1)
931
3
      ElfSym::End1->Section = Last->LastSec;
932
1.14k
    if (ElfSym::End2)
933
8
      ElfSym::End2->Section = Last->LastSec;
934
1.14k
  }
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.13k
    if (ElfSym::Etext1)
939
0
      ElfSym::Etext1->Section = LastRO->LastSec;
940
1.13k
    if (ElfSym::Etext2)
941
1
      ElfSym::Etext2->Section = LastRO->LastSec;
942
1.13k
  }
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
722
    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
713
        break;
950
722
951
4.16k
    for (; 
I < OutputSections.size()4.16k
;
++I3.44k
) {
952
3.54k
      if (OutputSections[I]->Type != SHT_NOBITS)
953
3.44k
        continue;
954
98
      break;
955
98
    }
956
722
    if (ElfSym::Edata1)
957
0
      ElfSym::Edata1->Section = OutputSections[I - 1];
958
722
    if (ElfSym::Edata2)
959
3
      ElfSym::Edata2->Section = OutputSections[I - 1];
960
722
  }
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
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::setReservedSymbolSections()
Line
Count
Source
913
187
template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
914
187
  PhdrEntry *Last = nullptr;
915
187
  PhdrEntry *LastRO = nullptr;
916
187
  PhdrEntry *LastRW = nullptr;
917
187
918
1.06k
  for (PhdrEntry *P : Phdrs) {
919
1.06k
    if (P->p_type != PT_LOAD)
920
602
      continue;
921
467
    Last = P;
922
467
    if (P->p_flags & PF_W)
923
130
      LastRW = P;
924
467
    else
925
337
      LastRO = P;
926
1.06k
  }
927
187
928
187
  // _end is the first location after the uninitialized data region.
929
187
  if (
Last187
) {
930
180
    if (ElfSym::End1)
931
0
      ElfSym::End1->Section = Last->LastSec;
932
180
    if (ElfSym::End2)
933
0
      ElfSym::End2->Section = Last->LastSec;
934
180
  }
935
187
936
187
  // _etext is the first location after the last read-only loadable segment.
937
187
  if (
LastRO187
) {
938
178
    if (ElfSym::Etext1)
939
0
      ElfSym::Etext1->Section = LastRO->LastSec;
940
178
    if (ElfSym::Etext2)
941
0
      ElfSym::Etext2->Section = LastRO->LastSec;
942
178
  }
943
187
944
187
  // _edata points to the end of the last non SHT_NOBITS section.
945
187
  if (
LastRW187
) {
946
127
    size_t I = 0;
947
746
    for (; 
I < OutputSections.size()746
;
++I619
)
948
745
      
if (745
OutputSections[I] == LastRW->FirstSec745
)
949
126
        break;
950
127
951
699
    for (; 
I < OutputSections.size()699
;
++I572
) {
952
607
      if (OutputSections[I]->Type != SHT_NOBITS)
953
572
        continue;
954
35
      break;
955
35
    }
956
127
    if (ElfSym::Edata1)
957
0
      ElfSym::Edata1->Section = OutputSections[I - 1];
958
127
    if (ElfSym::Edata2)
959
0
      ElfSym::Edata2->Section = OutputSections[I - 1];
960
127
  }
961
187
962
187
  if (ElfSym::Bss)
963
0
    ElfSym::Bss->Section = findSection(".bss");
964
187
965
187
  // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
966
187
  // be equal to the _gp symbol's value.
967
187
  if (
ElfSym::MipsGp187
) {
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
187
    }
977
14
  }
978
187
}
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
410
static bool shouldSkip(BaseCommand *Cmd) {
1010
410
  if (isa<OutputSection>(Cmd))
1011
242
    return false;
1012
168
  
if (auto *168
Assign168
= dyn_cast<SymbolAssignment>(Cmd))
1013
166
    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
605
              std::vector<BaseCommand *>::iterator E) {
1024
605
  OutputSection *Sec = cast<OutputSection>(*E);
1025
605
1026
605
  // Find the first element that has as close a rank as possible.
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)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, 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
136
  auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
1028
136
    return getRankProximity(Sec, A) < getRankProximity(Sec, B);
1029
136
  });
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)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
  });
1030
605
  if (I == E)
1031
40
    return E;
1032
565
1033
565
  // Consider all existing sections with the same proximity.
1034
565
  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
565
  auto J = std::find_if(
1044
565
      llvm::make_reverse_iterator(I), llvm::make_reverse_iterator(B),
1045
591
      [](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
32
      [](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
519
      [](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)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
565
  I = J.base();
1047
565
1048
565
  // As a special case, if the orphan section is the last section, put
1049
565
  // it at the very end, past any other commands.
1050
565
  // This matches bfd's behavior and is convenient when the linker script fully
1051
565
  // specifies the start of the file, but doesn't care about the end (the non
1052
565
  // alloc sections for example).
1053
565
  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, 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)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)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
565
  if (NextSec == E)
1056
522
    return E;
1057
43
1058
48
  
while (43
I != E && 48
shouldSkip(*I)48
)
1059
5
    ++I;
1060
605
  return I;
1061
605
}
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
33
              std::vector<BaseCommand *>::iterator E) {
1024
33
  OutputSection *Sec = cast<OutputSection>(*E);
1025
33
1026
33
  // Find the first element that has as close a rank as possible.
1027
33
  auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
1028
33
    return getRankProximity(Sec, A) < getRankProximity(Sec, B);
1029
33
  });
1030
33
  if (I == E)
1031
0
    return E;
1032
33
1033
33
  // Consider all existing sections with the same proximity.
1034
33
  int Proximity = getRankProximity(Sec, *I);
1035
177
  for (; 
I != E177
;
++I144
) {
1036
146
    auto *CurSec = dyn_cast<OutputSection>(*I);
1037
146
    if (
!CurSec || 146
!CurSec->Live146
)
1038
0
      continue;
1039
146
    
if (146
getRankProximity(Sec, CurSec) != Proximity ||
1040
145
        Sec->SortRank < CurSec->SortRank)
1041
2
      break;
1042
146
  }
1043
33
  auto J = std::find_if(
1044
33
      llvm::make_reverse_iterator(I), llvm::make_reverse_iterator(B),
1045
33
      [](BaseCommand *Cmd) { return isa<OutputSection>(Cmd); });
1046
33
  I = J.base();
1047
33
1048
33
  // As a special case, if the orphan section is the last section, put
1049
33
  // it at the very end, past any other commands.
1050
33
  // This matches bfd's behavior and is convenient when the linker script fully
1051
33
  // specifies the start of the file, but doesn't care about the end (the non
1052
33
  // alloc sections for example).
1053
33
  auto NextSec = std::find_if(
1054
33
      I, E, [](BaseCommand *Cmd) { return isa<OutputSection>(Cmd); });
1055
33
  if (NextSec == E)
1056
31
    return E;
1057
2
1058
2
  
while (2
I != E && 2
shouldSkip(*I)2
)
1059
0
    ++I;
1060
33
  return I;
1061
33
}
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
533
              std::vector<BaseCommand *>::iterator E) {
1024
533
  OutputSection *Sec = cast<OutputSection>(*E);
1025
533
1026
533
  // Find the first element that has as close a rank as possible.
1027
533
  auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
1028
533
    return getRankProximity(Sec, A) < getRankProximity(Sec, B);
1029
533
  });
1030
533
  if (I == E)
1031
40
    return E;
1032
493
1033
493
  // Consider all existing sections with the same proximity.
1034
493
  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
493
  auto J = std::find_if(
1044
493
      llvm::make_reverse_iterator(I), llvm::make_reverse_iterator(B),
1045
493
      [](BaseCommand *Cmd) { return isa<OutputSection>(Cmd); });
1046
493
  I = J.base();
1047
493
1048
493
  // As a special case, if the orphan section is the last section, put
1049
493
  // it at the very end, past any other commands.
1050
493
  // This matches bfd's behavior and is convenient when the linker script fully
1051
493
  // specifies the start of the file, but doesn't care about the end (the non
1052
493
  // alloc sections for example).
1053
493
  auto NextSec = std::find_if(
1054
493
      I, E, [](BaseCommand *Cmd) { return isa<OutputSection>(Cmd); });
1055
493
  if (NextSec == E)
1056
462
    return E;
1057
31
1058
33
  
while (31
I != E && 33
shouldSkip(*I)33
)
1059
2
    ++I;
1060
533
  return I;
1061
533
}
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
}
1062
1063
1.52k
template <class ELFT> void Writer<ELFT>::sortSections() {
1064
1.52k
  if (Script->Opt.HasSections)
1065
283
    Script->adjustSectionsBeforeSorting();
1066
1.52k
1067
1.52k
  // Don't sort if using -r. It is not necessary and we want to preserve the
1068
1.52k
  // relative order for SHF_LINK_ORDER sections.
1069
1.52k
  if (Config->Relocatable)
1070
59
    return;
1071
1.46k
1072
1.46k
  for (BaseCommand *Base : Script->Opt.Commands)
1073
210k
    
if (auto *210k
Sec210k
= dyn_cast<OutputSection>(Base))
1074
208k
      Sec->SortRank = getSectionRank(Sec);
1075
1.46k
1076
1.46k
  if (
!Script->Opt.HasSections1.46k
) {
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.56k
    auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::sortSections()::'lambda'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1081
123
    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.71k
    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); };
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
282
1090
282
  // Orphan sections are sections present in the input files which are
1091
282
  // not explicitly placed into the output file by the linker script.
1092
282
  //
1093
282
  // The sections in the linker script are already in the correct
1094
282
  // order. We have to figuere out where to insert the orphan
1095
282
  // sections.
1096
282
  //
1097
282
  // The order of the sections in the script is arbitrary and may not agree with
1098
282
  // compareSections. This means that we cannot easily define a strict weak
1099
282
  // ordering. To see why, consider a comparison of a section in the script and
1100
282
  // one not in the script. We have a two simple options:
1101
282
  // * Make them equivalent (a is not less than b, and b is not less than a).
1102
282
  //   The problem is then that equivalence has to be transitive and we can
1103
282
  //   have sections a, b and c with only b in a script and a less than c
1104
282
  //   which breaks this property.
1105
282
  // * Use compareSectionsNonScript. Given that the script order doesn't have
1106
282
  //   to match, we can end up with sections a, b, c, d where b and c are in the
1107
282
  //   script and c is compareSectionsNonScript less than b. In which case d
1108
282
  //   can be equivalent to c, a to b and d < a. As a concrete example:
1109
282
  //   .a (rx) # not in script
1110
282
  //   .b (rx) # in script
1111
282
  //   .c (ro) # in script
1112
282
  //   .d (ro) # not in script
1113
282
  //
1114
282
  // The way we define an order then is:
1115
282
  // *  Sort only the orphan sections. They are in the end right now.
1116
282
  // *  Move each orphan section to its preferred position. We try
1117
282
  //    to put each section in the last position where it it can share
1118
282
  //    a PT_LOAD.
1119
282
  //
1120
282
  // There is some ambiguity as to where exactly a new entry should be
1121
282
  // inserted, because Opt.Commands contains not only output section
1122
282
  // commands but also other types of commands such as symbol assignment
1123
282
  // expressions. There's no correct answer here due to the lack of the
1124
282
  // formal specification of the linker script. We use heuristics to
1125
282
  // determine whether a new output command should be added before or
1126
282
  // after another commands. For the details, look at shouldSkip
1127
282
  // function.
1128
282
1129
282
  auto I = Script->Opt.Commands.begin();
1130
282
  auto E = Script->Opt.Commands.end();
1131
957
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1132
957
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1133
719
      
return Sec->Live && 719
Sec->SectionIndex == INT_MAX691
;
1134
238
    return false;
1135
238
  });
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
84
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1132
84
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1133
74
      
return Sec->Live && 74
Sec->SectionIndex == INT_MAX74
;
1134
10
    return false;
1135
10
  });
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
  });
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
846
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1132
846
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1133
622
      
return Sec->Live && 622
Sec->SectionIndex == INT_MAX594
;
1134
224
    return false;
1135
224
  });
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
  });
1136
282
1137
282
  // Sort the orphan sections.
1138
282
  std::stable_sort(NonScriptI, E, compareSections);
1139
282
1140
282
  // As a horrible special case, skip the first . assignment if it is before any
1141
282
  // section. We do this because it is common to set a load address by starting
1142
282
  // the script with ". = 0xabcd" and the expectation is that every section is
1143
282
  // after that.
1144
282
  auto FirstSectionOrDotAssignment =
1145
362
      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
336
      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
17
      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
282
  if (FirstSectionOrDotAssignment != E &&
1147
282
      isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1148
77
    ++FirstSectionOrDotAssignment;
1149
282
  I = FirstSectionOrDotAssignment;
1150
282
1151
887
  while (
NonScriptI != E887
) {
1152
605
    auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1153
605
    OutputSection *Orphan = cast<OutputSection>(*NonScriptI);
1154
605
1155
605
    // As an optimization, find all sections with the same sort rank
1156
605
    // and insert them with one rotate.
1157
605
    unsigned Rank = Orphan->SortRank;
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)1, false> >::sortSections()::'lambda2'(lld::elf::BaseCommand*)::operator()(lld::elf::BaseCommand*) const
Line
Count
Source
1158
88
    auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1159
88
      return cast<OutputSection>(Cmd)->SortRank != Rank;
1160
88
    });
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
    });
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
    });
1161
605
    std::rotate(Pos, NonScriptI, End);
1162
605
    NonScriptI = End;
1163
605
  }
1164
1.52k
1165
1.52k
  Script->adjustSectionsAfterSorting();
1166
1.52k
}
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, false> >::sortSections()
Line
Count
Source
1063
187
template <class ELFT> void Writer<ELFT>::sortSections() {
1064
187
  if (Script->Opt.HasSections)
1065
17
    Script->adjustSectionsBeforeSorting();
1066
187
1067
187
  // Don't sort if using -r. It is not necessary and we want to preserve the
1068
187
  // relative order for SHF_LINK_ORDER sections.
1069
187
  if (Config->Relocatable)
1070
6
    return;
1071
181
1072
181
  for (BaseCommand *Base : Script->Opt.Commands)
1073
1.88k
    
if (auto *1.88k
Sec1.88k
= dyn_cast<OutputSection>(Base))
1074
1.71k
      Sec->SortRank = getSectionRank(Sec);
1075
181
1076
181
  if (
!Script->Opt.HasSections181
) {
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
17
1090
17
  // Orphan sections are sections present in the input files which are
1091
17
  // not explicitly placed into the output file by the linker script.
1092
17
  //
1093
17
  // The sections in the linker script are already in the correct
1094
17
  // order. We have to figuere out where to insert the orphan
1095
17
  // sections.
1096
17
  //
1097
17
  // The order of the sections in the script is arbitrary and may not agree with
1098
17
  // compareSections. This means that we cannot easily define a strict weak
1099
17
  // ordering. To see why, consider a comparison of a section in the script and
1100
17
  // one not in the script. We have a two simple options:
1101
17
  // * Make them equivalent (a is not less than b, and b is not less than a).
1102
17
  //   The problem is then that equivalence has to be transitive and we can
1103
17
  //   have sections a, b and c with only b in a script and a less than c
1104
17
  //   which breaks this property.
1105
17
  // * Use compareSectionsNonScript. Given that the script order doesn't have
1106
17
  //   to match, we can end up with sections a, b, c, d where b and c are in the
1107
17
  //   script and c is compareSectionsNonScript less than b. In which case d
1108
17
  //   can be equivalent to c, a to b and d < a. As a concrete example:
1109
17
  //   .a (rx) # not in script
1110
17
  //   .b (rx) # in script
1111
17
  //   .c (ro) # in script
1112
17
  //   .d (ro) # not in script
1113
17
  //
1114
17
  // The way we define an order then is:
1115
17
  // *  Sort only the orphan sections. They are in the end right now.
1116
17
  // *  Move each orphan section to its preferred position. We try
1117
17
  //    to put each section in the last position where it it can share
1118
17
  //    a PT_LOAD.
1119
17
  //
1120
17
  // There is some ambiguity as to where exactly a new entry should be
1121
17
  // inserted, because Opt.Commands contains not only output section
1122
17
  // commands but also other types of commands such as symbol assignment
1123
17
  // expressions. There's no correct answer here due to the lack of the
1124
17
  // formal specification of the linker script. We use heuristics to
1125
17
  // determine whether a new output command should be added before or
1126
17
  // after another commands. For the details, look at shouldSkip
1127
17
  // function.
1128
17
1129
17
  auto I = Script->Opt.Commands.begin();
1130
17
  auto E = Script->Opt.Commands.end();
1131
17
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1132
17
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1133
17
      return Sec->Live && Sec->SectionIndex == INT_MAX;
1134
17
    return false;
1135
17
  });
1136
17
1137
17
  // Sort the orphan sections.
1138
17
  std::stable_sort(NonScriptI, E, compareSections);
1139
17
1140
17
  // As a horrible special case, skip the first . assignment if it is before any
1141
17
  // section. We do this because it is common to set a load address by starting
1142
17
  // the script with ". = 0xabcd" and the expectation is that every section is
1143
17
  // after that.
1144
17
  auto FirstSectionOrDotAssignment =
1145
17
      std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1146
17
  if (FirstSectionOrDotAssignment != E &&
1147
17
      isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1148
10
    ++FirstSectionOrDotAssignment;
1149
17
  I = FirstSectionOrDotAssignment;
1150
17
1151
50
  while (
NonScriptI != E50
) {
1152
33
    auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1153
33
    OutputSection *Orphan = cast<OutputSection>(*NonScriptI);
1154
33
1155
33
    // As an optimization, find all sections with the same sort rank
1156
33
    // and insert them with one rotate.
1157
33
    unsigned Rank = Orphan->SortRank;
1158
33
    auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1159
33
      return cast<OutputSection>(Cmd)->SortRank != Rank;
1160
33
    });
1161
33
    std::rotate(Pos, NonScriptI, End);
1162
33
    NonScriptI = End;
1163
33
  }
1164
187
1165
187
  Script->adjustSectionsAfterSorting();
1166
187
}
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
257
    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.15k
1072
1.15k
  for (BaseCommand *Base : Script->Opt.Commands)
1073
206k
    
if (auto *206k
Sec206k
= dyn_cast<OutputSection>(Base))
1074
205k
      Sec->SortRank = getSectionRank(Sec);
1075
1.15k
1076
1.15k
  if (
!Script->Opt.HasSections1.15k
) {
1077
899
    // We know that all the OutputSections are contiguous in
1078
899
    // this case.
1079
899
    auto E = Script->Opt.Commands.end();
1080
899
    auto I = Script->Opt.Commands.begin();
1081
899
    auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
1082
899
    I = std::find_if(I, E, IsSection);
1083
899
    E = std::find_if(llvm::make_reverse_iterator(E),
1084
899
                     llvm::make_reverse_iterator(I), IsSection)
1085
899
            .base();
1086
899
    std::stable_sort(I, E, compareSections);
1087
899
    return;
1088
899
  }
1089
256
1090
256
  // Orphan sections are sections present in the input files which are
1091
256
  // not explicitly placed into the output file by the linker script.
1092
256
  //
1093
256
  // The sections in the linker script are already in the correct
1094
256
  // order. We have to figuere out where to insert the orphan
1095
256
  // sections.
1096
256
  //
1097
256
  // The order of the sections in the script is arbitrary and may not agree with
1098
256
  // compareSections. This means that we cannot easily define a strict weak
1099
256
  // ordering. To see why, consider a comparison of a section in the script and
1100
256
  // one not in the script. We have a two simple options:
1101
256
  // * Make them equivalent (a is not less than b, and b is not less than a).
1102
256
  //   The problem is then that equivalence has to be transitive and we can
1103
256
  //   have sections a, b and c with only b in a script and a less than c
1104
256
  //   which breaks this property.
1105
256
  // * Use compareSectionsNonScript. Given that the script order doesn't have
1106
256
  //   to match, we can end up with sections a, b, c, d where b and c are in the
1107
256
  //   script and c is compareSectionsNonScript less than b. In which case d
1108
256
  //   can be equivalent to c, a to b and d < a. As a concrete example:
1109
256
  //   .a (rx) # not in script
1110
256
  //   .b (rx) # in script
1111
256
  //   .c (ro) # in script
1112
256
  //   .d (ro) # not in script
1113
256
  //
1114
256
  // The way we define an order then is:
1115
256
  // *  Sort only the orphan sections. They are in the end right now.
1116
256
  // *  Move each orphan section to its preferred position. We try
1117
256
  //    to put each section in the last position where it it can share
1118
256
  //    a PT_LOAD.
1119
256
  //
1120
256
  // There is some ambiguity as to where exactly a new entry should be
1121
256
  // inserted, because Opt.Commands contains not only output section
1122
256
  // commands but also other types of commands such as symbol assignment
1123
256
  // expressions. There's no correct answer here due to the lack of the
1124
256
  // formal specification of the linker script. We use heuristics to
1125
256
  // determine whether a new output command should be added before or
1126
256
  // after another commands. For the details, look at shouldSkip
1127
256
  // function.
1128
256
1129
256
  auto I = Script->Opt.Commands.begin();
1130
256
  auto E = Script->Opt.Commands.end();
1131
256
  auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1132
256
    if (auto *Sec = dyn_cast<OutputSection>(Base))
1133
256
      return Sec->Live && Sec->SectionIndex == INT_MAX;
1134
256
    return false;
1135
256
  });
1136
256
1137
256
  // Sort the orphan sections.
1138
256
  std::stable_sort(NonScriptI, E, compareSections);
1139
256
1140
256
  // As a horrible special case, skip the first . assignment if it is before any
1141
256
  // section. We do this because it is common to set a load address by starting
1142
256
  // the script with ". = 0xabcd" and the expectation is that every section is
1143
256
  // after that.
1144
256
  auto FirstSectionOrDotAssignment =
1145
256
      std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1146
256
  if (FirstSectionOrDotAssignment != E &&
1147
256
      isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1148
66
    ++FirstSectionOrDotAssignment;
1149
256
  I = FirstSectionOrDotAssignment;
1150
256
1151
789
  while (
NonScriptI != E789
) {
1152
533
    auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1153
533
    OutputSection *Orphan = cast<OutputSection>(*NonScriptI);
1154
533
1155
533
    // As an optimization, find all sections with the same sort rank
1156
533
    // and insert them with one rotate.
1157
533
    unsigned Rank = Orphan->SortRank;
1158
533
    auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1159
533
      return cast<OutputSection>(Cmd)->SortRank != Rank;
1160
533
    });
1161
533
    std::rotate(Pos, NonScriptI, End);
1162
533
    NonScriptI = End;
1163
533
  }
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.65k
                           std::function<void(SyntheticSection *)> Fn) {
1170
4.65k
  for (SyntheticSection *SS : Sections)
1171
41.2k
    
if (41.2k
SS && 41.2k
SS->getParent()32.0k
&&
!SS->empty()29.7k
)
1172
13.1k
      Fn(SS);
1173
4.65k
}
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.52k
static void removeUnusedSyntheticSections() {
1180
1.52k
  // All input synthetic sections that can be empty are placed after
1181
1.52k
  // all regular ones. We iterate over them all and exit at first
1182
1.52k
  // non-synthetic.
1183
28.5k
  for (InputSectionBase *S : llvm::reverse(InputSections)) {
1184
28.5k
    SyntheticSection *SS = dyn_cast<SyntheticSection>(S);
1185
28.5k
    if (!SS)
1186
1.52k
      return;
1187
27.0k
    OutputSection *OS = SS->getParent();
1188
27.0k
    if (
!SS->empty() || 27.0k
!OS16.5k
)
1189
10.4k
      continue;
1190
16.5k
    
if (16.5k
(SS == InX::Got || 16.5k
SS == InX::MipsGot15.2k
) &&
ElfSym::GlobalOffsetTable1.30k
)
1191
3
      continue;
1192
16.5k
1193
16.5k
    std::vector<BaseCommand *>::iterator Empty = OS->Commands.end();
1194
33.0k
    for (auto I = OS->Commands.begin(), E = OS->Commands.end(); 
I != E33.0k
;
++I16.5k
) {
1195
16.5k
      BaseCommand *B = *I;
1196
16.5k
      if (auto *
ISD16.5k
= dyn_cast<InputSectionDescription>(B)) {
1197
16.5k
        llvm::erase_if(ISD->Sections,
1198
21.3k
                       [=](InputSection *IS) { return IS == SS; });
1199
16.5k
        if (ISD->Sections.empty())
1200
11.7k
          Empty = I;
1201
16.5k
      }
1202
16.5k
    }
1203
16.5k
    if (Empty != OS->Commands.end())
1204
11.7k
      OS->Commands.erase(Empty);
1205
16.5k
1206
16.5k
    // If there are no other sections in the output section, remove it from the
1207
16.5k
    // output.
1208
16.5k
    if (OS->Commands.empty())
1209
11.7k
      llvm::erase_if(Script->Opt.Commands,
1210
1.34M
                     [&](BaseCommand *Cmd) { return Cmd == OS; });
1211
28.5k
  }
1212
1.52k
}
1213
1214
// Returns true if a symbol can be replaced at load-time by a symbol
1215
// with the same name defined in other ELF executable or DSO.
1216
4.63k
static bool computeIsPreemptible(const SymbolBody &B) {
1217
4.63k
  assert(!B.isLocal());
1218
4.63k
  // Only symbols that appear in dynsym can be preempted.
1219
4.63k
  if (!B.symbol()->includeInDynsym())
1220
3.04k
    return false;
1221
1.58k
1222
1.58k
  // Only default visibility symbols can be preempted.
1223
1.58k
  
if (1.58k
B.symbol()->Visibility != STV_DEFAULT1.58k
)
1224
17
    return false;
1225
1.56k
1226
1.56k
  // At this point copy relocations have not been created yet, so any
1227
1.56k
  // symbol that is not defined locally is preemptible.
1228
1.56k
  
if (1.56k
!B.isInCurrentDSO()1.56k
)
1229
688
    return true;
1230
878
1231
878
  // If we have a dynamic list it specifies which local symbols are preemptible.
1232
878
  
if (878
Config->HasDynamicList878
)
1233
17
    return false;
1234
861
1235
861
  
if (861
!Config->Shared861
)
1236
64
    return false;
1237
797
1238
797
  // -Bsymbolic means that definitions are not preempted.
1239
797
  
if (797
Config->Bsymbolic || 797
(Config->BsymbolicFunctions && 792
B.isFunc()3
))
1240
8
    return false;
1241
789
  return true;
1242
789
}
1243
1244
// Create output section objects and add them to OutputSections.
1245
1.58k
template <class ELFT> void Writer<ELFT>::finalizeSections() {
1246
1.58k
  Out::DebugInfo = findSection(".debug_info");
1247
1.58k
  Out::PreinitArray = findSection(".preinit_array");
1248
1.58k
  Out::InitArray = findSection(".init_array");
1249
1.58k
  Out::FiniArray = findSection(".fini_array");
1250
1.58k
1251
1.58k
  // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1252
1.58k
  // symbols for sections, so that the runtime can get the start and end
1253
1.58k
  // addresses of each section by section name. Add such symbols.
1254
1.58k
  if (
!Config->Relocatable1.58k
) {
1255
1.52k
    addStartEndSymbols();
1256
1.52k
    for (BaseCommand *Base : Script->Opt.Commands)
1257
222k
      
if (auto *222k
Sec222k
= dyn_cast<OutputSection>(Base))
1258
221k
        addStartStopSymbols(Sec);
1259
1.52k
  }
1260
1.58k
1261
1.58k
  // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1262
1.58k
  // It should be okay as no one seems to care about the type.
1263
1.58k
  // Even the author of gold doesn't remember why gold behaves that way.
1264
1.58k
  // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1265
1.58k
  if (InX::DynSymTab)
1266
802
    addRegular<ELFT>("_DYNAMIC", InX::Dynamic, 0);
1267
1.58k
1268
1.58k
  // Define __rel[a]_iplt_{start,end} symbols if needed.
1269
1.58k
  addRelIpltSymbols();
1270
1.58k
1271
1.58k
  // This responsible for splitting up .eh_frame section into
1272
1.58k
  // pieces. The relocation scan uses those pieces, so this has to be
1273
1.58k
  // earlier.
1274
1.58k
  applySynthetic({In<ELFT>::EhFrame},
1275
79
                 [](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
1275
72
                 [](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
1275
3
                 [](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
1275
3
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::finalizeSections()::'lambda'(lld::elf::SyntheticSection*)::operator()(lld::elf::SyntheticSection*) const
Line
Count
Source
1275
1
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1276
1.58k
1277
1.58k
  for (Symbol *S : Symtab->getSymbols())
1278
4.63k
    S->body()->IsPreemptible |= computeIsPreemptible(*S->body());
1279
1.58k
1280
1.58k
  // Scan relocations. This must be done after every symbol is declared so that
1281
1.58k
  // we can correctly decide if a dynamic relocation is needed.
1282
1.58k
  if (!Config->Relocatable)
1283
1.52k
    forEachRelSec(scanRelocations<ELFT>);
1284
1.58k
1285
1.58k
  if (
InX::Plt && 1.58k
!InX::Plt->empty()1.58k
)
1286
132
    InX::Plt->addSymbols();
1287
1.58k
  if (
InX::Iplt && 1.58k
!InX::Iplt->empty()1.58k
)
1288
15
    InX::Iplt->addSymbols();
1289
1.58k
1290
1.58k
  // Now that we have defined all possible global symbols including linker-
1291
1.58k
  // synthesized ones. Visit all symbols to give the finishing touches.
1292
4.63k
  for (Symbol *S : Symtab->getSymbols()) {
1293
4.63k
    SymbolBody *Body = S->body();
1294
4.63k
1295
4.63k
    if (!includeInSymtab(*Body))
1296
351
      continue;
1297
4.28k
    
if (4.28k
InX::SymTab4.28k
)
1298
4.27k
      InX::SymTab->addSymbol(Body);
1299
4.28k
1300
4.28k
    if (
InX::DynSymTab && 4.28k
S->includeInDynsym()2.58k
) {
1301
1.29k
      InX::DynSymTab->addSymbol(Body);
1302
1.29k
      if (auto *SS = dyn_cast<SharedSymbol>(Body))
1303
236
        
if (236
cast<SharedFile<ELFT>>(S->File)->isNeeded()236
)
1304
233
          In<ELFT>::VerNeed->addSymbol(SS);
1305
1.29k
    }
1306
4.63k
  }
1307
1.58k
1308
1.58k
  // Do not proceed if there was an undefined symbol.
1309
1.58k
  if (ErrorCount)
1310
65
    return;
1311
1.52k
1312
1.52k
  addPredefinedSections();
1313
1.52k
  removeUnusedSyntheticSections();
1314
1.52k
1315
1.52k
  sortSections();
1316
1.52k
1317
1.52k
  // Now that we have the final list, create a list of all the
1318
1.52k
  // OutputSections for convenience.
1319
1.52k
  for (BaseCommand *Base : Script->Opt.Commands)
1320
210k
    
if (auto *210k
Sec210k
= dyn_cast<OutputSection>(Base))
1321
209k
      OutputSections.push_back(Sec);
1322
1.52k
1323
1.52k
  // Prefer command line supplied address over other constraints.
1324
209k
  for (OutputSection *Sec : OutputSections) {
1325
209k
    auto I = Config->SectionStartMap.find(Sec->Name);
1326
209k
    if (I != Config->SectionStartMap.end())
1327
42
      
Sec->AddrExpr = [=] 41
{ return I->second; }42
;
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::finalizeSections()::'lambda'()::operator()() const
Line
Count
Source
1327
34
      Sec->AddrExpr = [=] { return I->second; };
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::finalizeSections()::'lambda'()::operator()() const
Line
Count
Source
1327
6
      Sec->AddrExpr = [=] { return I->second; };
Unexecuted instantiation: Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::finalizeSections()::'lambda'()::operator()() const
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::finalizeSections()::'lambda'()::operator()() const
Line
Count
Source
1327
2
      Sec->AddrExpr = [=] { return I->second; };
1328
209k
  }
1329
1.52k
1330
1.52k
  // This is a bit of a hack. A value of 0 means undef, so we set it
1331
1.52k
  // to 1 t make __ehdr_start defined. The section number is not
1332
1.52k
  // particularly relevant.
1333
1.52k
  Out::ElfHeader->SectionIndex = 1;
1334
1.52k
1335
1.52k
  unsigned I = 1;
1336
209k
  for (OutputSection *Sec : OutputSections) {
1337
209k
    Sec->SectionIndex = I++;
1338
209k
    Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1339
209k
  }
1340
1.52k
1341
1.52k
  // Binary and relocatable output does not have PHDRS.
1342
1.52k
  // The headers have to be created before finalize as that can influence the
1343
1.52k
  // image base and the dynamic section on mips includes the image base.
1344
1.52k
  if (
!Config->Relocatable && 1.52k
!Config->OFormatBinary1.46k
) {
1345
1.46k
    Phdrs = Script->hasPhdrsCommands() ? 
Script->createPhdrs()22
:
createPhdrs()1.43k
;
1346
1.46k
    addPtArmExid(Phdrs);
1347
1.46k
    Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1348
1.46k
  }
1349
1.52k
1350
1.52k
  // Some symbols are defined in term of program headers. Now that we
1351
1.52k
  // have the headers, we can find out which sections they point to.
1352
1.52k
  setReservedSymbolSections();
1353
1.52k
1354
1.52k
  // Dynamic section must be the last one in this list and dynamic
1355
1.52k
  // symbol table section (DynSymTab) must be the first one.
1356
1.52k
  applySynthetic({InX::DynSymTab,    InX::Bss,
1357
1.52k
                  InX::BssRelRo,     InX::GnuHashTab,
1358
1.52k
                  In<ELFT>::HashTab, InX::SymTab,
1359
1.52k
                  InX::ShStrTab,     InX::StrTab,
1360
1.52k
                  In<ELFT>::VerDef,  InX::DynStrTab,
1361
1.52k
                  InX::Got,          InX::MipsGot,
1362
1.52k
                  InX::IgotPlt,      InX::GotPlt,
1363
1.52k
                  In<ELFT>::RelaDyn, In<ELFT>::RelaIplt,
1364
1.52k
                  In<ELFT>::RelaPlt, InX::Plt,
1365
1.52k
                  InX::Iplt,         In<ELFT>::EhFrameHdr,
1366
1.52k
                  In<ELFT>::VerSym,  In<ELFT>::VerNeed,
1367
1.52k
                  InX::Dynamic},
1368
8.52k
                 [](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
1368
6.48k
                 [](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
1368
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
1368
1.14k
                 [](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
1368
604
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1369
1.52k
1370
1.52k
  if (
!Script->Opt.HasSections && 1.52k
!Config->Relocatable1.24k
)
1371
1.18k
    fixSectionAlignments();
1372
1.52k
1373
1.52k
  // Some architectures use small displacements for jump instructions.
1374
1.52k
  // It is linker's responsibility to create thunks containing long
1375
1.52k
  // jump instructions if jump targets are too far. Create thunks.
1376
1.52k
  if (
Target->NeedsThunks1.52k
) {
1377
213
    // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented,
1378
213
    // these
1379
213
    // do not require address information. To support range extension Thunks
1380
213
    // we need to assign addresses so that we can tell if jump instructions
1381
213
    // are out of range. This will need to turn into a loop that converges
1382
213
    // when no more Thunks are added
1383
213
    ThunkCreator TC;
1384
213
    Script->assignAddresses();
1385
213
    if (
TC.createThunks(OutputSections)213
) {
1386
14
      applySynthetic({InX::MipsGot},
1387
7
                     [](SyntheticSection *SS) { SS->updateAllocSize(); });
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
1387
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
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
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
1388
14
      if (TC.createThunks(OutputSections))
1389
0
        fatal("All non-range thunks should be created in first call");
1390
1.52k
    }
1391
213
  }
1392
1.52k
1393
1.52k
  // Fill other section headers. The dynamic table is finalized
1394
1.52k
  // at the end because some tags like RELSZ depend on result
1395
1.52k
  // of finalizing other sections.
1396
1.52k
  for (OutputSection *Sec : OutputSections)
1397
209k
    Sec->finalize<ELFT>();
1398
1.52k
1399
1.52k
  // createThunks may have added local symbols to the static symbol table
1400
1.52k
  applySynthetic({InX::SymTab, InX::ShStrTab, InX::StrTab},
1401
4.56k
                 [](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
1401
279
                 [](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
1401
561
                 [](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
1401
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
1401
3.59k
                 [](SyntheticSection *SS) { SS->postThunkContents(); });
1402
1.58k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, true> >::finalizeSections()
Line
Count
Source
1245
44
template <class ELFT> void Writer<ELFT>::finalizeSections() {
1246
44
  Out::DebugInfo = findSection(".debug_info");
1247
44
  Out::PreinitArray = findSection(".preinit_array");
1248
44
  Out::InitArray = findSection(".init_array");
1249
44
  Out::FiniArray = findSection(".fini_array");
1250
44
1251
44
  // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1252
44
  // symbols for sections, so that the runtime can get the start and end
1253
44
  // addresses of each section by section name. Add such symbols.
1254
44
  if (
!Config->Relocatable44
) {
1255
43
    addStartEndSymbols();
1256
43
    for (BaseCommand *Base : Script->Opt.Commands)
1257
858
      
if (auto *858
Sec858
= dyn_cast<OutputSection>(Base))
1258
816
        addStartStopSymbols(Sec);
1259
43
  }
1260
44
1261
44
  // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1262
44
  // It should be okay as no one seems to care about the type.
1263
44
  // Even the author of gold doesn't remember why gold behaves that way.
1264
44
  // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1265
44
  if (InX::DynSymTab)
1266
25
    addRegular<ELFT>("_DYNAMIC", InX::Dynamic, 0);
1267
44
1268
44
  // Define __rel[a]_iplt_{start,end} symbols if needed.
1269
44
  addRelIpltSymbols();
1270
44
1271
44
  // This responsible for splitting up .eh_frame section into
1272
44
  // pieces. The relocation scan uses those pieces, so this has to be
1273
44
  // earlier.
1274
44
  applySynthetic({In<ELFT>::EhFrame},
1275
44
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1276
44
1277
44
  for (Symbol *S : Symtab->getSymbols())
1278
180
    S->body()->IsPreemptible |= computeIsPreemptible(*S->body());
1279
44
1280
44
  // Scan relocations. This must be done after every symbol is declared so that
1281
44
  // we can correctly decide if a dynamic relocation is needed.
1282
44
  if (!Config->Relocatable)
1283
43
    forEachRelSec(scanRelocations<ELFT>);
1284
44
1285
44
  if (
InX::Plt && 44
!InX::Plt->empty()44
)
1286
2
    InX::Plt->addSymbols();
1287
44
  if (
InX::Iplt && 44
!InX::Iplt->empty()44
)
1288
0
    InX::Iplt->addSymbols();
1289
44
1290
44
  // Now that we have defined all possible global symbols including linker-
1291
44
  // synthesized ones. Visit all symbols to give the finishing touches.
1292
180
  for (Symbol *S : Symtab->getSymbols()) {
1293
180
    SymbolBody *Body = S->body();
1294
180
1295
180
    if (!includeInSymtab(*Body))
1296
9
      continue;
1297
171
    
if (171
InX::SymTab171
)
1298
171
      InX::SymTab->addSymbol(Body);
1299
171
1300
171
    if (
InX::DynSymTab && 171
S->includeInDynsym()106
) {
1301
47
      InX::DynSymTab->addSymbol(Body);
1302
47
      if (auto *SS = dyn_cast<SharedSymbol>(Body))
1303
8
        
if (8
cast<SharedFile<ELFT>>(S->File)->isNeeded()8
)
1304
8
          In<ELFT>::VerNeed->addSymbol(SS);
1305
47
    }
1306
180
  }
1307
44
1308
44
  // Do not proceed if there was an undefined symbol.
1309
44
  if (ErrorCount)
1310
0
    return;
1311
44
1312
44
  addPredefinedSections();
1313
44
  removeUnusedSyntheticSections();
1314
44
1315
44
  sortSections();
1316
44
1317
44
  // Now that we have the final list, create a list of all the
1318
44
  // OutputSections for convenience.
1319
44
  for (BaseCommand *Base : Script->Opt.Commands)
1320
572
    
if (auto *572
Sec572
= dyn_cast<OutputSection>(Base))
1321
529
      OutputSections.push_back(Sec);
1322
44
1323
44
  // Prefer command line supplied address over other constraints.
1324
529
  for (OutputSection *Sec : OutputSections) {
1325
529
    auto I = Config->SectionStartMap.find(Sec->Name);
1326
529
    if (I != Config->SectionStartMap.end())
1327
1
      Sec->AddrExpr = [=] { return I->second; };
1328
529
  }
1329
44
1330
44
  // This is a bit of a hack. A value of 0 means undef, so we set it
1331
44
  // to 1 t make __ehdr_start defined. The section number is not
1332
44
  // particularly relevant.
1333
44
  Out::ElfHeader->SectionIndex = 1;
1334
44
1335
44
  unsigned I = 1;
1336
529
  for (OutputSection *Sec : OutputSections) {
1337
529
    Sec->SectionIndex = I++;
1338
529
    Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1339
529
  }
1340
44
1341
44
  // Binary and relocatable output does not have PHDRS.
1342
44
  // The headers have to be created before finalize as that can influence the
1343
44
  // image base and the dynamic section on mips includes the image base.
1344
44
  if (
!Config->Relocatable && 44
!Config->OFormatBinary43
) {
1345
43
    Phdrs = Script->hasPhdrsCommands() ? 
Script->createPhdrs()0
:
createPhdrs()43
;
1346
43
    addPtArmExid(Phdrs);
1347
43
    Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1348
43
  }
1349
44
1350
44
  // Some symbols are defined in term of program headers. Now that we
1351
44
  // have the headers, we can find out which sections they point to.
1352
44
  setReservedSymbolSections();
1353
44
1354
44
  // Dynamic section must be the last one in this list and dynamic
1355
44
  // symbol table section (DynSymTab) must be the first one.
1356
44
  applySynthetic({InX::DynSymTab,    InX::Bss,
1357
44
                  InX::BssRelRo,     InX::GnuHashTab,
1358
44
                  In<ELFT>::HashTab, InX::SymTab,
1359
44
                  InX::ShStrTab,     InX::StrTab,
1360
44
                  In<ELFT>::VerDef,  InX::DynStrTab,
1361
44
                  InX::Got,          InX::MipsGot,
1362
44
                  InX::IgotPlt,      InX::GotPlt,
1363
44
                  In<ELFT>::RelaDyn, In<ELFT>::RelaIplt,
1364
44
                  In<ELFT>::RelaPlt, InX::Plt,
1365
44
                  InX::Iplt,         In<ELFT>::EhFrameHdr,
1366
44
                  In<ELFT>::VerSym,  In<ELFT>::VerNeed,
1367
44
                  InX::Dynamic},
1368
44
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1369
44
1370
44
  if (
!Script->Opt.HasSections && 44
!Config->Relocatable42
)
1371
41
    fixSectionAlignments();
1372
44
1373
44
  // Some architectures use small displacements for jump instructions.
1374
44
  // It is linker's responsibility to create thunks containing long
1375
44
  // jump instructions if jump targets are too far. Create thunks.
1376
44
  if (
Target->NeedsThunks44
) {
1377
28
    // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented,
1378
28
    // these
1379
28
    // do not require address information. To support range extension Thunks
1380
28
    // we need to assign addresses so that we can tell if jump instructions
1381
28
    // are out of range. This will need to turn into a loop that converges
1382
28
    // when no more Thunks are added
1383
28
    ThunkCreator TC;
1384
28
    Script->assignAddresses();
1385
28
    if (
TC.createThunks(OutputSections)28
) {
1386
0
      applySynthetic({InX::MipsGot},
1387
0
                     [](SyntheticSection *SS) { SS->updateAllocSize(); });
1388
0
      if (TC.createThunks(OutputSections))
1389
0
        fatal("All non-range thunks should be created in first call");
1390
44
    }
1391
28
  }
1392
44
1393
44
  // Fill other section headers. The dynamic table is finalized
1394
44
  // at the end because some tags like RELSZ depend on result
1395
44
  // of finalizing other sections.
1396
44
  for (OutputSection *Sec : OutputSections)
1397
529
    Sec->finalize<ELFT>();
1398
44
1399
44
  // createThunks may have added local symbols to the static symbol table
1400
44
  applySynthetic({InX::SymTab, InX::ShStrTab, InX::StrTab},
1401
44
                 [](SyntheticSection *SS) { SS->postThunkContents(); });
1402
44
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, false> >::finalizeSections()
Line
Count
Source
1245
191
template <class ELFT> void Writer<ELFT>::finalizeSections() {
1246
191
  Out::DebugInfo = findSection(".debug_info");
1247
191
  Out::PreinitArray = findSection(".preinit_array");
1248
191
  Out::InitArray = findSection(".init_array");
1249
191
  Out::FiniArray = findSection(".fini_array");
1250
191
1251
191
  // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1252
191
  // symbols for sections, so that the runtime can get the start and end
1253
191
  // addresses of each section by section name. Add such symbols.
1254
191
  if (
!Config->Relocatable191
) {
1255
185
    addStartEndSymbols();
1256
185
    for (BaseCommand *Base : Script->Opt.Commands)
1257
3.37k
      
if (auto *3.37k
Sec3.37k
= dyn_cast<OutputSection>(Base))
1258
3.20k
        addStartStopSymbols(Sec);
1259
185
  }
1260
191
1261
191
  // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1262
191
  // It should be okay as no one seems to care about the type.
1263
191
  // Even the author of gold doesn't remember why gold behaves that way.
1264
191
  // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1265
191
  if (InX::DynSymTab)
1266
106
    addRegular<ELFT>("_DYNAMIC", InX::Dynamic, 0);
1267
191
1268
191
  // Define __rel[a]_iplt_{start,end} symbols if needed.
1269
191
  addRelIpltSymbols();
1270
191
1271
191
  // This responsible for splitting up .eh_frame section into
1272
191
  // pieces. The relocation scan uses those pieces, so this has to be
1273
191
  // earlier.
1274
191
  applySynthetic({In<ELFT>::EhFrame},
1275
191
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1276
191
1277
191
  for (Symbol *S : Symtab->getSymbols())
1278
629
    S->body()->IsPreemptible |= computeIsPreemptible(*S->body());
1279
191
1280
191
  // Scan relocations. This must be done after every symbol is declared so that
1281
191
  // we can correctly decide if a dynamic relocation is needed.
1282
191
  if (!Config->Relocatable)
1283
185
    forEachRelSec(scanRelocations<ELFT>);
1284
191
1285
191
  if (
InX::Plt && 191
!InX::Plt->empty()191
)
1286
24
    InX::Plt->addSymbols();
1287
191
  if (
InX::Iplt && 191
!InX::Iplt->empty()191
)
1288
6
    InX::Iplt->addSymbols();
1289
191
1290
191
  // Now that we have defined all possible global symbols including linker-
1291
191
  // synthesized ones. Visit all symbols to give the finishing touches.
1292
629
  for (Symbol *S : Symtab->getSymbols()) {
1293
629
    SymbolBody *Body = S->body();
1294
629
1295
629
    if (!includeInSymtab(*Body))
1296
31
      continue;
1297
598
    
if (598
InX::SymTab598
)
1298
598
      InX::SymTab->addSymbol(Body);
1299
598
1300
598
    if (
InX::DynSymTab && 598
S->includeInDynsym()374
) {
1301
191
      InX::DynSymTab->addSymbol(Body);
1302
191
      if (auto *SS = dyn_cast<SharedSymbol>(Body))
1303
52
        
if (52
cast<SharedFile<ELFT>>(S->File)->isNeeded()52
)
1304
50
          In<ELFT>::VerNeed->addSymbol(SS);
1305
191
    }
1306
629
  }
1307
191
1308
191
  // Do not proceed if there was an undefined symbol.
1309
191
  if (ErrorCount)
1310
4
    return;
1311
187
1312
187
  addPredefinedSections();
1313
187
  removeUnusedSyntheticSections();
1314
187
1315
187
  sortSections();
1316
187
1317
187
  // Now that we have the final list, create a list of all the
1318
187
  // OutputSections for convenience.
1319
187
  for (BaseCommand *Base : Script->Opt.Commands)
1320
1.94k
    
if (auto *1.94k
Sec1.94k
= dyn_cast<OutputSection>(Base))
1321
1.76k
      OutputSections.push_back(Sec);
1322
187
1323
187
  // Prefer command line supplied address over other constraints.
1324
1.76k
  for (OutputSection *Sec : OutputSections) {
1325
1.76k
    auto I = Config->SectionStartMap.find(Sec->Name);
1326
1.76k
    if (I != Config->SectionStartMap.end())
1327
6
      Sec->AddrExpr = [=] { return I->second; };
1328
1.76k
  }
1329
187
1330
187
  // This is a bit of a hack. A value of 0 means undef, so we set it
1331
187
  // to 1 t make __ehdr_start defined. The section number is not
1332
187
  // particularly relevant.
1333
187
  Out::ElfHeader->SectionIndex = 1;
1334
187
1335
187
  unsigned I = 1;
1336
1.76k
  for (OutputSection *Sec : OutputSections) {
1337
1.76k
    Sec->SectionIndex = I++;
1338
1.76k
    Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1339
1.76k
  }
1340
187
1341
187
  // Binary and relocatable output does not have PHDRS.
1342
187
  // The headers have to be created before finalize as that can influence the
1343
187
  // image base and the dynamic section on mips includes the image base.
1344
187
  if (
!Config->Relocatable && 187
!Config->OFormatBinary181
) {
1345
181
    Phdrs = Script->hasPhdrsCommands() ? 
Script->createPhdrs()5
:
createPhdrs()176
;
1346
181
    addPtArmExid(Phdrs);
1347
181
    Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1348
181
  }
1349
187
1350
187
  // Some symbols are defined in term of program headers. Now that we
1351
187
  // have the headers, we can find out which sections they point to.
1352
187
  setReservedSymbolSections();
1353
187
1354
187
  // Dynamic section must be the last one in this list and dynamic
1355
187
  // symbol table section (DynSymTab) must be the first one.
1356
187
  applySynthetic({InX::DynSymTab,    InX::Bss,
1357
187
                  InX::BssRelRo,     InX::GnuHashTab,
1358
187
                  In<ELFT>::HashTab, InX::SymTab,
1359
187
                  InX::ShStrTab,     InX::StrTab,
1360
187
                  In<ELFT>::VerDef,  InX::DynStrTab,
1361
187
                  InX::Got,          InX::MipsGot,
1362
187
                  InX::IgotPlt,      InX::GotPlt,
1363
187
                  In<ELFT>::RelaDyn, In<ELFT>::RelaIplt,
1364
187
                  In<ELFT>::RelaPlt, InX::Plt,
1365
187
                  InX::Iplt,         In<ELFT>::EhFrameHdr,
1366
187
                  In<ELFT>::VerSym,  In<ELFT>::VerNeed,
1367
187
                  InX::Dynamic},
1368
187
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1369
187
1370
187
  if (
!Script->Opt.HasSections && 187
!Config->Relocatable170
)
1371
164
    fixSectionAlignments();
1372
187
1373
187
  // Some architectures use small displacements for jump instructions.
1374
187
  // It is linker's responsibility to create thunks containing long
1375
187
  // jump instructions if jump targets are too far. Create thunks.
1376
187
  if (
Target->NeedsThunks187
) {
1377
92
    // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented,
1378
92
    // these
1379
92
    // do not require address information. To support range extension Thunks
1380
92
    // we need to assign addresses so that we can tell if jump instructions
1381
92
    // are out of range. This will need to turn into a loop that converges
1382
92
    // when no more Thunks are added
1383
92
    ThunkCreator TC;
1384
92
    Script->assignAddresses();
1385
92
    if (
TC.createThunks(OutputSections)92
) {
1386
7
      applySynthetic({InX::MipsGot},
1387
7
                     [](SyntheticSection *SS) { SS->updateAllocSize(); });
1388
7
      if (TC.createThunks(OutputSections))
1389
0
        fatal("All non-range thunks should be created in first call");
1390
187
    }
1391
92
  }
1392
187
1393
187
  // Fill other section headers. The dynamic table is finalized
1394
187
  // at the end because some tags like RELSZ depend on result
1395
187
  // of finalizing other sections.
1396
187
  for (OutputSection *Sec : OutputSections)
1397
1.76k
    Sec->finalize<ELFT>();
1398
191
1399
191
  // createThunks may have added local symbols to the static symbol table
1400
191
  applySynthetic({InX::SymTab, InX::ShStrTab, InX::StrTab},
1401
191
                 [](SyntheticSection *SS) { SS->postThunkContents(); });
1402
191
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)1, true> >::finalizeSections()
Line
Count
Source
1245
1.25k
template <class ELFT> void Writer<ELFT>::finalizeSections() {
1246
1.25k
  Out::DebugInfo = findSection(".debug_info");
1247
1.25k
  Out::PreinitArray = findSection(".preinit_array");
1248
1.25k
  Out::InitArray = findSection(".init_array");
1249
1.25k
  Out::FiniArray = findSection(".fini_array");
1250
1.25k
1251
1.25k
  // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1252
1.25k
  // symbols for sections, so that the runtime can get the start and end
1253
1.25k
  // addresses of each section by section name. Add such symbols.
1254
1.25k
  if (
!Config->Relocatable1.25k
) {
1255
1.21k
    addStartEndSymbols();
1256
1.21k
    for (BaseCommand *Base : Script->Opt.Commands)
1257
216k
      
if (auto *216k
Sec216k
= dyn_cast<OutputSection>(Base))
1258
215k
        addStartStopSymbols(Sec);
1259
1.21k
  }
1260
1.25k
1261
1.25k
  // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1262
1.25k
  // It should be okay as no one seems to care about the type.
1263
1.25k
  // Even the author of gold doesn't remember why gold behaves that way.
1264
1.25k
  // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1265
1.25k
  if (InX::DynSymTab)
1266
617
    addRegular<ELFT>("_DYNAMIC", InX::Dynamic, 0);
1267
1.25k
1268
1.25k
  // Define __rel[a]_iplt_{start,end} symbols if needed.
1269
1.25k
  addRelIpltSymbols();
1270
1.25k
1271
1.25k
  // This responsible for splitting up .eh_frame section into
1272
1.25k
  // pieces. The relocation scan uses those pieces, so this has to be
1273
1.25k
  // earlier.
1274
1.25k
  applySynthetic({In<ELFT>::EhFrame},
1275
1.25k
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1276
1.25k
1277
1.25k
  for (Symbol *S : Symtab->getSymbols())
1278
3.36k
    S->body()->IsPreemptible |= computeIsPreemptible(*S->body());
1279
1.25k
1280
1.25k
  // Scan relocations. This must be done after every symbol is declared so that
1281
1.25k
  // we can correctly decide if a dynamic relocation is needed.
1282
1.25k
  if (!Config->Relocatable)
1283
1.21k
    forEachRelSec(scanRelocations<ELFT>);
1284
1.25k
1285
1.25k
  if (
InX::Plt && 1.25k
!InX::Plt->empty()1.25k
)
1286
100
    InX::Plt->addSymbols();
1287
1.25k
  if (
InX::Iplt && 1.25k
!InX::Iplt->empty()1.25k
)
1288
9
    InX::Iplt->addSymbols();
1289
1.25k
1290
1.25k
  // Now that we have defined all possible global symbols including linker-
1291
1.25k
  // synthesized ones. Visit all symbols to give the finishing touches.
1292
3.36k
  for (Symbol *S : Symtab->getSymbols()) {
1293
3.36k
    SymbolBody *Body = S->body();
1294
3.36k
1295
3.36k
    if (!includeInSymtab(*Body))
1296
270
      continue;
1297
3.09k
    
if (3.09k
InX::SymTab3.09k
)
1298
3.09k
      InX::SymTab->addSymbol(Body);
1299
3.09k
1300
3.09k
    if (
InX::DynSymTab && 3.09k
S->includeInDynsym()1.85k
) {
1301
935
      InX::DynSymTab->addSymbol(Body);
1302
935
      if (auto *SS = dyn_cast<SharedSymbol>(Body))
1303
156
        
if (156
cast<SharedFile<ELFT>>(S->File)->isNeeded()156
)
1304
155
          In<ELFT>::VerNeed->addSymbol(SS);
1305
935
    }
1306
3.36k
  }
1307
1.25k
1308
1.25k
  // Do not proceed if there was an undefined symbol.
1309
1.25k
  if (ErrorCount)
1310
59
    return;
1311
1.20k
1312
1.20k
  addPredefinedSections();
1313
1.20k
  removeUnusedSyntheticSections();
1314
1.20k
1315
1.20k
  sortSections();
1316
1.20k
1317
1.20k
  // Now that we have the final list, create a list of all the
1318
1.20k
  // OutputSections for convenience.
1319
1.20k
  for (BaseCommand *Base : Script->Opt.Commands)
1320
206k
    
if (auto *206k
Sec206k
= dyn_cast<OutputSection>(Base))
1321
205k
      OutputSections.push_back(Sec);
1322
1.20k
1323
1.20k
  // Prefer command line supplied address over other constraints.
1324
205k
  for (OutputSection *Sec : OutputSections) {
1325
205k
    auto I = Config->SectionStartMap.find(Sec->Name);
1326
205k
    if (I != Config->SectionStartMap.end())
1327
34
      Sec->AddrExpr = [=] { return I->second; };
1328
205k
  }
1329
1.20k
1330
1.20k
  // This is a bit of a hack. A value of 0 means undef, so we set it
1331
1.20k
  // to 1 t make __ehdr_start defined. The section number is not
1332
1.20k
  // particularly relevant.
1333
1.20k
  Out::ElfHeader->SectionIndex = 1;
1334
1.20k
1335
1.20k
  unsigned I = 1;
1336
205k
  for (OutputSection *Sec : OutputSections) {
1337
205k
    Sec->SectionIndex = I++;
1338
205k
    Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1339
205k
  }
1340
1.20k
1341
1.20k
  // Binary and relocatable output does not have PHDRS.
1342
1.20k
  // The headers have to be created before finalize as that can influence the
1343
1.20k
  // image base and the dynamic section on mips includes the image base.
1344
1.20k
  if (
!Config->Relocatable && 1.20k
!Config->OFormatBinary1.15k
) {
1345
1.15k
    Phdrs = Script->hasPhdrsCommands() ? 
Script->createPhdrs()17
:
createPhdrs()1.13k
;
1346
1.15k
    addPtArmExid(Phdrs);
1347
1.15k
    Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1348
1.15k
  }
1349
1.20k
1350
1.20k
  // Some symbols are defined in term of program headers. Now that we
1351
1.20k
  // have the headers, we can find out which sections they point to.
1352
1.20k
  setReservedSymbolSections();
1353
1.20k
1354
1.20k
  // Dynamic section must be the last one in this list and dynamic
1355
1.20k
  // symbol table section (DynSymTab) must be the first one.
1356
1.20k
  applySynthetic({InX::DynSymTab,    InX::Bss,
1357
1.20k
                  InX::BssRelRo,     InX::GnuHashTab,
1358
1.20k
                  In<ELFT>::HashTab, InX::SymTab,
1359
1.20k
                  InX::ShStrTab,     InX::StrTab,
1360
1.20k
                  In<ELFT>::VerDef,  InX::DynStrTab,
1361
1.20k
                  InX::Got,          InX::MipsGot,
1362
1.20k
                  InX::IgotPlt,      InX::GotPlt,
1363
1.20k
                  In<ELFT>::RelaDyn, In<ELFT>::RelaIplt,
1364
1.20k
                  In<ELFT>::RelaPlt, InX::Plt,
1365
1.20k
                  InX::Iplt,         In<ELFT>::EhFrameHdr,
1366
1.20k
                  In<ELFT>::VerSym,  In<ELFT>::VerNeed,
1367
1.20k
                  InX::Dynamic},
1368
1.20k
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1369
1.20k
1370
1.20k
  if (
!Script->Opt.HasSections && 1.20k
!Config->Relocatable943
)
1371
899
    fixSectionAlignments();
1372
1.20k
1373
1.20k
  // Some architectures use small displacements for jump instructions.
1374
1.20k
  // It is linker's responsibility to create thunks containing long
1375
1.20k
  // jump instructions if jump targets are too far. Create thunks.
1376
1.20k
  if (
Target->NeedsThunks1.20k
) {
1377
2
    // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented,
1378
2
    // these
1379
2
    // do not require address information. To support range extension Thunks
1380
2
    // we need to assign addresses so that we can tell if jump instructions
1381
2
    // are out of range. This will need to turn into a loop that converges
1382
2
    // when no more Thunks are added
1383
2
    ThunkCreator TC;
1384
2
    Script->assignAddresses();
1385
2
    if (
TC.createThunks(OutputSections)2
) {
1386
0
      applySynthetic({InX::MipsGot},
1387
0
                     [](SyntheticSection *SS) { SS->updateAllocSize(); });
1388
0
      if (TC.createThunks(OutputSections))
1389
0
        fatal("All non-range thunks should be created in first call");
1390
1.20k
    }
1391
2
  }
1392
1.20k
1393
1.20k
  // Fill other section headers. The dynamic table is finalized
1394
1.20k
  // at the end because some tags like RELSZ depend on result
1395
1.20k
  // of finalizing other sections.
1396
1.20k
  for (OutputSection *Sec : OutputSections)
1397
205k
    Sec->finalize<ELFT>();
1398
1.25k
1399
1.25k
  // createThunks may have added local symbols to the static symbol table
1400
1.25k
  applySynthetic({InX::SymTab, InX::ShStrTab, InX::StrTab},
1401
1.25k
                 [](SyntheticSection *SS) { SS->postThunkContents(); });
1402
1.25k
}
Writer.cpp:(anonymous namespace)::Writer<llvm::object::ELFType<(llvm::support::endianness)0, false> >::finalizeSections()
Line
Count
Source
1245
95
template <class ELFT> void Writer<ELFT>::finalizeSections() {
1246
95
  Out::DebugInfo = findSection(".debug_info");
1247
95
  Out::PreinitArray = findSection(".preinit_array");
1248
95
  Out::InitArray = findSection(".init_array");
1249
95
  Out::FiniArray = findSection(".fini_array");
1250
95
1251
95
  // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1252
95
  // symbols for sections, so that the runtime can get the start and end
1253
95
  // addresses of each section by section name. Add such symbols.
1254
95
  if (
!Config->Relocatable95
) {
1255
87
    addStartEndSymbols();
1256
87
    for (BaseCommand *Base : Script->Opt.Commands)
1257
1.79k
      
if (auto *1.79k
Sec1.79k
= dyn_cast<OutputSection>(Base))
1258
1.71k
        addStartStopSymbols(Sec);
1259
87
  }
1260
95
1261
95
  // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1262
95
  // It should be okay as no one seems to care about the type.
1263
95
  // Even the author of gold doesn't remember why gold behaves that way.
1264
95
  // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1265
95
  if (InX::DynSymTab)
1266
54
    addRegular<ELFT>("_DYNAMIC", InX::Dynamic, 0);
1267
95
1268
95
  // Define __rel[a]_iplt_{start,end} symbols if needed.
1269
95
  addRelIpltSymbols();
1270
95
1271
95
  // This responsible for splitting up .eh_frame section into
1272
95
  // pieces. The relocation scan uses those pieces, so this has to be
1273
95
  // earlier.
1274
95
  applySynthetic({In<ELFT>::EhFrame},
1275
95
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1276
95
1277
95
  for (Symbol *S : Symtab->getSymbols())
1278
457
    S->body()->IsPreemptible |= computeIsPreemptible(*S->body());
1279
95
1280
95
  // Scan relocations. This must be done after every symbol is declared so that
1281
95
  // we can correctly decide if a dynamic relocation is needed.
1282
95
  if (!Config->Relocatable)
1283
87
    forEachRelSec(scanRelocations<ELFT>);
1284
95
1285
95
  if (
InX::Plt && 95
!InX::Plt->empty()95
)
1286
6
    InX::Plt->addSymbols();
1287
95
  if (
InX::Iplt && 95
!InX::Iplt->empty()95
)
1288
0
    InX::Iplt->addSymbols();
1289
95
1290
95
  // Now that we have defined all possible global symbols including linker-
1291
95
  // synthesized ones. Visit all symbols to give the finishing touches.
1292
457
  for (Symbol *S : Symtab->getSymbols()) {
1293
457
    SymbolBody *Body = S->body();
1294
457
1295
457
    if (!includeInSymtab(*Body))
1296
41
      continue;
1297
416
    
if (416
InX::SymTab416
)
1298
416
      InX::SymTab->addSymbol(Body);
1299
416
1300
416
    if (
InX::DynSymTab && 416
S->includeInDynsym()255
) {
1301
123
      InX::DynSymTab->addSymbol(Body);
1302
123
      if (auto *SS = dyn_cast<SharedSymbol>(Body))
1303
20
        
if (20
cast<SharedFile<ELFT>>(S->File)->isNeeded()20
)
1304
20
          In<ELFT>::VerNeed->addSymbol(SS);
1305
123
    }
1306
457
  }
1307
95
1308
95
  // Do not proceed if there was an undefined symbol.
1309
95
  if (ErrorCount)
1310
2
    return;
1311
93
1312
93
  addPredefinedSections();
1313
93
  removeUnusedSyntheticSections();
1314
93
1315
93
  sortSections();
1316
93
1317
93
  // Now that we have the final list, create a list of all the
1318
93
  // OutputSections for convenience.
1319
93
  for (BaseCommand *Base : Script->Opt.Commands)
1320
1.27k
    
if (auto *1.27k
Sec1.27k
= dyn_cast<OutputSection>(Base))
1321
1.19k
      OutputSections.push_back(Sec);
1322
93
1323
93
  // Prefer command line supplied address over other constraints.
1324
1.19k
  for (OutputSection *Sec : OutputSections) {
1325
1.19k
    auto I = Config->SectionStartMap.find(Sec->Name);
1326
1.19k
    if (I != Config->SectionStartMap.end())
1327
0
      Sec->AddrExpr = [=] { return I->second; };
1328
1.19k
  }
1329
93
1330
93
  // This is a bit of a hack. A value of 0 means undef, so we set it
1331
93
  // to 1 t make __ehdr_start defined. The section number is not
1332
93
  // particularly relevant.
1333
93
  Out::ElfHeader->SectionIndex = 1;
1334
93
1335
93
  unsigned I = 1;
1336
1.19k
  for (OutputSection *Sec : OutputSections) {
1337
1.19k
    Sec->SectionIndex = I++;
1338
1.19k
    Sec->ShName = InX::ShStrTab->addString(Sec->Name);
1339
1.19k
  }
1340
93
1341
93
  // Binary and relocatable output does not have PHDRS.
1342
93
  // The headers have to be created before finalize as that can influence the
1343
93
  // image base and the dynamic section on mips includes the image base.
1344
93
  if (
!Config->Relocatable && 93
!Config->OFormatBinary86
) {
1345
86
    Phdrs = Script->hasPhdrsCommands() ? 
Script->createPhdrs()0
:
createPhdrs()86
;
1346
86
    addPtArmExid(Phdrs);
1347
86
    Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1348
86
  }
1349
93
1350
93
  // Some symbols are defined in term of program headers. Now that we
1351
93
  // have the headers, we can find out which sections they point to.
1352
93
  setReservedSymbolSections();
1353
93
1354
93
  // Dynamic section must be the last one in this list and dynamic
1355
93
  // symbol table section (DynSymTab) must be the first one.
1356
93
  applySynthetic({InX::DynSymTab,    InX::Bss,
1357
93
                  InX::BssRelRo,     InX::GnuHashTab,
1358
93
                  In<ELFT>::HashTab, InX::SymTab,
1359
93
                  InX::ShStrTab,     InX::StrTab,
1360
93
                  In<ELFT>::VerDef,  InX::DynStrTab,
1361
93
                  InX::Got,          InX::MipsGot,
1362
93
                  InX::IgotPlt,      InX::GotPlt,
1363
93
                  In<ELFT>::RelaDyn, In<ELFT>::RelaIplt,
1364
93
                  In<ELFT>::RelaPlt, InX::Plt,
1365
93
                  InX::Iplt,         In<ELFT>::EhFrameHdr,
1366
93
                  In<ELFT>::VerSym,  In<ELFT>::VerNeed,
1367
93
                  InX::Dynamic},
1368
93
                 [](SyntheticSection *SS) { SS->finalizeContents(); });
1369
93
1370
93
  if (
!Script->Opt.HasSections && 93
!Config->Relocatable86
)
1371
79
    fixSectionAlignments();
1372
93
1373
93
  // Some architectures use small displacements for jump instructions.
1374
93
  // It is linker's responsibility to create thunks containing long
1375
93
  // jump instructions if jump targets are too far. Create thunks.
1376
93
  if (
Target->NeedsThunks93
) {
1377
91
    // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented,
1378
91
    // these
1379
91
    // do not require address information. To support range extension Thunks
1380
91
    // we need to assign addresses so that we can tell if jump instructions
1381
91
    // are out of range. This will need to turn into a loop that converges
1382
91
    // when no more Thunks are added
1383
91
    ThunkCreator TC;
1384
91
    Script->assignAddresses();
1385
91
    if (
TC.createThunks(OutputSections)91
) {
1386
7
      applySynthetic({InX::MipsGot},
1387
7
                     [](SyntheticSection *SS) { SS->updateAllocSize(); });
1388
7
      if (TC.createThunks(OutputSections))
1389
0
        fatal("All non-range thunks should be created in first call");
1390
93