Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/ELF/InputFiles.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- InputFiles.cpp -----------------------------------------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
9
#include "InputFiles.h"
10
#include "Driver.h"
11
#include "InputSection.h"
12
#include "LinkerScript.h"
13
#include "SymbolTable.h"
14
#include "Symbols.h"
15
#include "SyntheticSections.h"
16
#include "lld/Common/ErrorHandler.h"
17
#include "lld/Common/Memory.h"
18
#include "llvm/ADT/STLExtras.h"
19
#include "llvm/CodeGen/Analysis.h"
20
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
21
#include "llvm/IR/LLVMContext.h"
22
#include "llvm/IR/Module.h"
23
#include "llvm/LTO/LTO.h"
24
#include "llvm/MC/StringTableBuilder.h"
25
#include "llvm/Object/ELFObjectFile.h"
26
#include "llvm/Support/ARMAttributeParser.h"
27
#include "llvm/Support/ARMBuildAttributes.h"
28
#include "llvm/Support/Endian.h"
29
#include "llvm/Support/Path.h"
30
#include "llvm/Support/TarWriter.h"
31
#include "llvm/Support/raw_ostream.h"
32
33
using namespace llvm;
34
using namespace llvm::ELF;
35
using namespace llvm::object;
36
using namespace llvm::sys;
37
using namespace llvm::sys::fs;
38
using namespace llvm::support::endian;
39
40
using namespace lld;
41
using namespace lld::elf;
42
43
bool InputFile::isInGroup;
44
uint32_t InputFile::nextGroupId;
45
std::vector<BinaryFile *> elf::binaryFiles;
46
std::vector<BitcodeFile *> elf::bitcodeFiles;
47
std::vector<LazyObjFile *> elf::lazyObjFiles;
48
std::vector<InputFile *> elf::objectFiles;
49
std::vector<SharedFile *> elf::sharedFiles;
50
51
std::unique_ptr<TarWriter> elf::tar;
52
53
7.65k
static ELFKind getELFKind(MemoryBufferRef mb, StringRef archiveName) {
54
7.65k
  unsigned char size;
55
7.65k
  unsigned char endian;
56
7.65k
  std::tie(size, endian) = getElfArchType(mb.getBuffer());
57
7.65k
58
7.65k
  auto report = [&](StringRef msg) {
59
0
    StringRef filename = mb.getBufferIdentifier();
60
0
    if (archiveName.empty())
61
0
      fatal(filename + ": " + msg);
62
0
    else
63
0
      fatal(archiveName + "(" + filename + "): " + msg);
64
0
  };
65
7.65k
66
7.65k
  if (!mb.getBuffer().startswith(ElfMagic))
67
0
    report("not an ELF file");
68
7.65k
  if (endian != ELFDATA2LSB && 
endian != ELFDATA2MSB744
)
69
0
    report("corrupted ELF file: invalid data encoding");
70
7.65k
  if (size != ELFCLASS32 && 
size != ELFCLASS646.20k
)
71
0
    report("corrupted ELF file: invalid file class");
72
7.65k
73
7.65k
  size_t bufSize = mb.getBuffer().size();
74
7.65k
  if ((size == ELFCLASS32 && 
bufSize < sizeof(Elf32_Ehdr)1.44k
) ||
75
7.65k
      (size == ELFCLASS64 && 
bufSize < sizeof(Elf64_Ehdr)6.20k
))
76
0
    report("corrupted ELF file: file is too short");
77
7.65k
78
7.65k
  if (size == ELFCLASS32)
79
1.44k
    return (endian == ELFDATA2LSB) ? 
ELF32LEKind994
:
ELF32BEKind453
;
80
6.20k
  return (endian == ELFDATA2LSB) ? 
ELF64LEKind5.91k
:
ELF64BEKind291
;
81
6.20k
}
82
83
InputFile::InputFile(Kind k, MemoryBufferRef m)
84
4.45k
    : mb(m), groupId(nextGroupId), fileKind(k) {
85
4.45k
  // All files within the same --{start,end}-group get the same group ID.
86
4.45k
  // Otherwise, a new file will get a new group ID.
87
4.45k
  if (!isInGroup)
88
4.38k
    ++nextGroupId;
89
4.45k
}
90
91
5.03k
Optional<MemoryBufferRef> elf::readFile(StringRef path) {
92
5.03k
  // The --chroot option changes our virtual root directory.
93
5.03k
  // This is useful when you are dealing with files created by --reproduce.
94
5.03k
  if (!config->chroot.empty() && 
path.startswith("/")3
)
95
3
    path = saver.save(config->chroot + path);
96
5.03k
97
5.03k
  log(path);
98
5.03k
99
5.03k
  auto mbOrErr = MemoryBuffer::getFile(path, -1, false);
100
5.03k
  if (auto ec = mbOrErr.getError()) {
101
90
    error("cannot open " + path + ": " + ec.message());
102
90
    return None;
103
90
  }
104
4.94k
105
4.94k
  std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
106
4.94k
  MemoryBufferRef mbref = mb->getMemBufferRef();
107
4.94k
  make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take MB ownership
108
4.94k
109
4.94k
  if (tar)
110
16
    tar->append(relativeToRoot(path), mbref.getBuffer());
111
4.94k
  return mbref;
112
4.94k
}
113
114
// All input object files must be for the same architecture
115
// (e.g. it does not make sense to link x86 object files with
116
// MIPS object files.) This function checks for that error.
117
4.09k
static bool isCompatible(InputFile *file) {
118
4.09k
  if (!file->isElf() && 
!isa<BitcodeFile>(file)415
)
119
156
    return true;
120
3.93k
121
3.93k
  if (file->ekind == config->ekind && 
file->emachine == config->emachine3.92k
) {
122
3.92k
    if (config->emachine != EM_MIPS)
123
3.62k
      return true;
124
298
    if (isMipsN32Abi(file) == config->mipsN32Abi)
125
297
      return true;
126
15
  }
127
15
128
15
  if (!config->emulation.empty()) {
129
6
    error(toString(file) + " is incompatible with " + config->emulation);
130
9
  } else {
131
9
    InputFile *existing;
132
9
    if (!objectFiles.empty())
133
6
      existing = objectFiles[0];
134
3
    else if (!sharedFiles.empty())
135
2
      existing = sharedFiles[0];
136
1
    else
137
1
      existing = bitcodeFiles[0];
138
9
139
9
    error(toString(file) + " is incompatible with " + toString(existing));
140
9
  }
141
15
142
15
  return false;
143
15
}
144
145
4.09k
template <class ELFT> static void doParseFile(InputFile *file) {
146
4.09k
  if (!isCompatible(file))
147
15
    return;
148
4.07k
149
4.07k
  // Binary file
150
4.07k
  if (auto *f = dyn_cast<BinaryFile>(file)) {
151
8
    binaryFiles.push_back(f);
152
8
    f->parse();
153
8
    return;
154
8
  }
155
4.06k
156
4.06k
  // .a file
157
4.06k
  if (auto *f = dyn_cast<ArchiveFile>(file)) {
158
118
    f->parse();
159
118
    return;
160
118
  }
161
3.95k
162
3.95k
  // Lazy object file
163
3.95k
  if (auto *f = dyn_cast<LazyObjFile>(file)) {
164
30
    lazyObjFiles.push_back(f);
165
30
    f->parse<ELFT>();
166
30
    return;
167
30
  }
168
3.92k
169
3.92k
  if (config->trace)
170
13
    message(toString(file));
171
3.92k
172
3.92k
  // .so file
173
3.92k
  if (auto *f = dyn_cast<SharedFile>(file)) {
174
407
    f->parse<ELFT>();
175
407
    return;
176
407
  }
177
3.51k
178
3.51k
  // LLVM bitcode file
179
3.51k
  if (auto *f = dyn_cast<BitcodeFile>(file)) {
180
257
    bitcodeFiles.push_back(f);
181
257
    f->parse<ELFT>();
182
257
    return;
183
257
  }
184
3.25k
185
3.25k
  // Regular object file
186
3.25k
  objectFiles.push_back(file);
187
3.25k
  cast<ObjFile<ELFT>>(file)->parse();
188
3.25k
}
InputFiles.cpp:void doParseFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >(lld::elf::InputFile*)
Line
Count
Source
145
538
template <class ELFT> static void doParseFile(InputFile *file) {
146
538
  if (!isCompatible(file))
147
8
    return;
148
530
149
530
  // Binary file
150
530
  if (auto *f = dyn_cast<BinaryFile>(file)) {
151
0
    binaryFiles.push_back(f);
152
0
    f->parse();
153
0
    return;
154
0
  }
155
530
156
530
  // .a file
157
530
  if (auto *f = dyn_cast<ArchiveFile>(file)) {
158
4
    f->parse();
159
4
    return;
160
4
  }
161
526
162
526
  // Lazy object file
163
526
  if (auto *f = dyn_cast<LazyObjFile>(file)) {
164
0
    lazyObjFiles.push_back(f);
165
0
    f->parse<ELFT>();
166
0
    return;
167
0
  }
168
526
169
526
  if (config->trace)
170
0
    message(toString(file));
171
526
172
526
  // .so file
173
526
  if (auto *f = dyn_cast<SharedFile>(file)) {
174
65
    f->parse<ELFT>();
175
65
    return;
176
65
  }
177
461
178
461
  // LLVM bitcode file
179
461
  if (auto *f = dyn_cast<BitcodeFile>(file)) {
180
3
    bitcodeFiles.push_back(f);
181
3
    f->parse<ELFT>();
182
3
    return;
183
3
  }
184
458
185
458
  // Regular object file
186
458
  objectFiles.push_back(file);
187
458
  cast<ObjFile<ELFT>>(file)->parse();
188
458
}
InputFiles.cpp:void doParseFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >(lld::elf::InputFile*)
Line
Count
Source
145
240
template <class ELFT> static void doParseFile(InputFile *file) {
146
240
  if (!isCompatible(file))
147
1
    return;
148
239
149
239
  // Binary file
150
239
  if (auto *f = dyn_cast<BinaryFile>(file)) {
151
0
    binaryFiles.push_back(f);
152
0
    f->parse();
153
0
    return;
154
0
  }
155
239
156
239
  // .a file
157
239
  if (auto *f = dyn_cast<ArchiveFile>(file)) {
158
0
    f->parse();
159
0
    return;
160
0
  }
161
239
162
239
  // Lazy object file
163
239
  if (auto *f = dyn_cast<LazyObjFile>(file)) {
164
0
    lazyObjFiles.push_back(f);
165
0
    f->parse<ELFT>();
166
0
    return;
167
0
  }
168
239
169
239
  if (config->trace)
170
0
    message(toString(file));
171
239
172
239
  // .so file
173
239
  if (auto *f = dyn_cast<SharedFile>(file)) {
174
29
    f->parse<ELFT>();
175
29
    return;
176
29
  }
177
210
178
210
  // LLVM bitcode file
179
210
  if (auto *f = dyn_cast<BitcodeFile>(file)) {
180
0
    bitcodeFiles.push_back(f);
181
0
    f->parse<ELFT>();
182
0
    return;
183
0
  }
184
210
185
210
  // Regular object file
186
210
  objectFiles.push_back(file);
187
210
  cast<ObjFile<ELFT>>(file)->parse();
188
210
}
InputFiles.cpp:void doParseFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >(lld::elf::InputFile*)
Line
Count
Source
145
3.15k
template <class ELFT> static void doParseFile(InputFile *file) {
146
3.15k
  if (!isCompatible(file))
147
3
    return;
148
3.15k
149
3.15k
  // Binary file
150
3.15k
  if (auto *f = dyn_cast<BinaryFile>(file)) {
151
8
    binaryFiles.push_back(f);
152
8
    f->parse();
153
8
    return;
154
8
  }
155
3.14k
156
3.14k
  // .a file
157
3.14k
  if (auto *f = dyn_cast<ArchiveFile>(file)) {
158
113
    f->parse();
159
113
    return;
160
113
  }
161
3.03k
162
3.03k
  // Lazy object file
163
3.03k
  if (auto *f = dyn_cast<LazyObjFile>(file)) {
164
30
    lazyObjFiles.push_back(f);
165
30
    f->parse<ELFT>();
166
30
    return;
167
30
  }
168
3.00k
169
3.00k
  if (config->trace)
170
13
    message(toString(file));
171
3.00k
172
3.00k
  // .so file
173
3.00k
  if (auto *f = dyn_cast<SharedFile>(file)) {
174
298
    f->parse<ELFT>();
175
298
    return;
176
298
  }
177
2.70k
178
2.70k
  // LLVM bitcode file
179
2.70k
  if (auto *f = dyn_cast<BitcodeFile>(file)) {
180
254
    bitcodeFiles.push_back(f);
181
254
    f->parse<ELFT>();
182
254
    return;
183
254
  }
184
2.45k
185
2.45k
  // Regular object file
186
2.45k
  objectFiles.push_back(file);
187
2.45k
  cast<ObjFile<ELFT>>(file)->parse();
188
2.45k
}
InputFiles.cpp:void doParseFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >(lld::elf::InputFile*)
Line
Count
Source
145
157
template <class ELFT> static void doParseFile(InputFile *file) {
146
157
  if (!isCompatible(file))
147
3
    return;
148
154
149
154
  // Binary file
150
154
  if (auto *f = dyn_cast<BinaryFile>(file)) {
151
0
    binaryFiles.push_back(f);
152
0
    f->parse();
153
0
    return;
154
0
  }
155
154
156
154
  // .a file
157
154
  if (auto *f = dyn_cast<ArchiveFile>(file)) {
158
1
    f->parse();
159
1
    return;
160
1
  }
161
153
162
153
  // Lazy object file
163
153
  if (auto *f = dyn_cast<LazyObjFile>(file)) {
164
0
    lazyObjFiles.push_back(f);
165
0
    f->parse<ELFT>();
166
0
    return;
167
0
  }
168
153
169
153
  if (config->trace)
170
0
    message(toString(file));
171
153
172
153
  // .so file
173
153
  if (auto *f = dyn_cast<SharedFile>(file)) {
174
15
    f->parse<ELFT>();
175
15
    return;
176
15
  }
177
138
178
138
  // LLVM bitcode file
179
138
  if (auto *f = dyn_cast<BitcodeFile>(file)) {
180
0
    bitcodeFiles.push_back(f);
181
0
    f->parse<ELFT>();
182
0
    return;
183
0
  }
184
138
185
138
  // Regular object file
186
138
  objectFiles.push_back(file);
187
138
  cast<ObjFile<ELFT>>(file)->parse();
188
138
}
189
190
// Add symbols in File to the symbol table.
191
4.09k
void elf::parseFile(InputFile *file) {
192
4.09k
  switch (config->ekind) {
193
4.09k
  case ELF32LEKind:
194
538
    doParseFile<ELF32LE>(file);
195
538
    return;
196
4.09k
  case ELF32BEKind:
197
240
    doParseFile<ELF32BE>(file);
198
240
    return;
199
4.09k
  case ELF64LEKind:
200
3.15k
    doParseFile<ELF64LE>(file);
201
3.15k
    return;
202
4.09k
  case ELF64BEKind:
203
157
    doParseFile<ELF64BE>(file);
204
157
    return;
205
4.09k
  default:
206
0
    llvm_unreachable("unknown ELFT");
207
4.09k
  }
208
4.09k
}
209
210
// Concatenates arguments to construct a string representing an error location.
211
39
static std::string createFileLineMsg(StringRef path, unsigned line) {
212
39
  std::string filename = path::filename(path);
213
39
  std::string lineno = ":" + std::to_string(line);
214
39
  if (filename == path)
215
22
    return filename + lineno;
216
17
  return filename + lineno + " (" + path.str() + lineno + ")";
217
17
}
218
219
template <class ELFT>
220
static std::string getSrcMsgAux(ObjFile<ELFT> &file, const Symbol &sym,
221
242
                                InputSectionBase &sec, uint64_t offset) {
222
242
  // In DWARF, functions and variables are stored to different places.
223
242
  // First, lookup a function for a given offset.
224
242
  if (Optional<DILineInfo> info = file.getDILineInfo(&sec, offset))
225
23
    return createFileLineMsg(info->FileName, info->Line);
226
219
227
219
  // If it failed, lookup again as a variable.
228
219
  if (Optional<std::pair<std::string, unsigned>> fileLine =
229
16
          file.getVariableLoc(sym.getName()))
230
16
    return createFileLineMsg(fileLine->first, fileLine->second);
231
203
232
203
  // File.sourceFile contains STT_FILE symbol, and that is a last resort.
233
203
  return file.sourceFile;
234
203
}
InputFiles.cpp:std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > getSrcMsgAux<llvm::object::ELFType<(llvm::support::endianness)1, false> >(lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >&, lld::elf::Symbol const&, lld::elf::InputSectionBase&, unsigned long long)
Line
Count
Source
221
11
                                InputSectionBase &sec, uint64_t offset) {
222
11
  // In DWARF, functions and variables are stored to different places.
223
11
  // First, lookup a function for a given offset.
224
11
  if (Optional<DILineInfo> info = file.getDILineInfo(&sec, offset))
225
2
    return createFileLineMsg(info->FileName, info->Line);
226
9
227
9
  // If it failed, lookup again as a variable.
228
9
  if (Optional<std::pair<std::string, unsigned>> fileLine =
229
0
          file.getVariableLoc(sym.getName()))
230
0
    return createFileLineMsg(fileLine->first, fileLine->second);
231
9
232
9
  // File.sourceFile contains STT_FILE symbol, and that is a last resort.
233
9
  return file.sourceFile;
234
9
}
Unexecuted instantiation: InputFiles.cpp:std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > getSrcMsgAux<llvm::object::ELFType<(llvm::support::endianness)0, false> >(lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >&, lld::elf::Symbol const&, lld::elf::InputSectionBase&, unsigned long long)
InputFiles.cpp:std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > getSrcMsgAux<llvm::object::ELFType<(llvm::support::endianness)1, true> >(lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >&, lld::elf::Symbol const&, lld::elf::InputSectionBase&, unsigned long long)
Line
Count
Source
221
231
                                InputSectionBase &sec, uint64_t offset) {
222
231
  // In DWARF, functions and variables are stored to different places.
223
231
  // First, lookup a function for a given offset.
224
231
  if (Optional<DILineInfo> info = file.getDILineInfo(&sec, offset))
225
21
    return createFileLineMsg(info->FileName, info->Line);
226
210
227
210
  // If it failed, lookup again as a variable.
228
210
  if (Optional<std::pair<std::string, unsigned>> fileLine =
229
16
          file.getVariableLoc(sym.getName()))
230
16
    return createFileLineMsg(fileLine->first, fileLine->second);
231
194
232
194
  // File.sourceFile contains STT_FILE symbol, and that is a last resort.
233
194
  return file.sourceFile;
234
194
}
Unexecuted instantiation: InputFiles.cpp:std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > getSrcMsgAux<llvm::object::ELFType<(llvm::support::endianness)0, true> >(lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >&, lld::elf::Symbol const&, lld::elf::InputSectionBase&, unsigned long long)
235
236
std::string InputFile::getSrcMsg(const Symbol &sym, InputSectionBase &sec,
237
244
                                 uint64_t offset) {
238
244
  if (kind() != ObjKind)
239
2
    return "";
240
242
  switch (config->ekind) {
241
242
  default:
242
0
    llvm_unreachable("Invalid kind");
243
242
  case ELF32LEKind:
244
11
    return getSrcMsgAux(cast<ObjFile<ELF32LE>>(*this), sym, sec, offset);
245
242
  case ELF32BEKind:
246
0
    return getSrcMsgAux(cast<ObjFile<ELF32BE>>(*this), sym, sec, offset);
247
242
  case ELF64LEKind:
248
231
    return getSrcMsgAux(cast<ObjFile<ELF64LE>>(*this), sym, sec, offset);
249
242
  case ELF64BEKind:
250
0
    return getSrcMsgAux(cast<ObjFile<ELF64BE>>(*this), sym, sec, offset);
251
242
  }
252
242
}
253
254
232
template <class ELFT> void ObjFile<ELFT>::initializeDwarf() {
255
232
  dwarf = llvm::make_unique<DWARFContext>(make_unique<LLDDwarfObj<ELFT>>(this));
256
232
  for (std::unique_ptr<DWARFUnit> &cu : dwarf->compile_units()) {
257
34
    auto report = [](Error err) {
258
4
      handleAllErrors(std::move(err),
259
4
                      [](ErrorInfoBase &info) { warn(info.message()); });
Unexecuted instantiation: lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >::initializeDwarf()::'lambda'(llvm::Error)::operator()(llvm::Error) const::'lambda'(llvm::ErrorInfoBase&)::operator()(llvm::ErrorInfoBase&) const
Unexecuted instantiation: lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >::initializeDwarf()::'lambda'(llvm::Error)::operator()(llvm::Error) const::'lambda'(llvm::ErrorInfoBase&)::operator()(llvm::ErrorInfoBase&) const
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >::initializeDwarf()::'lambda'(llvm::Error)::operator()(llvm::Error) const::'lambda'(llvm::ErrorInfoBase&)::operator()(llvm::ErrorInfoBase&) const
Line
Count
Source
259
4
                      [](ErrorInfoBase &info) { warn(info.message()); });
Unexecuted instantiation: lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >::initializeDwarf()::'lambda'(llvm::Error)::operator()(llvm::Error) const::'lambda'(llvm::ErrorInfoBase&)::operator()(llvm::ErrorInfoBase&) const
260
4
    };
Unexecuted instantiation: lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >::initializeDwarf()::'lambda'(llvm::Error)::operator()(llvm::Error) const
Unexecuted instantiation: lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >::initializeDwarf()::'lambda'(llvm::Error)::operator()(llvm::Error) const
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >::initializeDwarf()::'lambda'(llvm::Error)::operator()(llvm::Error) const
Line
Count
Source
257
4
    auto report = [](Error err) {
258
4
      handleAllErrors(std::move(err),
259
4
                      [](ErrorInfoBase &info) { warn(info.message()); });
260
4
    };
Unexecuted instantiation: lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >::initializeDwarf()::'lambda'(llvm::Error)::operator()(llvm::Error) const
261
34
    Expected<const DWARFDebugLine::LineTable *> expectedLT =
262
34
        dwarf->getLineTableForUnit(cu.get(), report);
263
34
    const DWARFDebugLine::LineTable *lt = nullptr;
264
34
    if (expectedLT)
265
32
      lt = *expectedLT;
266
2
    else
267
2
      report(expectedLT.takeError());
268
34
    if (!lt)
269
2
      continue;
270
32
    lineTables.push_back(lt);
271
32
272
32
    // Loop over variable records and insert them to variableLoc.
273
91
    for (const auto &entry : cu->dies()) {
274
91
      DWARFDie die(cu.get(), &entry);
275
91
      // Skip all tags that are not variables.
276
91
      if (die.getTag() != dwarf::DW_TAG_variable)
277
67
        continue;
278
24
279
24
      // Skip if a local variable because we don't need them for generating
280
24
      // error messages. In general, only non-local symbols can fail to be
281
24
      // linked.
282
24
      if (!dwarf::toUnsigned(die.find(dwarf::DW_AT_external), 0))
283
4
        continue;
284
20
285
20
      // Get the source filename index for the variable.
286
20
      unsigned file = dwarf::toUnsigned(die.find(dwarf::DW_AT_decl_file), 0);
287
20
      if (!lt->hasFileAtIndex(file))
288
2
        continue;
289
18
290
18
      // Get the line number on which the variable is declared.
291
18
      unsigned line = dwarf::toUnsigned(die.find(dwarf::DW_AT_decl_line), 0);
292
18
293
18
      // Here we want to take the variable name to add it into variableLoc.
294
18
      // Variable can have regular and linkage name associated. At first, we try
295
18
      // to get linkage name as it can be different, for example when we have
296
18
      // two variables in different namespaces of the same object. Use common
297
18
      // name otherwise, but handle the case when it also absent in case if the
298
18
      // input object file lacks some debug info.
299
18
      StringRef name =
300
18
          dwarf::toString(die.find(dwarf::DW_AT_linkage_name),
301
18
                          dwarf::toString(die.find(dwarf::DW_AT_name), ""));
302
18
      if (!name.empty())
303
18
        variableLoc.insert({name, {lt, file, line}});
304
18
    }
305
32
  }
306
232
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >::initializeDwarf()
Line
Count
Source
254
20
template <class ELFT> void ObjFile<ELFT>::initializeDwarf() {
255
20
  dwarf = llvm::make_unique<DWARFContext>(make_unique<LLDDwarfObj<ELFT>>(this));
256
20
  for (std::unique_ptr<DWARFUnit> &cu : dwarf->compile_units()) {
257
2
    auto report = [](Error err) {
258
2
      handleAllErrors(std::move(err),
259
2
                      [](ErrorInfoBase &info) { warn(info.message()); });
260
2
    };
261
2
    Expected<const DWARFDebugLine::LineTable *> expectedLT =
262
2
        dwarf->getLineTableForUnit(cu.get(), report);
263
2
    const DWARFDebugLine::LineTable *lt = nullptr;
264
2
    if (expectedLT)
265
2
      lt = *expectedLT;
266
0
    else
267
0
      report(expectedLT.takeError());
268
2
    if (!lt)
269
0
      continue;
270
2
    lineTables.push_back(lt);
271
2
272
2
    // Loop over variable records and insert them to variableLoc.
273
2
    for (const auto &entry : cu->dies()) {
274
2
      DWARFDie die(cu.get(), &entry);
275
2
      // Skip all tags that are not variables.
276
2
      if (die.getTag() != dwarf::DW_TAG_variable)
277
2
        continue;
278
0
279
0
      // Skip if a local variable because we don't need them for generating
280
0
      // error messages. In general, only non-local symbols can fail to be
281
0
      // linked.
282
0
      if (!dwarf::toUnsigned(die.find(dwarf::DW_AT_external), 0))
283
0
        continue;
284
0
285
0
      // Get the source filename index for the variable.
286
0
      unsigned file = dwarf::toUnsigned(die.find(dwarf::DW_AT_decl_file), 0);
287
0
      if (!lt->hasFileAtIndex(file))
288
0
        continue;
289
0
290
0
      // Get the line number on which the variable is declared.
291
0
      unsigned line = dwarf::toUnsigned(die.find(dwarf::DW_AT_decl_line), 0);
292
0
293
0
      // Here we want to take the variable name to add it into variableLoc.
294
0
      // Variable can have regular and linkage name associated. At first, we try
295
0
      // to get linkage name as it can be different, for example when we have
296
0
      // two variables in different namespaces of the same object. Use common
297
0
      // name otherwise, but handle the case when it also absent in case if the
298
0
      // input object file lacks some debug info.
299
0
      StringRef name =
300
0
          dwarf::toString(die.find(dwarf::DW_AT_linkage_name),
301
0
                          dwarf::toString(die.find(dwarf::DW_AT_name), ""));
302
0
      if (!name.empty())
303
0
        variableLoc.insert({name, {lt, file, line}});
304
0
    }
305
2
  }
306
20
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >::initializeDwarf()
Line
Count
Source
254
2
template <class ELFT> void ObjFile<ELFT>::initializeDwarf() {
255
2
  dwarf = llvm::make_unique<DWARFContext>(make_unique<LLDDwarfObj<ELFT>>(this));
256
2
  for (std::unique_ptr<DWARFUnit> &cu : dwarf->compile_units()) {
257
0
    auto report = [](Error err) {
258
0
      handleAllErrors(std::move(err),
259
0
                      [](ErrorInfoBase &info) { warn(info.message()); });
260
0
    };
261
0
    Expected<const DWARFDebugLine::LineTable *> expectedLT =
262
0
        dwarf->getLineTableForUnit(cu.get(), report);
263
0
    const DWARFDebugLine::LineTable *lt = nullptr;
264
0
    if (expectedLT)
265
0
      lt = *expectedLT;
266
0
    else
267
0
      report(expectedLT.takeError());
268
0
    if (!lt)
269
0
      continue;
270
0
    lineTables.push_back(lt);
271
0
272
0
    // Loop over variable records and insert them to variableLoc.
273
0
    for (const auto &entry : cu->dies()) {
274
0
      DWARFDie die(cu.get(), &entry);
275
0
      // Skip all tags that are not variables.
276
0
      if (die.getTag() != dwarf::DW_TAG_variable)
277
0
        continue;
278
0
279
0
      // Skip if a local variable because we don't need them for generating
280
0
      // error messages. In general, only non-local symbols can fail to be
281
0
      // linked.
282
0
      if (!dwarf::toUnsigned(die.find(dwarf::DW_AT_external), 0))
283
0
        continue;
284
0
285
0
      // Get the source filename index for the variable.
286
0
      unsigned file = dwarf::toUnsigned(die.find(dwarf::DW_AT_decl_file), 0);
287
0
      if (!lt->hasFileAtIndex(file))
288
0
        continue;
289
0
290
0
      // Get the line number on which the variable is declared.
291
0
      unsigned line = dwarf::toUnsigned(die.find(dwarf::DW_AT_decl_line), 0);
292
0
293
0
      // Here we want to take the variable name to add it into variableLoc.
294
0
      // Variable can have regular and linkage name associated. At first, we try
295
0
      // to get linkage name as it can be different, for example when we have
296
0
      // two variables in different namespaces of the same object. Use common
297
0
      // name otherwise, but handle the case when it also absent in case if the
298
0
      // input object file lacks some debug info.
299
0
      StringRef name =
300
0
          dwarf::toString(die.find(dwarf::DW_AT_linkage_name),
301
0
                          dwarf::toString(die.find(dwarf::DW_AT_name), ""));
302
0
      if (!name.empty())
303
0
        variableLoc.insert({name, {lt, file, line}});
304
0
    }
305
0
  }
306
2
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >::initializeDwarf()
Line
Count
Source
254
201
template <class ELFT> void ObjFile<ELFT>::initializeDwarf() {
255
201
  dwarf = llvm::make_unique<DWARFContext>(make_unique<LLDDwarfObj<ELFT>>(this));
256
201
  for (std::unique_ptr<DWARFUnit> &cu : dwarf->compile_units()) {
257
32
    auto report = [](Error err) {
258
32
      handleAllErrors(std::move(err),
259
32
                      [](ErrorInfoBase &info) { warn(info.message()); });
260
32
    };
261
32
    Expected<const DWARFDebugLine::LineTable *> expectedLT =
262
32
        dwarf->getLineTableForUnit(cu.get(), report);
263
32
    const DWARFDebugLine::LineTable *lt = nullptr;
264
32
    if (expectedLT)
265
30
      lt = *expectedLT;
266
2
    else
267
2
      report(expectedLT.takeError());
268
32
    if (!lt)
269
2
      continue;
270
30
    lineTables.push_back(lt);
271
30
272
30
    // Loop over variable records and insert them to variableLoc.
273
89
    for (const auto &entry : cu->dies()) {
274
89
      DWARFDie die(cu.get(), &entry);
275
89
      // Skip all tags that are not variables.
276
89
      if (die.getTag() != dwarf::DW_TAG_variable)
277
65
        continue;
278
24
279
24
      // Skip if a local variable because we don't need them for generating
280
24
      // error messages. In general, only non-local symbols can fail to be
281
24
      // linked.
282
24
      if (!dwarf::toUnsigned(die.find(dwarf::DW_AT_external), 0))
283
4
        continue;
284
20
285
20
      // Get the source filename index for the variable.
286
20
      unsigned file = dwarf::toUnsigned(die.find(dwarf::DW_AT_decl_file), 0);
287
20
      if (!lt->hasFileAtIndex(file))
288
2
        continue;
289
18
290
18
      // Get the line number on which the variable is declared.
291
18
      unsigned line = dwarf::toUnsigned(die.find(dwarf::DW_AT_decl_line), 0);
292
18
293
18
      // Here we want to take the variable name to add it into variableLoc.
294
18
      // Variable can have regular and linkage name associated. At first, we try
295
18
      // to get linkage name as it can be different, for example when we have
296
18
      // two variables in different namespaces of the same object. Use common
297
18
      // name otherwise, but handle the case when it also absent in case if the
298
18
      // input object file lacks some debug info.
299
18
      StringRef name =
300
18
          dwarf::toString(die.find(dwarf::DW_AT_linkage_name),
301
18
                          dwarf::toString(die.find(dwarf::DW_AT_name), ""));
302
18
      if (!name.empty())
303
18
        variableLoc.insert({name, {lt, file, line}});
304
18
    }
305
30
  }
306
201
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >::initializeDwarf()
Line
Count
Source
254
9
template <class ELFT> void ObjFile<ELFT>::initializeDwarf() {
255
9
  dwarf = llvm::make_unique<DWARFContext>(make_unique<LLDDwarfObj<ELFT>>(this));
256
9
  for (std::unique_ptr<DWARFUnit> &cu : dwarf->compile_units()) {
257
0
    auto report = [](Error err) {
258
0
      handleAllErrors(std::move(err),
259
0
                      [](ErrorInfoBase &info) { warn(info.message()); });
260
0
    };
261
0
    Expected<const DWARFDebugLine::LineTable *> expectedLT =
262
0
        dwarf->getLineTableForUnit(cu.get(), report);
263
0
    const DWARFDebugLine::LineTable *lt = nullptr;
264
0
    if (expectedLT)
265
0
      lt = *expectedLT;
266
0
    else
267
0
      report(expectedLT.takeError());
268
0
    if (!lt)
269
0
      continue;
270
0
    lineTables.push_back(lt);
271
0
272
0
    // Loop over variable records and insert them to variableLoc.
273
0
    for (const auto &entry : cu->dies()) {
274
0
      DWARFDie die(cu.get(), &entry);
275
0
      // Skip all tags that are not variables.
276
0
      if (die.getTag() != dwarf::DW_TAG_variable)
277
0
        continue;
278
0
279
0
      // Skip if a local variable because we don't need them for generating
280
0
      // error messages. In general, only non-local symbols can fail to be
281
0
      // linked.
282
0
      if (!dwarf::toUnsigned(die.find(dwarf::DW_AT_external), 0))
283
0
        continue;
284
0
285
0
      // Get the source filename index for the variable.
286
0
      unsigned file = dwarf::toUnsigned(die.find(dwarf::DW_AT_decl_file), 0);
287
0
      if (!lt->hasFileAtIndex(file))
288
0
        continue;
289
0
290
0
      // Get the line number on which the variable is declared.
291
0
      unsigned line = dwarf::toUnsigned(die.find(dwarf::DW_AT_decl_line), 0);
292
0
293
0
      // Here we want to take the variable name to add it into variableLoc.
294
0
      // Variable can have regular and linkage name associated. At first, we try
295
0
      // to get linkage name as it can be different, for example when we have
296
0
      // two variables in different namespaces of the same object. Use common
297
0
      // name otherwise, but handle the case when it also absent in case if the
298
0
      // input object file lacks some debug info.
299
0
      StringRef name =
300
0
          dwarf::toString(die.find(dwarf::DW_AT_linkage_name),
301
0
                          dwarf::toString(die.find(dwarf::DW_AT_name), ""));
302
0
      if (!name.empty())
303
0
        variableLoc.insert({name, {lt, file, line}});
304
0
    }
305
0
  }
306
9
}
307
308
// Returns the pair of file name and line number describing location of data
309
// object (variable, array, etc) definition.
310
template <class ELFT>
311
Optional<std::pair<std::string, unsigned>>
312
219
ObjFile<ELFT>::getVariableLoc(StringRef name) {
313
219
  llvm::call_once(initDwarfLine, [this]() 
{ initializeDwarf(); }0
);
Unexecuted instantiation: lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >::getVariableLoc(llvm::StringRef)::'lambda'()::operator()() const
Unexecuted instantiation: lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >::getVariableLoc(llvm::StringRef)::'lambda'()::operator()() const
Unexecuted instantiation: lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >::getVariableLoc(llvm::StringRef)::'lambda'()::operator()() const
Unexecuted instantiation: lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >::getVariableLoc(llvm::StringRef)::'lambda'()::operator()() const
314
219
315
219
  // Return if we have no debug information about data object.
316
219
  auto it = variableLoc.find(name);
317
219
  if (it == variableLoc.end())
318
203
    return None;
319
16
320
16
  // Take file name string from line table.
321
16
  std::string fileName;
322
16
  if (!it->second.lt->getFileNameByIndex(
323
16
          it->second.file, {},
324
16
          DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, fileName))
325
0
    return None;
326
16
327
16
  return std::make_pair(fileName, it->second.line);
328
16
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >::getVariableLoc(llvm::StringRef)
Line
Count
Source
312
9
ObjFile<ELFT>::getVariableLoc(StringRef name) {
313
9
  llvm::call_once(initDwarfLine, [this]() { initializeDwarf(); });
314
9
315
9
  // Return if we have no debug information about data object.
316
9
  auto it = variableLoc.find(name);
317
9
  if (it == variableLoc.end())
318
9
    return None;
319
0
320
0
  // Take file name string from line table.
321
0
  std::string fileName;
322
0
  if (!it->second.lt->getFileNameByIndex(
323
0
          it->second.file, {},
324
0
          DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, fileName))
325
0
    return None;
326
0
327
0
  return std::make_pair(fileName, it->second.line);
328
0
}
Unexecuted instantiation: lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >::getVariableLoc(llvm::StringRef)
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >::getVariableLoc(llvm::StringRef)
Line
Count
Source
312
210
ObjFile<ELFT>::getVariableLoc(StringRef name) {
313
210
  llvm::call_once(initDwarfLine, [this]() { initializeDwarf(); });
314
210
315
210
  // Return if we have no debug information about data object.
316
210
  auto it = variableLoc.find(name);
317
210
  if (it == variableLoc.end())
318
194
    return None;
319
16
320
16
  // Take file name string from line table.
321
16
  std::string fileName;
322
16
  if (!it->second.lt->getFileNameByIndex(
323
16
          it->second.file, {},
324
16
          DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, fileName))
325
0
    return None;
326
16
327
16
  return std::make_pair(fileName, it->second.line);
328
16
}
Unexecuted instantiation: lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >::getVariableLoc(llvm::StringRef)
329
330
// Returns source line information for a given offset
331
// using DWARF debug info.
332
template <class ELFT>
333
Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *s,
334
2.15k
                                                  uint64_t offset) {
335
2.15k
  llvm::call_once(initDwarfLine, [this]() 
{ initializeDwarf(); }232
);
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >::getDILineInfo(lld::elf::InputSectionBase*, unsigned long long)::'lambda'()::operator()() const
Line
Count
Source
335
20
  llvm::call_once(initDwarfLine, [this]() { initializeDwarf(); });
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >::getDILineInfo(lld::elf::InputSectionBase*, unsigned long long)::'lambda'()::operator()() const
Line
Count
Source
335
2
  llvm::call_once(initDwarfLine, [this]() { initializeDwarf(); });
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >::getDILineInfo(lld::elf::InputSectionBase*, unsigned long long)::'lambda'()::operator()() const
Line
Count
Source
335
201
  llvm::call_once(initDwarfLine, [this]() { initializeDwarf(); });
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >::getDILineInfo(lld::elf::InputSectionBase*, unsigned long long)::'lambda'()::operator()() const
Line
Count
Source
335
9
  llvm::call_once(initDwarfLine, [this]() { initializeDwarf(); });
336
2.15k
337
2.15k
  // Detect SectionIndex for specified section.
338
2.15k
  uint64_t sectionIndex = object::SectionedAddress::UndefSection;
339
2.15k
  ArrayRef<InputSectionBase *> sections = s->file->getSections();
340
6.57k
  for (uint64_t curIndex = 0; curIndex < sections.size(); 
++curIndex4.41k
) {
341
6.57k
    if (s == sections[curIndex]) {
342
2.15k
      sectionIndex = curIndex;
343
2.15k
      break;
344
2.15k
    }
345
6.57k
  }
346
2.15k
347
2.15k
  // Use fake address calcuated by adding section file offset and offset in
348
2.15k
  // section. See comments for ObjectInfo class.
349
2.15k
  DILineInfo info;
350
2.15k
  for (const llvm::DWARFDebugLine::LineTable *lt : lineTables) {
351
51
    if (lt->getFileLineInfoForAddress(
352
51
            {s->getOffsetInFile() + offset, sectionIndex}, nullptr,
353
51
            DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, info))
354
24
      return info;
355
51
  }
356
2.15k
  
return None2.13k
;
357
2.15k
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >::getDILineInfo(lld::elf::InputSectionBase*, unsigned long long)
Line
Count
Source
334
25
                                                  uint64_t offset) {
335
25
  llvm::call_once(initDwarfLine, [this]() { initializeDwarf(); });
336
25
337
25
  // Detect SectionIndex for specified section.
338
25
  uint64_t sectionIndex = object::SectionedAddress::UndefSection;
339
25
  ArrayRef<InputSectionBase *> sections = s->file->getSections();
340
73
  for (uint64_t curIndex = 0; curIndex < sections.size(); 
++curIndex48
) {
341
73
    if (s == sections[curIndex]) {
342
25
      sectionIndex = curIndex;
343
25
      break;
344
25
    }
345
73
  }
346
25
347
25
  // Use fake address calcuated by adding section file offset and offset in
348
25
  // section. See comments for ObjectInfo class.
349
25
  DILineInfo info;
350
25
  for (const llvm::DWARFDebugLine::LineTable *lt : lineTables) {
351
2
    if (lt->getFileLineInfoForAddress(
352
2
            {s->getOffsetInFile() + offset, sectionIndex}, nullptr,
353
2
            DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, info))
354
2
      return info;
355
2
  }
356
25
  
return None23
;
357
25
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >::getDILineInfo(lld::elf::InputSectionBase*, unsigned long long)
Line
Count
Source
334
3
                                                  uint64_t offset) {
335
3
  llvm::call_once(initDwarfLine, [this]() { initializeDwarf(); });
336
3
337
3
  // Detect SectionIndex for specified section.
338
3
  uint64_t sectionIndex = object::SectionedAddress::UndefSection;
339
3
  ArrayRef<InputSectionBase *> sections = s->file->getSections();
340
9
  for (uint64_t curIndex = 0; curIndex < sections.size(); 
++curIndex6
) {
341
9
    if (s == sections[curIndex]) {
342
3
      sectionIndex = curIndex;
343
3
      break;
344
3
    }
345
9
  }
346
3
347
3
  // Use fake address calcuated by adding section file offset and offset in
348
3
  // section. See comments for ObjectInfo class.
349
3
  DILineInfo info;
350
3
  for (const llvm::DWARFDebugLine::LineTable *lt : lineTables) {
351
0
    if (lt->getFileLineInfoForAddress(
352
0
            {s->getOffsetInFile() + offset, sectionIndex}, nullptr,
353
0
            DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, info))
354
0
      return info;
355
0
  }
356
3
  return None;
357
3
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >::getDILineInfo(lld::elf::InputSectionBase*, unsigned long long)
Line
Count
Source
334
308
                                                  uint64_t offset) {
335
308
  llvm::call_once(initDwarfLine, [this]() { initializeDwarf(); });
336
308
337
308
  // Detect SectionIndex for specified section.
338
308
  uint64_t sectionIndex = object::SectionedAddress::UndefSection;
339
308
  ArrayRef<InputSectionBase *> sections = s->file->getSections();
340
1.03k
  for (uint64_t curIndex = 0; curIndex < sections.size(); 
++curIndex727
) {
341
1.03k
    if (s == sections[curIndex]) {
342
308
      sectionIndex = curIndex;
343
308
      break;
344
308
    }
345
1.03k
  }
346
308
347
308
  // Use fake address calcuated by adding section file offset and offset in
348
308
  // section. See comments for ObjectInfo class.
349
308
  DILineInfo info;
350
308
  for (const llvm::DWARFDebugLine::LineTable *lt : lineTables) {
351
49
    if (lt->getFileLineInfoForAddress(
352
49
            {s->getOffsetInFile() + offset, sectionIndex}, nullptr,
353
49
            DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, info))
354
22
      return info;
355
49
  }
356
308
  
return None286
;
357
308
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >::getDILineInfo(lld::elf::InputSectionBase*, unsigned long long)
Line
Count
Source
334
1.81k
                                                  uint64_t offset) {
335
1.81k
  llvm::call_once(initDwarfLine, [this]() { initializeDwarf(); });
336
1.81k
337
1.81k
  // Detect SectionIndex for specified section.
338
1.81k
  uint64_t sectionIndex = object::SectionedAddress::UndefSection;
339
1.81k
  ArrayRef<InputSectionBase *> sections = s->file->getSections();
340
5.45k
  for (uint64_t curIndex = 0; curIndex < sections.size(); 
++curIndex3.63k
) {
341
5.45k
    if (s == sections[curIndex]) {
342
1.81k
      sectionIndex = curIndex;
343
1.81k
      break;
344
1.81k
    }
345
5.45k
  }
346
1.81k
347
1.81k
  // Use fake address calcuated by adding section file offset and offset in
348
1.81k
  // section. See comments for ObjectInfo class.
349
1.81k
  DILineInfo info;
350
1.81k
  for (const llvm::DWARFDebugLine::LineTable *lt : lineTables) {
351
0
    if (lt->getFileLineInfoForAddress(
352
0
            {s->getOffsetInFile() + offset, sectionIndex}, nullptr,
353
0
            DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, info))
354
0
      return info;
355
0
  }
356
1.81k
  return None;
357
1.81k
}
358
359
// Returns "<internal>", "foo.a(bar.o)" or "baz.o".
360
2.95k
std::string lld::toString(const InputFile *f) {
361
2.95k
  if (!f)
362
176
    return "<internal>";
363
2.78k
364
2.78k
  if (f->toStringCache.empty()) {
365
640
    if (f->archiveName.empty())
366
619
      f->toStringCache = f->getName();
367
21
    else
368
21
      f->toStringCache = (f->archiveName + "(" + f->getName() + ")").str();
369
640
  }
370
2.78k
  return f->toStringCache;
371
2.78k
}
372
373
4.02k
ELFFileBase::ELFFileBase(Kind k, MemoryBufferRef mb) : InputFile(k, mb) {
374
4.02k
  ekind = getELFKind(mb, "");
375
4.02k
376
4.02k
  switch (ekind) {
377
4.02k
  case ELF32LEKind:
378
530
    init<ELF32LE>();
379
530
    break;
380
4.02k
  case ELF32BEKind:
381
241
    init<ELF32BE>();
382
241
    break;
383
4.02k
  case ELF64LEKind:
384
3.10k
    init<ELF64LE>();
385
3.10k
    break;
386
4.02k
  case ELF64BEKind:
387
153
    init<ELF64BE>();
388
153
    break;
389
4.02k
  default:
390
0
    llvm_unreachable("getELFKind");
391
4.02k
  }
392
4.02k
}
393
394
template <typename Elf_Shdr>
395
4.02k
static const Elf_Shdr *findSection(ArrayRef<Elf_Shdr> sections, uint32_t type) {
396
4.02k
  for (const Elf_Shdr &sec : sections)
397
352k
    if (sec.sh_type == type)
398
4.02k
      return &sec;
399
4.02k
  
return nullptr3
;
400
4.02k
}
InputFiles.cpp:llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false> > const* findSection<llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false> > >(llvm::ArrayRef<llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false> > >, unsigned int)
Line
Count
Source
395
530
static const Elf_Shdr *findSection(ArrayRef<Elf_Shdr> sections, uint32_t type) {
396
530
  for (const Elf_Shdr &sec : sections)
397
3.38k
    if (sec.sh_type == type)
398
530
      return &sec;
399
530
  
return nullptr0
;
400
530
}
InputFiles.cpp:llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false> > const* findSection<llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false> > >(llvm::ArrayRef<llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false> > >, unsigned int)
Line
Count
Source
395
241
static const Elf_Shdr *findSection(ArrayRef<Elf_Shdr> sections, uint32_t type) {
396
241
  for (const Elf_Shdr &sec : sections)
397
1.83k
    if (sec.sh_type == type)
398
241
      return &sec;
399
241
  
return nullptr0
;
400
241
}
InputFiles.cpp:llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true> > const* findSection<llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true> > >(llvm::ArrayRef<llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true> > >, unsigned int)
Line
Count
Source
395
3.10k
static const Elf_Shdr *findSection(ArrayRef<Elf_Shdr> sections, uint32_t type) {
396
3.10k
  for (const Elf_Shdr &sec : sections)
397
345k
    if (sec.sh_type == type)
398
3.09k
      return &sec;
399
3.10k
  
return nullptr3
;
400
3.10k
}
InputFiles.cpp:llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true> > const* findSection<llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true> > >(llvm::ArrayRef<llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true> > >, unsigned int)
Line
Count
Source
395
153
static const Elf_Shdr *findSection(ArrayRef<Elf_Shdr> sections, uint32_t type) {
396
153
  for (const Elf_Shdr &sec : sections)
397
969
    if (sec.sh_type == type)
398
153
      return &sec;
399
153
  
return nullptr0
;
400
153
}
401
402
4.02k
template <class ELFT> void ELFFileBase::init() {
403
4.02k
  using Elf_Shdr = typename ELFT::Shdr;
404
4.02k
  using Elf_Sym = typename ELFT::Sym;
405
4.02k
406
4.02k
  // Initialize trivial attributes.
407
4.02k
  const ELFFile<ELFT> &obj = getObj<ELFT>();
408
4.02k
  emachine = obj.getHeader()->e_machine;
409
4.02k
  osabi = obj.getHeader()->e_ident[llvm::ELF::EI_OSABI];
410
4.02k
  abiVersion = obj.getHeader()->e_ident[llvm::ELF::EI_ABIVERSION];
411
4.02k
412
4.02k
  ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
413
4.02k
414
4.02k
  // Find a symbol table.
415
4.02k
  bool isDSO =
416
4.02k
      (identify_magic(mb.getBuffer()) == file_magic::elf_shared_object);
417
4.02k
  const Elf_Shdr *symtabSec =
418
4.02k
      findSection(sections, isDSO ? 
SHT_DYNSYM411
:
SHT_SYMTAB3.61k
);
419
4.02k
420
4.02k
  if (!symtabSec)
421
3
    return;
422
4.02k
423
4.02k
  // Initialize members corresponding to a symbol table.
424
4.02k
  firstGlobal = symtabSec->sh_info;
425
4.02k
426
4.02k
  ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(symtabSec), this);
427
4.02k
  if (firstGlobal == 0 || firstGlobal > eSyms.size())
428
0
    fatal(toString(this) + ": invalid sh_info in symbol table");
429
4.02k
430
4.02k
  elfSyms = reinterpret_cast<const void *>(eSyms.data());
431
4.02k
  numELFSyms = eSyms.size();
432
4.02k
  stringTable = CHECK(obj.getStringTableForSymtab(*symtabSec, sections), this);
433
4.02k
}
void lld::elf::ELFFileBase::init<llvm::object::ELFType<(llvm::support::endianness)1, false> >()
Line
Count
Source
402
530
template <class ELFT> void ELFFileBase::init() {
403
530
  using Elf_Shdr = typename ELFT::Shdr;
404
530
  using Elf_Sym = typename ELFT::Sym;
405
530
406
530
  // Initialize trivial attributes.
407
530
  const ELFFile<ELFT> &obj = getObj<ELFT>();
408
530
  emachine = obj.getHeader()->e_machine;
409
530
  osabi = obj.getHeader()->e_ident[llvm::ELF::EI_OSABI];
410
530
  abiVersion = obj.getHeader()->e_ident[llvm::ELF::EI_ABIVERSION];
411
530
412
530
  ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
413
530
414
530
  // Find a symbol table.
415
530
  bool isDSO =
416
530
      (identify_magic(mb.getBuffer()) == file_magic::elf_shared_object);
417
530
  const Elf_Shdr *symtabSec =
418
530
      findSection(sections, isDSO ? 
SHT_DYNSYM67
:
SHT_SYMTAB463
);
419
530
420
530
  if (!symtabSec)
421
0
    return;
422
530
423
530
  // Initialize members corresponding to a symbol table.
424
530
  firstGlobal = symtabSec->sh_info;
425
530
426
530
  ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(symtabSec), this);
427
530
  if (firstGlobal == 0 || firstGlobal > eSyms.size())
428
0
    fatal(toString(this) + ": invalid sh_info in symbol table");
429
530
430
530
  elfSyms = reinterpret_cast<const void *>(eSyms.data());
431
530
  numELFSyms = eSyms.size();
432
530
  stringTable = CHECK(obj.getStringTableForSymtab(*symtabSec, sections), this);
433
530
}
void lld::elf::ELFFileBase::init<llvm::object::ELFType<(llvm::support::endianness)0, false> >()
Line
Count
Source
402
241
template <class ELFT> void ELFFileBase::init() {
403
241
  using Elf_Shdr = typename ELFT::Shdr;
404
241
  using Elf_Sym = typename ELFT::Sym;
405
241
406
241
  // Initialize trivial attributes.
407
241
  const ELFFile<ELFT> &obj = getObj<ELFT>();
408
241
  emachine = obj.getHeader()->e_machine;
409
241
  osabi = obj.getHeader()->e_ident[llvm::ELF::EI_OSABI];
410
241
  abiVersion = obj.getHeader()->e_ident[llvm::ELF::EI_ABIVERSION];
411
241
412
241
  ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
413
241
414
241
  // Find a symbol table.
415
241
  bool isDSO =
416
241
      (identify_magic(mb.getBuffer()) == file_magic::elf_shared_object);
417
241
  const Elf_Shdr *symtabSec =
418
241
      findSection(sections, isDSO ? 
SHT_DYNSYM29
:
SHT_SYMTAB212
);
419
241
420
241
  if (!symtabSec)
421
0
    return;
422
241
423
241
  // Initialize members corresponding to a symbol table.
424
241
  firstGlobal = symtabSec->sh_info;
425
241
426
241
  ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(symtabSec), this);
427
241
  if (firstGlobal == 0 || firstGlobal > eSyms.size())
428
0
    fatal(toString(this) + ": invalid sh_info in symbol table");
429
241
430
241
  elfSyms = reinterpret_cast<const void *>(eSyms.data());
431
241
  numELFSyms = eSyms.size();
432
241
  stringTable = CHECK(obj.getStringTableForSymtab(*symtabSec, sections), this);
433
241
}
void lld::elf::ELFFileBase::init<llvm::object::ELFType<(llvm::support::endianness)1, true> >()
Line
Count
Source
402
3.10k
template <class ELFT> void ELFFileBase::init() {
403
3.10k
  using Elf_Shdr = typename ELFT::Shdr;
404
3.10k
  using Elf_Sym = typename ELFT::Sym;
405
3.10k
406
3.10k
  // Initialize trivial attributes.
407
3.10k
  const ELFFile<ELFT> &obj = getObj<ELFT>();
408
3.10k
  emachine = obj.getHeader()->e_machine;
409
3.10k
  osabi = obj.getHeader()->e_ident[llvm::ELF::EI_OSABI];
410
3.10k
  abiVersion = obj.getHeader()->e_ident[llvm::ELF::EI_ABIVERSION];
411
3.10k
412
3.10k
  ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
413
3.10k
414
3.10k
  // Find a symbol table.
415
3.10k
  bool isDSO =
416
3.10k
      (identify_magic(mb.getBuffer()) == file_magic::elf_shared_object);
417
3.10k
  const Elf_Shdr *symtabSec =
418
3.10k
      findSection(sections, isDSO ? 
SHT_DYNSYM300
:
SHT_SYMTAB2.80k
);
419
3.10k
420
3.10k
  if (!symtabSec)
421
3
    return;
422
3.09k
423
3.09k
  // Initialize members corresponding to a symbol table.
424
3.09k
  firstGlobal = symtabSec->sh_info;
425
3.09k
426
3.09k
  ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(symtabSec), this);
427
3.09k
  if (firstGlobal == 0 || firstGlobal > eSyms.size())
428
0
    fatal(toString(this) + ": invalid sh_info in symbol table");
429
3.09k
430
3.09k
  elfSyms = reinterpret_cast<const void *>(eSyms.data());
431
3.09k
  numELFSyms = eSyms.size();
432
3.09k
  stringTable = CHECK(obj.getStringTableForSymtab(*symtabSec, sections), this);
433
3.09k
}
void lld::elf::ELFFileBase::init<llvm::object::ELFType<(llvm::support::endianness)0, true> >()
Line
Count
Source
402
153
template <class ELFT> void ELFFileBase::init() {
403
153
  using Elf_Shdr = typename ELFT::Shdr;
404
153
  using Elf_Sym = typename ELFT::Sym;
405
153
406
153
  // Initialize trivial attributes.
407
153
  const ELFFile<ELFT> &obj = getObj<ELFT>();
408
153
  emachine = obj.getHeader()->e_machine;
409
153
  osabi = obj.getHeader()->e_ident[llvm::ELF::EI_OSABI];
410
153
  abiVersion = obj.getHeader()->e_ident[llvm::ELF::EI_ABIVERSION];
411
153
412
153
  ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
413
153
414
153
  // Find a symbol table.
415
153
  bool isDSO =
416
153
      (identify_magic(mb.getBuffer()) == file_magic::elf_shared_object);
417
153
  const Elf_Shdr *symtabSec =
418
153
      findSection(sections, isDSO ? 
SHT_DYNSYM15
:
SHT_SYMTAB138
);
419
153
420
153
  if (!symtabSec)
421
0
    return;
422
153
423
153
  // Initialize members corresponding to a symbol table.
424
153
  firstGlobal = symtabSec->sh_info;
425
153
426
153
  ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(symtabSec), this);
427
153
  if (firstGlobal == 0 || firstGlobal > eSyms.size())
428
0
    fatal(toString(this) + ": invalid sh_info in symbol table");
429
153
430
153
  elfSyms = reinterpret_cast<const void *>(eSyms.data());
431
153
  numELFSyms = eSyms.size();
432
153
  stringTable = CHECK(obj.getStringTableForSymtab(*symtabSec, sections), this);
433
153
}
434
435
template <class ELFT>
436
88.8k
uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &sym) const {
437
88.8k
  return CHECK(
438
88.8k
      this->getObj().getSectionIndex(&sym, getELFSyms<ELFT>(), shndxTable),
439
88.8k
      this);
440
88.8k
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >::getSectionIndex(llvm::object::Elf_Sym_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false> > const&) const
Line
Count
Source
436
2.63k
uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &sym) const {
437
2.63k
  return CHECK(
438
2.63k
      this->getObj().getSectionIndex(&sym, getELFSyms<ELFT>(), shndxTable),
439
2.63k
      this);
440
2.63k
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >::getSectionIndex(llvm::object::Elf_Sym_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false> > const&) const
Line
Count
Source
436
830
uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &sym) const {
437
830
  return CHECK(
438
830
      this->getObj().getSectionIndex(&sym, getELFSyms<ELFT>(), shndxTable),
439
830
      this);
440
830
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >::getSectionIndex(llvm::object::Elf_Sym_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true> > const&) const
Line
Count
Source
436
74.8k
uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &sym) const {
437
74.8k
  return CHECK(
438
74.8k
      this->getObj().getSectionIndex(&sym, getELFSyms<ELFT>(), shndxTable),
439
74.8k
      this);
440
74.8k
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >::getSectionIndex(llvm::object::Elf_Sym_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true> > const&) const
Line
Count
Source
436
10.5k
uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &sym) const {
437
10.5k
  return CHECK(
438
10.5k
      this->getObj().getSectionIndex(&sym, getELFSyms<ELFT>(), shndxTable),
439
10.5k
      this);
440
10.5k
}
441
442
3.37k
template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getLocalSymbols() {
443
3.37k
  if (this->symbols.empty())
444
2
    return {};
445
3.37k
  return makeArrayRef(this->symbols).slice(1, this->firstGlobal - 1);
446
3.37k
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >::getLocalSymbols()
Line
Count
Source
442
436
template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getLocalSymbols() {
443
436
  if (this->symbols.empty())
444
0
    return {};
445
436
  return makeArrayRef(this->symbols).slice(1, this->firstGlobal - 1);
446
436
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >::getLocalSymbols()
Line
Count
Source
442
210
template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getLocalSymbols() {
443
210
  if (this->symbols.empty())
444
0
    return {};
445
210
  return makeArrayRef(this->symbols).slice(1, this->firstGlobal - 1);
446
210
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >::getLocalSymbols()
Line
Count
Source
442
2.59k
template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getLocalSymbols() {
443
2.59k
  if (this->symbols.empty())
444
2
    return {};
445
2.58k
  return makeArrayRef(this->symbols).slice(1, this->firstGlobal - 1);
446
2.58k
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >::getLocalSymbols()
Line
Count
Source
442
136
template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getLocalSymbols() {
443
136
  if (this->symbols.empty())
444
0
    return {};
445
136
  return makeArrayRef(this->symbols).slice(1, this->firstGlobal - 1);
446
136
}
447
448
214
template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getGlobalSymbols() {
449
214
  return makeArrayRef(this->symbols).slice(this->firstGlobal);
450
214
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >::getGlobalSymbols()
Line
Count
Source
448
2
template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getGlobalSymbols() {
449
2
  return makeArrayRef(this->symbols).slice(this->firstGlobal);
450
2
}
Unexecuted instantiation: lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >::getGlobalSymbols()
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >::getGlobalSymbols()
Line
Count
Source
448
212
template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getGlobalSymbols() {
449
212
  return makeArrayRef(this->symbols).slice(this->firstGlobal);
450
212
}
Unexecuted instantiation: lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >::getGlobalSymbols()
451
452
3.47k
template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) {
453
3.47k
  // Read a section table. justSymbols is usually false.
454
3.47k
  if (this->justSymbols)
455
3
    initializeJustSymbols();
456
3.46k
  else
457
3.46k
    initializeSections(ignoreComdats);
458
3.47k
459
3.47k
  // Read a symbol table.
460
3.47k
  initializeSymbols();
461
3.47k
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >::parse(bool)
Line
Count
Source
452
460
template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) {
453
460
  // Read a section table. justSymbols is usually false.
454
460
  if (this->justSymbols)
455
0
    initializeJustSymbols();
456
460
  else
457
460
    initializeSections(ignoreComdats);
458
460
459
460
  // Read a symbol table.
460
460
  initializeSymbols();
461
460
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >::parse(bool)
Line
Count
Source
452
210
template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) {
453
210
  // Read a section table. justSymbols is usually false.
454
210
  if (this->justSymbols)
455
0
    initializeJustSymbols();
456
210
  else
457
210
    initializeSections(ignoreComdats);
458
210
459
210
  // Read a symbol table.
460
210
  initializeSymbols();
461
210
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >::parse(bool)
Line
Count
Source
452
2.66k
template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) {
453
2.66k
  // Read a section table. justSymbols is usually false.
454
2.66k
  if (this->justSymbols)
455
3
    initializeJustSymbols();
456
2.66k
  else
457
2.66k
    initializeSections(ignoreComdats);
458
2.66k
459
2.66k
  // Read a symbol table.
460
2.66k
  initializeSymbols();
461
2.66k
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >::parse(bool)
Line
Count
Source
452
138
template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) {
453
138
  // Read a section table. justSymbols is usually false.
454
138
  if (this->justSymbols)
455
0
    initializeJustSymbols();
456
138
  else
457
138
    initializeSections(ignoreComdats);
458
138
459
138
  // Read a symbol table.
460
138
  initializeSymbols();
461
138
}
462
463
// Sections with SHT_GROUP and comdat bits define comdat section groups.
464
// They are identified and deduplicated by group name. This function
465
// returns a group name.
466
template <class ELFT>
467
StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> sections,
468
82
                                              const Elf_Shdr &sec) {
469
82
  typename ELFT::SymRange symbols = this->getELFSyms<ELFT>();
470
82
  if (sec.sh_info >= symbols.size())
471
0
    fatal(toString(this) + ": invalid symbol index");
472
82
  const typename ELFT::Sym &sym = symbols[sec.sh_info];
473
82
  StringRef signature = CHECK(sym.getName(this->stringTable), this);
474
82
475
82
  // As a special case, if a symbol is a section symbol and has no name,
476
82
  // we use a section name as a signature.
477
82
  //
478
82
  // Such SHT_GROUP sections are invalid from the perspective of the ELF
479
82
  // standard, but GNU gold 1.14 (the newest version as of July 2017) or
480
82
  // older produce such sections as outputs for the -r option, so we need
481
82
  // a bug-compatibility.
482
82
  if (signature.empty() && 
sym.getType() == STT_SECTION4
)
483
4
    return getSectionName(sec);
484
78
  return signature;
485
78
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >::getShtGroupSignature(llvm::ArrayRef<llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false> > >, llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false> > const&)
Line
Count
Source
468
2
                                              const Elf_Shdr &sec) {
469
2
  typename ELFT::SymRange symbols = this->getELFSyms<ELFT>();
470
2
  if (sec.sh_info >= symbols.size())
471
0
    fatal(toString(this) + ": invalid symbol index");
472
2
  const typename ELFT::Sym &sym = symbols[sec.sh_info];
473
2
  StringRef signature = CHECK(sym.getName(this->stringTable), this);
474
2
475
2
  // As a special case, if a symbol is a section symbol and has no name,
476
2
  // we use a section name as a signature.
477
2
  //
478
2
  // Such SHT_GROUP sections are invalid from the perspective of the ELF
479
2
  // standard, but GNU gold 1.14 (the newest version as of July 2017) or
480
2
  // older produce such sections as outputs for the -r option, so we need
481
2
  // a bug-compatibility.
482
2
  if (signature.empty() && 
sym.getType() == STT_SECTION0
)
483
0
    return getSectionName(sec);
484
2
  return signature;
485
2
}
Unexecuted instantiation: lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >::getShtGroupSignature(llvm::ArrayRef<llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false> > >, llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false> > const&)
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >::getShtGroupSignature(llvm::ArrayRef<llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true> > >, llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true> > const&)
Line
Count
Source
468
80
                                              const Elf_Shdr &sec) {
469
80
  typename ELFT::SymRange symbols = this->getELFSyms<ELFT>();
470
80
  if (sec.sh_info >= symbols.size())
471
0
    fatal(toString(this) + ": invalid symbol index");
472
80
  const typename ELFT::Sym &sym = symbols[sec.sh_info];
473
80
  StringRef signature = CHECK(sym.getName(this->stringTable), this);
474
80
475
80
  // As a special case, if a symbol is a section symbol and has no name,
476
80
  // we use a section name as a signature.
477
80
  //
478
80
  // Such SHT_GROUP sections are invalid from the perspective of the ELF
479
80
  // standard, but GNU gold 1.14 (the newest version as of July 2017) or
480
80
  // older produce such sections as outputs for the -r option, so we need
481
80
  // a bug-compatibility.
482
80
  if (signature.empty() && 
sym.getType() == STT_SECTION4
)
483
4
    return getSectionName(sec);
484
76
  return signature;
485
76
}
Unexecuted instantiation: lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >::getShtGroupSignature(llvm::ArrayRef<llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true> > >, llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true> > const&)
486
487
337k
template <class ELFT> bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec) {
488
337k
  // On a regular link we don't merge sections if -O0 (default is -O1). This
489
337k
  // sometimes makes the linker significantly faster, although the output will
490
337k
  // be bigger.
491
337k
  //
492
337k
  // Doing the same for -r would create a problem as it would combine sections
493
337k
  // with different sh_entsize. One option would be to just copy every SHF_MERGE
494
337k
  // section as is to the output. While this would produce a valid ELF file with
495
337k
  // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when
496
337k
  // they see two .debug_str. We could have separate logic for combining
497
337k
  // SHF_MERGE sections based both on their name and sh_entsize, but that seems
498
337k
  // to be more trouble than it is worth. Instead, we just use the regular (-O1)
499
337k
  // logic for -r.
500
337k
  if (config->optimize == 0 && 
!config->relocatable23
)
501
15
    return false;
502
337k
503
337k
  // A mergeable section with size 0 is useless because they don't have
504
337k
  // any data to merge. A mergeable string section with size 0 can be
505
337k
  // argued as invalid because it doesn't end with a null character.
506
337k
  // We'll avoid a mess by handling them as if they were non-mergeable.
507
337k
  if (sec.sh_size == 0)
508
331k
    return false;
509
6.06k
510
6.06k
  // Check for sh_entsize. The ELF spec is not clear about the zero
511
6.06k
  // sh_entsize. It says that "the member [sh_entsize] contains 0 if
512
6.06k
  // the section does not hold a table of fixed-size entries". We know
513
6.06k
  // that Rust 1.13 produces a string mergeable section with a zero
514
6.06k
  // sh_entsize. Here we just accept it rather than being picky about it.
515
6.06k
  uint64_t entSize = sec.sh_entsize;
516
6.06k
  if (entSize == 0)
517
5.42k
    return false;
518
641
  if (sec.sh_size % entSize)
519
0
    fatal(toString(this) +
520
0
          ": SHF_MERGE section size must be a multiple of sh_entsize");
521
641
522
641
  uint64_t flags = sec.sh_flags;
523
641
  if (!(flags & SHF_MERGE))
524
511
    return false;
525
130
  if (flags & SHF_WRITE)
526
0
    fatal(toString(this) + ": writable SHF_MERGE section is not supported");
527
130
528
130
  return true;
529
130
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >::shouldMerge(llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false> > const&)
Line
Count
Source
487
1.31k
template <class ELFT> bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec) {
488
1.31k
  // On a regular link we don't merge sections if -O0 (default is -O1). This
489
1.31k
  // sometimes makes the linker significantly faster, although the output will
490
1.31k
  // be bigger.
491
1.31k
  //
492
1.31k
  // Doing the same for -r would create a problem as it would combine sections
493
1.31k
  // with different sh_entsize. One option would be to just copy every SHF_MERGE
494
1.31k
  // section as is to the output. While this would produce a valid ELF file with
495
1.31k
  // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when
496
1.31k
  // they see two .debug_str. We could have separate logic for combining
497
1.31k
  // SHF_MERGE sections based both on their name and sh_entsize, but that seems
498
1.31k
  // to be more trouble than it is worth. Instead, we just use the regular (-O1)
499
1.31k
  // logic for -r.
500
1.31k
  if (config->optimize == 0 && 
!config->relocatable0
)
501
0
    return false;
502
1.31k
503
1.31k
  // A mergeable section with size 0 is useless because they don't have
504
1.31k
  // any data to merge. A mergeable string section with size 0 can be
505
1.31k
  // argued as invalid because it doesn't end with a null character.
506
1.31k
  // We'll avoid a mess by handling them as if they were non-mergeable.
507
1.31k
  if (sec.sh_size == 0)
508
239
    return false;
509
1.07k
510
1.07k
  // Check for sh_entsize. The ELF spec is not clear about the zero
511
1.07k
  // sh_entsize. It says that "the member [sh_entsize] contains 0 if
512
1.07k
  // the section does not hold a table of fixed-size entries". We know
513
1.07k
  // that Rust 1.13 produces a string mergeable section with a zero
514
1.07k
  // sh_entsize. Here we just accept it rather than being picky about it.
515
1.07k
  uint64_t entSize = sec.sh_entsize;
516
1.07k
  if (entSize == 0)
517
1.01k
    return false;
518
61
  if (sec.sh_size % entSize)
519
0
    fatal(toString(this) +
520
0
          ": SHF_MERGE section size must be a multiple of sh_entsize");
521
61
522
61
  uint64_t flags = sec.sh_flags;
523
61
  if (!(flags & SHF_MERGE))
524
56
    return false;
525
5
  if (flags & SHF_WRITE)
526
0
    fatal(toString(this) + ": writable SHF_MERGE section is not supported");
527
5
528
5
  return true;
529
5
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >::shouldMerge(llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false> > const&)
Line
Count
Source
487
954
template <class ELFT> bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec) {
488
954
  // On a regular link we don't merge sections if -O0 (default is -O1). This
489
954
  // sometimes makes the linker significantly faster, although the output will
490
954
  // be bigger.
491
954
  //
492
954
  // Doing the same for -r would create a problem as it would combine sections
493
954
  // with different sh_entsize. One option would be to just copy every SHF_MERGE
494
954
  // section as is to the output. While this would produce a valid ELF file with
495
954
  // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when
496
954
  // they see two .debug_str. We could have separate logic for combining
497
954
  // SHF_MERGE sections based both on their name and sh_entsize, but that seems
498
954
  // to be more trouble than it is worth. Instead, we just use the regular (-O1)
499
954
  // logic for -r.
500
954
  if (config->optimize == 0 && 
!config->relocatable0
)
501
0
    return false;
502
954
503
954
  // A mergeable section with size 0 is useless because they don't have
504
954
  // any data to merge. A mergeable string section with size 0 can be
505
954
  // argued as invalid because it doesn't end with a null character.
506
954
  // We'll avoid a mess by handling them as if they were non-mergeable.
507
954
  if (sec.sh_size == 0)
508
329
    return false;
509
625
510
625
  // Check for sh_entsize. The ELF spec is not clear about the zero
511
625
  // sh_entsize. It says that "the member [sh_entsize] contains 0 if
512
625
  // the section does not hold a table of fixed-size entries". We know
513
625
  // that Rust 1.13 produces a string mergeable section with a zero
514
625
  // sh_entsize. Here we just accept it rather than being picky about it.
515
625
  uint64_t entSize = sec.sh_entsize;
516
625
  if (entSize == 0)
517
288
    return false;
518
337
  if (sec.sh_size % entSize)
519
0
    fatal(toString(this) +
520
0
          ": SHF_MERGE section size must be a multiple of sh_entsize");
521
337
522
337
  uint64_t flags = sec.sh_flags;
523
337
  if (!(flags & SHF_MERGE))
524
336
    return false;
525
1
  if (flags & SHF_WRITE)
526
0
    fatal(toString(this) + ": writable SHF_MERGE section is not supported");
527
1
528
1
  return true;
529
1
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >::shouldMerge(llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true> > const&)
Line
Count
Source
487
334k
template <class ELFT> bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec) {
488
334k
  // On a regular link we don't merge sections if -O0 (default is -O1). This
489
334k
  // sometimes makes the linker significantly faster, although the output will
490
334k
  // be bigger.
491
334k
  //
492
334k
  // Doing the same for -r would create a problem as it would combine sections
493
334k
  // with different sh_entsize. One option would be to just copy every SHF_MERGE
494
334k
  // section as is to the output. While this would produce a valid ELF file with
495
334k
  // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when
496
334k
  // they see two .debug_str. We could have separate logic for combining
497
334k
  // SHF_MERGE sections based both on their name and sh_entsize, but that seems
498
334k
  // to be more trouble than it is worth. Instead, we just use the regular (-O1)
499
334k
  // logic for -r.
500
334k
  if (config->optimize == 0 && 
!config->relocatable23
)
501
15
    return false;
502
334k
503
334k
  // A mergeable section with size 0 is useless because they don't have
504
334k
  // any data to merge. A mergeable string section with size 0 can be
505
334k
  // argued as invalid because it doesn't end with a null character.
506
334k
  // We'll avoid a mess by handling them as if they were non-mergeable.
507
334k
  if (sec.sh_size == 0)
508
330k
    return false;
509
4.07k
510
4.07k
  // Check for sh_entsize. The ELF spec is not clear about the zero
511
4.07k
  // sh_entsize. It says that "the member [sh_entsize] contains 0 if
512
4.07k
  // the section does not hold a table of fixed-size entries". We know
513
4.07k
  // that Rust 1.13 produces a string mergeable section with a zero
514
4.07k
  // sh_entsize. Here we just accept it rather than being picky about it.
515
4.07k
  uint64_t entSize = sec.sh_entsize;
516
4.07k
  if (entSize == 0)
517
3.93k
    return false;
518
140
  if (sec.sh_size % entSize)
519
0
    fatal(toString(this) +
520
0
          ": SHF_MERGE section size must be a multiple of sh_entsize");
521
140
522
140
  uint64_t flags = sec.sh_flags;
523
140
  if (!(flags & SHF_MERGE))
524
16
    return false;
525
124
  if (flags & SHF_WRITE)
526
0
    fatal(toString(this) + ": writable SHF_MERGE section is not supported");
527
124
528
124
  return true;
529
124
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >::shouldMerge(llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true> > const&)
Line
Count
Source
487
400
template <class ELFT> bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec) {
488
400
  // On a regular link we don't merge sections if -O0 (default is -O1). This
489
400
  // sometimes makes the linker significantly faster, although the output will
490
400
  // be bigger.
491
400
  //
492
400
  // Doing the same for -r would create a problem as it would combine sections
493
400
  // with different sh_entsize. One option would be to just copy every SHF_MERGE
494
400
  // section as is to the output. While this would produce a valid ELF file with
495
400
  // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when
496
400
  // they see two .debug_str. We could have separate logic for combining
497
400
  // SHF_MERGE sections based both on their name and sh_entsize, but that seems
498
400
  // to be more trouble than it is worth. Instead, we just use the regular (-O1)
499
400
  // logic for -r.
500
400
  if (config->optimize == 0 && 
!config->relocatable0
)
501
0
    return false;
502
400
503
400
  // A mergeable section with size 0 is useless because they don't have
504
400
  // any data to merge. A mergeable string section with size 0 can be
505
400
  // argued as invalid because it doesn't end with a null character.
506
400
  // We'll avoid a mess by handling them as if they were non-mergeable.
507
400
  if (sec.sh_size == 0)
508
105
    return false;
509
295
510
295
  // Check for sh_entsize. The ELF spec is not clear about the zero
511
295
  // sh_entsize. It says that "the member [sh_entsize] contains 0 if
512
295
  // the section does not hold a table of fixed-size entries". We know
513
295
  // that Rust 1.13 produces a string mergeable section with a zero
514
295
  // sh_entsize. Here we just accept it rather than being picky about it.
515
295
  uint64_t entSize = sec.sh_entsize;
516
295
  if (entSize == 0)
517
192
    return false;
518
103
  if (sec.sh_size % entSize)
519
0
    fatal(toString(this) +
520
0
          ": SHF_MERGE section size must be a multiple of sh_entsize");
521
103
522
103
  uint64_t flags = sec.sh_flags;
523
103
  if (!(flags & SHF_MERGE))
524
103
    return false;
525
0
  if (flags & SHF_WRITE)
526
0
    fatal(toString(this) + ": writable SHF_MERGE section is not supported");
527
0
528
0
  return true;
529
0
}
530
531
// This is for --just-symbols.
532
//
533
// --just-symbols is a very minor feature that allows you to link your
534
// output against other existing program, so that if you load both your
535
// program and the other program into memory, your output can refer the
536
// other program's symbols.
537
//
538
// When the option is given, we link "just symbols". The section table is
539
// initialized with null pointers.
540
3
template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() {
541
3
  ArrayRef<Elf_Shdr> sections = CHECK(this->getObj().sections(), this);
542
3
  this->sections.resize(sections.size());
543
3
}
Unexecuted instantiation: lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >::initializeJustSymbols()
Unexecuted instantiation: lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >::initializeJustSymbols()
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >::initializeJustSymbols()
Line
Count
Source
540
3
template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() {
541
3
  ArrayRef<Elf_Shdr> sections = CHECK(this->getObj().sections(), this);
542
3
  this->sections.resize(sections.size());
543
3
}
Unexecuted instantiation: lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >::initializeJustSymbols()
544
545
// An ELF object file may contain a `.deplibs` section. If it exists, the
546
// section contains a list of library specifiers such as `m` for libm. This
547
// function resolves a given name by finding the first matching library checking
548
// the various ways that a library can be specified to LLD. This ELF extension
549
// is a form of autolinking and is called `dependent libraries`. It is currently
550
// unique to LLVM and lld.
551
17
static void addDependentLibrary(StringRef specifier, const InputFile *f) {
552
17
  if (!config->dependentLibraries)
553
2
    return;
554
15
  if (fs::exists(specifier))
555
1
    driver->addFile(specifier, /*withLOption=*/false);
556
14
  else if (Optional<std::string> s = findFromSearchPaths(specifier))
557
3
    driver->addFile(*s, /*withLOption=*/true);
558
11
  else if (Optional<std::string> s = searchLibraryBaseName(specifier))
559
4
    driver->addFile(*s, /*withLOption=*/true);
560
7
  else
561
7
    error(toString(f) +
562
7
          ": unable to find library from dependent library specifier: " +
563
7
          specifier);
564
15
}
565
566
template <class ELFT>
567
3.46k
void ObjFile<ELFT>::initializeSections(bool ignoreComdats) {
568
3.46k
  const ELFFile<ELFT> &obj = this->getObj();
569
3.46k
570
3.46k
  ArrayRef<Elf_Shdr> objSections = CHECK(obj.sections(), this);
571
3.46k
  uint64_t size = objSections.size();
572
3.46k
  this->sections.resize(size);
573
3.46k
  this->sectionStringTable =
574
3.46k
      CHECK(obj.getSectionStringTable(objSections), this);
575
3.46k
576
354k
  for (size_t i = 0, e = objSections.size(); i < e; 
++i350k
) {
577
350k
    if (this->sections[i] == &InputSection::discarded)
578
29
      continue;
579
350k
    const Elf_Shdr &sec = objSections[i];
580
350k
581
350k
    if (sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH_PROFILE)
582
9
      cgProfile =
583
9
          check(obj.template getSectionContentsAsArray<Elf_CGProfile>(&sec));
584
350k
585
350k
    // SHF_EXCLUDE'ed sections are discarded by the linker. However,
586
350k
    // if -r is given, we'll let the final link discard such sections.
587
350k
    // This is compatible with GNU.
588
350k
    if ((sec.sh_flags & SHF_EXCLUDE) && 
!config->relocatable234
) {
589
228
      if (sec.sh_type == SHT_LLVM_ADDRSIG) {
590
215
        // We ignore the address-significance table if we know that the object
591
215
        // file was created by objcopy or ld -r. This is because these tools
592
215
        // will reorder the symbols in the symbol table, invalidating the data
593
215
        // in the address-significance table, which refers to symbols by index.
594
215
        if (sec.sh_link != 0)
595
214
          this->addrsigSec = &sec;
596
1
        else if (config->icf == ICFLevel::Safe)
597
1
          warn(toString(this) + ": --icf=safe is incompatible with object "
598
1
                                "files created using objcopy or ld -r");
599
215
      }
600
228
      this->sections[i] = &InputSection::discarded;
601
228
      continue;
602
228
    }
603
350k
604
350k
    switch (sec.sh_type) {
605
350k
    case SHT_GROUP: {
606
79
      // De-duplicate section groups by their signatures.
607
79
      StringRef signature = getShtGroupSignature(objSections, sec);
608
79
      this->sections[i] = &InputSection::discarded;
609
79
610
79
611
79
      ArrayRef<Elf_Word> entries =
612
79
          CHECK(obj.template getSectionContentsAsArray<Elf_Word>(&sec), this);
613
79
      if (entries.empty())
614
0
        fatal(toString(this) + ": empty SHT_GROUP");
615
79
616
79
      // The first word of a SHT_GROUP section contains flags. Currently,
617
79
      // the standard defines only "GRP_COMDAT" flag for the COMDAT group.
618
79
      // An group with the empty flag doesn't define anything; such sections
619
79
      // are just skipped.
620
79
      if (entries[0] == 0)
621
0
        continue;
622
79
623
79
      if (entries[0] != GRP_COMDAT)
624
0
        fatal(toString(this) + ": unsupported SHT_GROUP format");
625
79
626
79
      bool isNew =
627
79
          ignoreComdats ||
628
79
          symtab->comdatGroups.try_emplace(CachedHashStringRef(signature), this)
629
77
              .second;
630
79
      if (isNew) {
631
53
        if (config->relocatable)
632
10
          this->sections[i] = createInputSection(sec);
633
53
        continue;
634
53
      }
635
26
636
26
      // Otherwise, discard group members.
637
29
      
for (uint32_t secIndex : entries.slice(1))26
{
638
29
        if (secIndex >= size)
639
0
          fatal(toString(this) +
640
0
                ": invalid section index in group: " + Twine(secIndex));
641
29
        this->sections[secIndex] = &InputSection::discarded;
642
29
      }
643
26
      break;
644
26
    }
645
26
    case SHT_SYMTAB_SHNDX:
646
5
      shndxTable = CHECK(obj.getSHNDXTable(sec, objSections), this);
647
5
      break;
648
10.4k
    case SHT_SYMTAB:
649
10.4k
    case SHT_STRTAB:
650
10.4k
    case SHT_NULL:
651
10.4k
      break;
652
339k
    default:
653
339k
      this->sections[i] = createInputSection(sec);
654
350k
    }
655
350k
  }
656
3.46k
657
354k
  
for (size_t i = 0, e = objSections.size(); 3.46k
i < e;
++i350k
) {
658
350k
    if (this->sections[i] == &InputSection::discarded)
659
681
      continue;
660
349k
    const Elf_Shdr &sec = objSections[i];
661
349k
    if (!(sec.sh_flags & SHF_LINK_ORDER))
662
349k
      continue;
663
106
664
106
    // .ARM.exidx sections have a reverse dependency on the InputSection they
665
106
    // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
666
106
    InputSectionBase *linkSec = nullptr;
667
106
    if (sec.sh_link < this->sections.size())
668
106
      linkSec = this->sections[sec.sh_link];
669
106
    if (!linkSec)
670
0
      fatal(toString(this) + ": invalid sh_link index: " + Twine(sec.sh_link));
671
106
672
106
    InputSection *isec = cast<InputSection>(this->sections[i]);
673
106
    linkSec->dependentSections.push_back(isec);
674
106
    if (!isa<InputSection>(linkSec))
675
3
      error("a section " + isec->name +
676
3
            " with SHF_LINK_ORDER should not refer a non-regular section: " +
677
3
            toString(linkSec));
678
106
  }
679
3.46k
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >::initializeSections(bool)
Line
Count
Source
567
460
void ObjFile<ELFT>::initializeSections(bool ignoreComdats) {
568
460
  const ELFFile<ELFT> &obj = this->getObj();
569
460
570
460
  ArrayRef<Elf_Shdr> objSections = CHECK(obj.sections(), this);
571
460
  uint64_t size = objSections.size();
572
460
  this->sections.resize(size);
573
460
  this->sectionStringTable =
574
460
      CHECK(obj.getSectionStringTable(objSections), this);
575
460
576
3.71k
  for (size_t i = 0, e = objSections.size(); i < e; 
++i3.25k
) {
577
3.25k
    if (this->sections[i] == &InputSection::discarded)
578
0
      continue;
579
3.25k
    const Elf_Shdr &sec = objSections[i];
580
3.25k
581
3.25k
    if (sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH_PROFILE)
582
0
      cgProfile =
583
0
          check(obj.template getSectionContentsAsArray<Elf_CGProfile>(&sec));
584
3.25k
585
3.25k
    // SHF_EXCLUDE'ed sections are discarded by the linker. However,
586
3.25k
    // if -r is given, we'll let the final link discard such sections.
587
3.25k
    // This is compatible with GNU.
588
3.25k
    if ((sec.sh_flags & SHF_EXCLUDE) && 
!config->relocatable2
) {
589
2
      if (sec.sh_type == SHT_LLVM_ADDRSIG) {
590
2
        // We ignore the address-significance table if we know that the object
591
2
        // file was created by objcopy or ld -r. This is because these tools
592
2
        // will reorder the symbols in the symbol table, invalidating the data
593
2
        // in the address-significance table, which refers to symbols by index.
594
2
        if (sec.sh_link != 0)
595
2
          this->addrsigSec = &sec;
596
0
        else if (config->icf == ICFLevel::Safe)
597
0
          warn(toString(this) + ": --icf=safe is incompatible with object "
598
0
                                "files created using objcopy or ld -r");
599
2
      }
600
2
      this->sections[i] = &InputSection::discarded;
601
2
      continue;
602
2
    }
603
3.24k
604
3.24k
    switch (sec.sh_type) {
605
3.24k
    case SHT_GROUP: {
606
2
      // De-duplicate section groups by their signatures.
607
2
      StringRef signature = getShtGroupSignature(objSections, sec);
608
2
      this->sections[i] = &InputSection::discarded;
609
2
610
2
611
2
      ArrayRef<Elf_Word> entries =
612
2
          CHECK(obj.template getSectionContentsAsArray<Elf_Word>(&sec), this);
613
2
      if (entries.empty())
614
0
        fatal(toString(this) + ": empty SHT_GROUP");
615
2
616
2
      // The first word of a SHT_GROUP section contains flags. Currently,
617
2
      // the standard defines only "GRP_COMDAT" flag for the COMDAT group.
618
2
      // An group with the empty flag doesn't define anything; such sections
619
2
      // are just skipped.
620
2
      if (entries[0] == 0)
621
0
        continue;
622
2
623
2
      if (entries[0] != GRP_COMDAT)
624
0
        fatal(toString(this) + ": unsupported SHT_GROUP format");
625
2
626
2
      bool isNew =
627
2
          ignoreComdats ||
628
2
          symtab->comdatGroups.try_emplace(CachedHashStringRef(signature), this)
629
2
              .second;
630
2
      if (isNew) {
631
2
        if (config->relocatable)
632
0
          this->sections[i] = createInputSection(sec);
633
2
        continue;
634
2
      }
635
0
636
0
      // Otherwise, discard group members.
637
0
      for (uint32_t secIndex : entries.slice(1)) {
638
0
        if (secIndex >= size)
639
0
          fatal(toString(this) +
640
0
                ": invalid section index in group: " + Twine(secIndex));
641
0
        this->sections[secIndex] = &InputSection::discarded;
642
0
      }
643
0
      break;
644
0
    }
645
0
    case SHT_SYMTAB_SHNDX:
646
0
      shndxTable = CHECK(obj.getSHNDXTable(sec, objSections), this);
647
0
      break;
648
1.39k
    case SHT_SYMTAB:
649
1.39k
    case SHT_STRTAB:
650
1.39k
    case SHT_NULL:
651
1.39k
      break;
652
1.85k
    default:
653
1.85k
      this->sections[i] = createInputSection(sec);
654
3.24k
    }
655
3.24k
  }
656
460
657
3.71k
  
for (size_t i = 0, e = objSections.size(); 460
i < e;
++i3.25k
) {
658
3.25k
    if (this->sections[i] == &InputSection::discarded)
659
45
      continue;
660
3.20k
    const Elf_Shdr &sec = objSections[i];
661
3.20k
    if (!(sec.sh_flags & SHF_LINK_ORDER))
662
3.12k
      continue;
663
81
664
81
    // .ARM.exidx sections have a reverse dependency on the InputSection they
665
81
    // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
666
81
    InputSectionBase *linkSec = nullptr;
667
81
    if (sec.sh_link < this->sections.size())
668
81
      linkSec = this->sections[sec.sh_link];
669
81
    if (!linkSec)
670
0
      fatal(toString(this) + ": invalid sh_link index: " + Twine(sec.sh_link));
671
81
672
81
    InputSection *isec = cast<InputSection>(this->sections[i]);
673
81
    linkSec->dependentSections.push_back(isec);
674
81
    if (!isa<InputSection>(linkSec))
675
0
      error("a section " + isec->name +
676
0
            " with SHF_LINK_ORDER should not refer a non-regular section: " +
677
0
            toString(linkSec));
678
81
  }
679
460
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >::initializeSections(bool)
Line
Count
Source
567
210
void ObjFile<ELFT>::initializeSections(bool ignoreComdats) {
568
210
  const ELFFile<ELFT> &obj = this->getObj();
569
210
570
210
  ArrayRef<Elf_Shdr> objSections = CHECK(obj.sections(), this);
571
210
  uint64_t size = objSections.size();
572
210
  this->sections.resize(size);
573
210
  this->sectionStringTable =
574
210
      CHECK(obj.getSectionStringTable(objSections), this);
575
210
576
1.95k
  for (size_t i = 0, e = objSections.size(); i < e; 
++i1.74k
) {
577
1.74k
    if (this->sections[i] == &InputSection::discarded)
578
0
      continue;
579
1.74k
    const Elf_Shdr &sec = objSections[i];
580
1.74k
581
1.74k
    if (sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH_PROFILE)
582
0
      cgProfile =
583
0
          check(obj.template getSectionContentsAsArray<Elf_CGProfile>(&sec));
584
1.74k
585
1.74k
    // SHF_EXCLUDE'ed sections are discarded by the linker. However,
586
1.74k
    // if -r is given, we'll let the final link discard such sections.
587
1.74k
    // This is compatible with GNU.
588
1.74k
    if ((sec.sh_flags & SHF_EXCLUDE) && 
!config->relocatable0
) {
589
0
      if (sec.sh_type == SHT_LLVM_ADDRSIG) {
590
0
        // We ignore the address-significance table if we know that the object
591
0
        // file was created by objcopy or ld -r. This is because these tools
592
0
        // will reorder the symbols in the symbol table, invalidating the data
593
0
        // in the address-significance table, which refers to symbols by index.
594
0
        if (sec.sh_link != 0)
595
0
          this->addrsigSec = &sec;
596
0
        else if (config->icf == ICFLevel::Safe)
597
0
          warn(toString(this) + ": --icf=safe is incompatible with object "
598
0
                                "files created using objcopy or ld -r");
599
0
      }
600
0
      this->sections[i] = &InputSection::discarded;
601
0
      continue;
602
0
    }
603
1.74k
604
1.74k
    switch (sec.sh_type) {
605
1.74k
    case SHT_GROUP: {
606
0
      // De-duplicate section groups by their signatures.
607
0
      StringRef signature = getShtGroupSignature(objSections, sec);
608
0
      this->sections[i] = &InputSection::discarded;
609
0
610
0
611
0
      ArrayRef<Elf_Word> entries =
612
0
          CHECK(obj.template getSectionContentsAsArray<Elf_Word>(&sec), this);
613
0
      if (entries.empty())
614
0
        fatal(toString(this) + ": empty SHT_GROUP");
615
0
616
0
      // The first word of a SHT_GROUP section contains flags. Currently,
617
0
      // the standard defines only "GRP_COMDAT" flag for the COMDAT group.
618
0
      // An group with the empty flag doesn't define anything; such sections
619
0
      // are just skipped.
620
0
      if (entries[0] == 0)
621
0
        continue;
622
0
623
0
      if (entries[0] != GRP_COMDAT)
624
0
        fatal(toString(this) + ": unsupported SHT_GROUP format");
625
0
626
0
      bool isNew =
627
0
          ignoreComdats ||
628
0
          symtab->comdatGroups.try_emplace(CachedHashStringRef(signature), this)
629
0
              .second;
630
0
      if (isNew) {
631
0
        if (config->relocatable)
632
0
          this->sections[i] = createInputSection(sec);
633
0
        continue;
634
0
      }
635
0
636
0
      // Otherwise, discard group members.
637
0
      for (uint32_t secIndex : entries.slice(1)) {
638
0
        if (secIndex >= size)
639
0
          fatal(toString(this) +
640
0
                ": invalid section index in group: " + Twine(secIndex));
641
0
        this->sections[secIndex] = &InputSection::discarded;
642
0
      }
643
0
      break;
644
0
    }
645
0
    case SHT_SYMTAB_SHNDX:
646
0
      shndxTable = CHECK(obj.getSHNDXTable(sec, objSections), this);
647
0
      break;
648
646
    case SHT_SYMTAB:
649
646
    case SHT_STRTAB:
650
646
    case SHT_NULL:
651
646
      break;
652
1.09k
    default:
653
1.09k
      this->sections[i] = createInputSection(sec);
654
1.74k
    }
655
1.74k
  }
656
210
657
1.95k
  
for (size_t i = 0, e = objSections.size(); 210
i < e;
++i1.74k
) {
658
1.74k
    if (this->sections[i] == &InputSection::discarded)
659
10
      continue;
660
1.73k
    const Elf_Shdr &sec = objSections[i];
661
1.73k
    if (!(sec.sh_flags & SHF_LINK_ORDER))
662
1.73k
      continue;
663
0
664
0
    // .ARM.exidx sections have a reverse dependency on the InputSection they
665
0
    // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
666
0
    InputSectionBase *linkSec = nullptr;
667
0
    if (sec.sh_link < this->sections.size())
668
0
      linkSec = this->sections[sec.sh_link];
669
0
    if (!linkSec)
670
0
      fatal(toString(this) + ": invalid sh_link index: " + Twine(sec.sh_link));
671
0
672
0
    InputSection *isec = cast<InputSection>(this->sections[i]);
673
0
    linkSec->dependentSections.push_back(isec);
674
0
    if (!isa<InputSection>(linkSec))
675
0
      error("a section " + isec->name +
676
0
            " with SHF_LINK_ORDER should not refer a non-regular section: " +
677
0
            toString(linkSec));
678
0
  }
679
210
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >::initializeSections(bool)
Line
Count
Source
567
2.66k
void ObjFile<ELFT>::initializeSections(bool ignoreComdats) {
568
2.66k
  const ELFFile<ELFT> &obj = this->getObj();
569
2.66k
570
2.66k
  ArrayRef<Elf_Shdr> objSections = CHECK(obj.sections(), this);
571
2.66k
  uint64_t size = objSections.size();
572
2.66k
  this->sections.resize(size);
573
2.66k
  this->sectionStringTable =
574
2.66k
      CHECK(obj.getSectionStringTable(objSections), this);
575
2.66k
576
347k
  for (size_t i = 0, e = objSections.size(); i < e; 
++i344k
) {
577
344k
    if (this->sections[i] == &InputSection::discarded)
578
29
      continue;
579
344k
    const Elf_Shdr &sec = objSections[i];
580
344k
581
344k
    if (sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH_PROFILE)
582
9
      cgProfile =
583
9
          check(obj.template getSectionContentsAsArray<Elf_CGProfile>(&sec));
584
344k
585
344k
    // SHF_EXCLUDE'ed sections are discarded by the linker. However,
586
344k
    // if -r is given, we'll let the final link discard such sections.
587
344k
    // This is compatible with GNU.
588
344k
    if ((sec.sh_flags & SHF_EXCLUDE) && 
!config->relocatable232
) {
589
226
      if (sec.sh_type == SHT_LLVM_ADDRSIG) {
590
213
        // We ignore the address-significance table if we know that the object
591
213
        // file was created by objcopy or ld -r. This is because these tools
592
213
        // will reorder the symbols in the symbol table, invalidating the data
593
213
        // in the address-significance table, which refers to symbols by index.
594
213
        if (sec.sh_link != 0)
595
212
          this->addrsigSec = &sec;
596
1
        else if (config->icf == ICFLevel::Safe)
597
1
          warn(toString(this) + ": --icf=safe is incompatible with object "
598
1
                                "files created using objcopy or ld -r");
599
213
      }
600
226
      this->sections[i] = &InputSection::discarded;
601
226
      continue;
602
226
    }
603
344k
604
344k
    switch (sec.sh_type) {
605
344k
    case SHT_GROUP: {
606
77
      // De-duplicate section groups by their signatures.
607
77
      StringRef signature = getShtGroupSignature(objSections, sec);
608
77
      this->sections[i] = &InputSection::discarded;
609
77
610
77
611
77
      ArrayRef<Elf_Word> entries =
612
77
          CHECK(obj.template getSectionContentsAsArray<Elf_Word>(&sec), this);
613
77
      if (entries.empty())
614
0
        fatal(toString(this) + ": empty SHT_GROUP");
615
77
616
77
      // The first word of a SHT_GROUP section contains flags. Currently,
617
77
      // the standard defines only "GRP_COMDAT" flag for the COMDAT group.
618
77
      // An group with the empty flag doesn't define anything; such sections
619
77
      // are just skipped.
620
77
      if (entries[0] == 0)
621
0
        continue;
622
77
623
77
      if (entries[0] != GRP_COMDAT)
624
0
        fatal(toString(this) + ": unsupported SHT_GROUP format");
625
77
626
77
      bool isNew =
627
77
          ignoreComdats ||
628
77
          symtab->comdatGroups.try_emplace(CachedHashStringRef(signature), this)
629
75
              .second;
630
77
      if (isNew) {
631
51
        if (config->relocatable)
632
10
          this->sections[i] = createInputSection(sec);
633
51
        continue;
634
51
      }
635
26
636
26
      // Otherwise, discard group members.
637
29
      
for (uint32_t secIndex : entries.slice(1))26
{
638
29
        if (secIndex >= size)
639
0
          fatal(toString(this) +
640
0
                ": invalid section index in group: " + Twine(secIndex));
641
29
        this->sections[secIndex] = &InputSection::discarded;
642
29
      }
643
26
      break;
644
26
    }
645
26
    case SHT_SYMTAB_SHNDX:
646
5
      shndxTable = CHECK(obj.getSHNDXTable(sec, objSections), this);
647
5
      break;
648
8.01k
    case SHT_SYMTAB:
649
8.01k
    case SHT_STRTAB:
650
8.01k
    case SHT_NULL:
651
8.01k
      break;
652
336k
    default:
653
336k
      this->sections[i] = createInputSection(sec);
654
344k
    }
655
344k
  }
656
2.66k
657
347k
  
for (size_t i = 0, e = objSections.size(); 2.66k
i < e;
++i344k
) {
658
344k
    if (this->sections[i] == &InputSection::discarded)
659
618
      continue;
660
344k
    const Elf_Shdr &sec = objSections[i];
661
344k
    if (!(sec.sh_flags & SHF_LINK_ORDER))
662
344k
      continue;
663
25
664
25
    // .ARM.exidx sections have a reverse dependency on the InputSection they
665
25
    // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
666
25
    InputSectionBase *linkSec = nullptr;
667
25
    if (sec.sh_link < this->sections.size())
668
25
      linkSec = this->sections[sec.sh_link];
669
25
    if (!linkSec)
670
0
      fatal(toString(this) + ": invalid sh_link index: " + Twine(sec.sh_link));
671
25
672
25
    InputSection *isec = cast<InputSection>(this->sections[i]);
673
25
    linkSec->dependentSections.push_back(isec);
674
25
    if (!isa<InputSection>(linkSec))
675
3
      error("a section " + isec->name +
676
3
            " with SHF_LINK_ORDER should not refer a non-regular section: " +
677
3
            toString(linkSec));
678
25
  }
679
2.66k
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >::initializeSections(bool)
Line
Count
Source
567
138
void ObjFile<ELFT>::initializeSections(bool ignoreComdats) {
568
138
  const ELFFile<ELFT> &obj = this->getObj();
569
138
570
138
  ArrayRef<Elf_Shdr> objSections = CHECK(obj.sections(), this);
571
138
  uint64_t size = objSections.size();
572
138
  this->sections.resize(size);
573
138
  this->sectionStringTable =
574
138
      CHECK(obj.getSectionStringTable(objSections), this);
575
138
576
1.08k
  for (size_t i = 0, e = objSections.size(); i < e; 
++i949
) {
577
949
    if (this->sections[i] == &InputSection::discarded)
578
0
      continue;
579
949
    const Elf_Shdr &sec = objSections[i];
580
949
581
949
    if (sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH_PROFILE)
582
0
      cgProfile =
583
0
          check(obj.template getSectionContentsAsArray<Elf_CGProfile>(&sec));
584
949
585
949
    // SHF_EXCLUDE'ed sections are discarded by the linker. However,
586
949
    // if -r is given, we'll let the final link discard such sections.
587
949
    // This is compatible with GNU.
588
949
    if ((sec.sh_flags & SHF_EXCLUDE) && 
!config->relocatable0
) {
589
0
      if (sec.sh_type == SHT_LLVM_ADDRSIG) {
590
0
        // We ignore the address-significance table if we know that the object
591
0
        // file was created by objcopy or ld -r. This is because these tools
592
0
        // will reorder the symbols in the symbol table, invalidating the data
593
0
        // in the address-significance table, which refers to symbols by index.
594
0
        if (sec.sh_link != 0)
595
0
          this->addrsigSec = &sec;
596
0
        else if (config->icf == ICFLevel::Safe)
597
0
          warn(toString(this) + ": --icf=safe is incompatible with object "
598
0
                                "files created using objcopy or ld -r");
599
0
      }
600
0
      this->sections[i] = &InputSection::discarded;
601
0
      continue;
602
0
    }
603
949
604
949
    switch (sec.sh_type) {
605
949
    case SHT_GROUP: {
606
0
      // De-duplicate section groups by their signatures.
607
0
      StringRef signature = getShtGroupSignature(objSections, sec);
608
0
      this->sections[i] = &InputSection::discarded;
609
0
610
0
611
0
      ArrayRef<Elf_Word> entries =
612
0
          CHECK(obj.template getSectionContentsAsArray<Elf_Word>(&sec), this);
613
0
      if (entries.empty())
614
0
        fatal(toString(this) + ": empty SHT_GROUP");
615
0
616
0
      // The first word of a SHT_GROUP section contains flags. Currently,
617
0
      // the standard defines only "GRP_COMDAT" flag for the COMDAT group.
618
0
      // An group with the empty flag doesn't define anything; such sections
619
0
      // are just skipped.
620
0
      if (entries[0] == 0)
621
0
        continue;
622
0
623
0
      if (entries[0] != GRP_COMDAT)
624
0
        fatal(toString(this) + ": unsupported SHT_GROUP format");
625
0
626
0
      bool isNew =
627
0
          ignoreComdats ||
628
0
          symtab->comdatGroups.try_emplace(CachedHashStringRef(signature), this)
629
0
              .second;
630
0
      if (isNew) {
631
0
        if (config->relocatable)
632
0
          this->sections[i] = createInputSection(sec);
633
0
        continue;
634
0
      }
635
0
636
0
      // Otherwise, discard group members.
637
0
      for (uint32_t secIndex : entries.slice(1)) {
638
0
        if (secIndex >= size)
639
0
          fatal(toString(this) +
640
0
                ": invalid section index in group: " + Twine(secIndex));
641
0
        this->sections[secIndex] = &InputSection::discarded;
642
0
      }
643
0
      break;
644
0
    }
645
0
    case SHT_SYMTAB_SHNDX:
646
0
      shndxTable = CHECK(obj.getSHNDXTable(sec, objSections), this);
647
0
      break;
648
429
    case SHT_SYMTAB:
649
429
    case SHT_STRTAB:
650
429
    case SHT_NULL:
651
429
      break;
652
520
    default:
653
520
      this->sections[i] = createInputSection(sec);
654
949
    }
655
949
  }
656
138
657
1.08k
  
for (size_t i = 0, e = objSections.size(); 138
i < e;
++i949
) {
658
949
    if (this->sections[i] == &InputSection::discarded)
659
8
      continue;
660
941
    const Elf_Shdr &sec = objSections[i];
661
941
    if (!(sec.sh_flags & SHF_LINK_ORDER))
662
941
      continue;
663
0
664
0
    // .ARM.exidx sections have a reverse dependency on the InputSection they
665
0
    // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
666
0
    InputSectionBase *linkSec = nullptr;
667
0
    if (sec.sh_link < this->sections.size())
668
0
      linkSec = this->sections[sec.sh_link];
669
0
    if (!linkSec)
670
0
      fatal(toString(this) + ": invalid sh_link index: " + Twine(sec.sh_link));
671
0
672
0
    InputSection *isec = cast<InputSection>(this->sections[i]);
673
0
    linkSec->dependentSections.push_back(isec);
674
0
    if (!isa<InputSection>(linkSec))
675
0
      error("a section " + isec->name +
676
0
            " with SHF_LINK_ORDER should not refer a non-regular section: " +
677
0
            toString(linkSec));
678
0
  }
679
138
}
680
681
// For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD
682
// flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how
683
// the input objects have been compiled.
684
static void updateARMVFPArgs(const ARMAttributeParser &attributes,
685
103
                             const InputFile *f) {
686
103
  if (!attributes.hasAttribute(ARMBuildAttrs::ABI_VFP_args))
687
75
    // If an ABI tag isn't present then it is implicitly given the value of 0
688
75
    // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files,
689
75
    // including some in glibc that don't use FP args (and should have value 3)
690
75
    // don't have the attribute so we do not consider an implicit value of 0
691
75
    // as a clash.
692
75
    return;
693
28
694
28
  unsigned vfpArgs = attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args);
695
28
  ARMVFPArgKind arg;
696
28
  switch (vfpArgs) {
697
28
  case ARMBuildAttrs::BaseAAPCS:
698
6
    arg = ARMVFPArgKind::Base;
699
6
    break;
700
28
  case ARMBuildAttrs::HardFPAAPCS:
701
6
    arg = ARMVFPArgKind::VFP;
702
6
    break;
703
28
  case ARMBuildAttrs::ToolChainFPPCS:
704
6
    // Tool chain specific convention that conforms to neither AAPCS variant.
705
6
    arg = ARMVFPArgKind::ToolChain;
706
6
    break;
707
28
  case ARMBuildAttrs::CompatibleFPAAPCS:
708
9
    // Object compatible with all conventions.
709
9
    return;
710
28
  default:
711
1
    error(toString(f) + ": unknown Tag_ABI_VFP_args value: " + Twine(vfpArgs));
712
1
    return;
713
18
  }
714
18
  // Follow ld.bfd and error if there is a mix of calling conventions.
715
18
  if (config->armVFPArgs != arg && config->armVFPArgs != ARMVFPArgKind::Default)
716
6
    error(toString(f) + ": incompatible Tag_ABI_VFP_args");
717
12
  else
718
12
    config->armVFPArgs = arg;
719
18
}
720
721
// The ARM support in lld makes some use of instructions that are not available
722
// on all ARM architectures. Namely:
723
// - Use of BLX instruction for interworking between ARM and Thumb state.
724
// - Use of the extended Thumb branch encoding in relocation.
725
// - Use of the MOVT/MOVW instructions in Thumb Thunks.
726
// The ARM Attributes section contains information about the architecture chosen
727
// at compile time. We follow the convention that if at least one input object
728
// is compiled with an architecture that supports these features then lld is
729
// permitted to use them.
730
103
static void updateSupportedARMFeatures(const ARMAttributeParser &attributes) {
731
103
  if (!attributes.hasAttribute(ARMBuildAttrs::CPU_arch))
732
2
    return;
733
101
  auto arch = attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
734
101
  switch (arch) {
735
101
  case ARMBuildAttrs::Pre_v4:
736
1
  case ARMBuildAttrs::v4:
737
1
  case ARMBuildAttrs::v4T:
738
1
    // Architectures prior to v5 do not support BLX instruction
739
1
    break;
740
5
  case ARMBuildAttrs::v5T:
741
5
  case ARMBuildAttrs::v5TE:
742
5
  case ARMBuildAttrs::v5TEJ:
743
5
  case ARMBuildAttrs::v6:
744
5
  case ARMBuildAttrs::v6KZ:
745
5
  case ARMBuildAttrs::v6K:
746
5
    config->armHasBlx = true;
747
5
    // Architectures used in pre-Cortex processors do not support
748
5
    // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
749
5
    // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
750
5
    break;
751
95
  default:
752
95
    // All other Architectures have BLX and extended branch encoding
753
95
    config->armHasBlx = true;
754
95
    config->armJ1J2BranchEncoding = true;
755
95
    if (arch != ARMBuildAttrs::v6_M && arch != ARMBuildAttrs::v6S_M)
756
93
      // All Architectures used in Cortex processors with the exception
757
93
      // of v6-M and v6S-M have the MOVT and MOVW instructions.
758
93
      config->armHasMovtMovw = true;
759
95
    break;
760
101
  }
761
101
}
762
763
// If a source file is compiled with x86 hardware-assisted call flow control
764
// enabled, the generated object file contains feature flags indicating that
765
// fact. This function reads the feature flags and returns it.
766
//
767
// Essentially we want to read a single 32-bit value in this function, but this
768
// function is rather complicated because the value is buried deep inside a
769
// .note.gnu.property section.
770
//
771
// The section consists of one or more NOTE records. Each NOTE record consists
772
// of zero or more type-length-value fields. We want to find a field of a
773
// certain type. It seems a bit too much to just store a 32-bit value, perhaps
774
// the ABI is unnecessarily complicated.
775
template <class ELFT>
776
36
static uint32_t readAndFeatures(ObjFile<ELFT> *obj, ArrayRef<uint8_t> data) {
777
36
  using Elf_Nhdr = typename ELFT::Nhdr;
778
36
  using Elf_Note = typename ELFT::Note;
779
36
780
36
  uint32_t featuresSet = 0;
781
74
  while (!data.empty()) {
782
38
    // Read one NOTE record.
783
38
    if (data.size() < sizeof(Elf_Nhdr))
784
0
      fatal(toString(obj) + ": .note.gnu.property: section too short");
785
38
786
38
    auto *nhdr = reinterpret_cast<const Elf_Nhdr *>(data.data());
787
38
    if (data.size() < nhdr->getSize())
788
0
      fatal(toString(obj) + ": .note.gnu.property: section too short");
789
38
790
38
    Elf_Note note(*nhdr);
791
38
    if (nhdr->n_type != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU") {
792
0
      data = data.slice(nhdr->getSize());
793
0
      continue;
794
0
    }
795
38
796
38
    uint32_t featureAndType = config->emachine == EM_AARCH64
797
38
                                  ? 
GNU_PROPERTY_AARCH64_FEATURE_1_AND20
798
38
                                  : 
GNU_PROPERTY_X86_FEATURE_1_AND18
;
799
38
800
38
    // Read a body of a NOTE record, which consists of type-length-value fields.
801
38
    ArrayRef<uint8_t> desc = note.getDesc();
802
78
    while (!desc.empty()) {
803
40
      if (desc.size() < 8)
804
0
        fatal(toString(obj) + ": .note.gnu.property: section too short");
805
40
806
40
      uint32_t type = read32le(desc.data());
807
40
      uint32_t size = read32le(desc.data() + 4);
808
40
809
40
      if (type == featureAndType) {
810
38
        // We found a FEATURE_1_AND field. There may be more than one of these
811
38
        // in a .note.gnu.propery section, for a relocatable object we
812
38
        // accumulate the bits set.
813
38
        featuresSet |= read32le(desc.data() + 8);
814
38
      }
815
40
816
40
      // On 64-bit, a payload may be followed by a 4-byte padding to make its
817
40
      // size a multiple of 8.
818
40
      if (ELFT::Is64Bits)
819
31
        size = alignTo(size, 8);
820
40
821
40
      desc = desc.slice(size + 8); // +8 for Type and Size
822
40
    }
823
38
824
38
    // Go to next NOTE record to look for more FEATURE_1_AND descriptions.
825
38
    data = data.slice(nhdr->getSize());
826
38
  }
827
36
828
36
  return featuresSet;
829
36
}
InputFiles.cpp:unsigned int readAndFeatures<llvm::object::ELFType<(llvm::support::endianness)1, false> >(lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >*, llvm::ArrayRef<unsigned char>)
Line
Count
Source
776
8
static uint32_t readAndFeatures(ObjFile<ELFT> *obj, ArrayRef<uint8_t> data) {
777
8
  using Elf_Nhdr = typename ELFT::Nhdr;
778
8
  using Elf_Note = typename ELFT::Note;
779
8
780
8
  uint32_t featuresSet = 0;
781
16
  while (!data.empty()) {
782
8
    // Read one NOTE record.
783
8
    if (data.size() < sizeof(Elf_Nhdr))
784
0
      fatal(toString(obj) + ": .note.gnu.property: section too short");
785
8
786
8
    auto *nhdr = reinterpret_cast<const Elf_Nhdr *>(data.data());
787
8
    if (data.size() < nhdr->getSize())
788
0
      fatal(toString(obj) + ": .note.gnu.property: section too short");
789
8
790
8
    Elf_Note note(*nhdr);
791
8
    if (nhdr->n_type != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU") {
792
0
      data = data.slice(nhdr->getSize());
793
0
      continue;
794
0
    }
795
8
796
8
    uint32_t featureAndType = config->emachine == EM_AARCH64
797
8
                                  ? 
GNU_PROPERTY_AARCH64_FEATURE_1_AND0
798
8
                                  : GNU_PROPERTY_X86_FEATURE_1_AND;
799
8
800
8
    // Read a body of a NOTE record, which consists of type-length-value fields.
801
8
    ArrayRef<uint8_t> desc = note.getDesc();
802
17
    while (!desc.empty()) {
803
9
      if (desc.size() < 8)
804
0
        fatal(toString(obj) + ": .note.gnu.property: section too short");
805
9
806
9
      uint32_t type = read32le(desc.data());
807
9
      uint32_t size = read32le(desc.data() + 4);
808
9
809
9
      if (type == featureAndType) {
810
8
        // We found a FEATURE_1_AND field. There may be more than one of these
811
8
        // in a .note.gnu.propery section, for a relocatable object we
812
8
        // accumulate the bits set.
813
8
        featuresSet |= read32le(desc.data() + 8);
814
8
      }
815
9
816
9
      // On 64-bit, a payload may be followed by a 4-byte padding to make its
817
9
      // size a multiple of 8.
818
9
      if (ELFT::Is64Bits)
819
0
        size = alignTo(size, 8);
820
9
821
9
      desc = desc.slice(size + 8); // +8 for Type and Size
822
9
    }
823
8
824
8
    // Go to next NOTE record to look for more FEATURE_1_AND descriptions.
825
8
    data = data.slice(nhdr->getSize());
826
8
  }
827
8
828
8
  return featuresSet;
829
8
}
Unexecuted instantiation: InputFiles.cpp:unsigned int readAndFeatures<llvm::object::ELFType<(llvm::support::endianness)0, false> >(lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >*, llvm::ArrayRef<unsigned char>)
InputFiles.cpp:unsigned int readAndFeatures<llvm::object::ELFType<(llvm::support::endianness)1, true> >(lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >*, llvm::ArrayRef<unsigned char>)
Line
Count
Source
776
28
static uint32_t readAndFeatures(ObjFile<ELFT> *obj, ArrayRef<uint8_t> data) {
777
28
  using Elf_Nhdr = typename ELFT::Nhdr;
778
28
  using Elf_Note = typename ELFT::Note;
779
28
780
28
  uint32_t featuresSet = 0;
781
58
  while (!data.empty()) {
782
30
    // Read one NOTE record.
783
30
    if (data.size() < sizeof(Elf_Nhdr))
784
0
      fatal(toString(obj) + ": .note.gnu.property: section too short");
785
30
786
30
    auto *nhdr = reinterpret_cast<const Elf_Nhdr *>(data.data());
787
30
    if (data.size() < nhdr->getSize())
788
0
      fatal(toString(obj) + ": .note.gnu.property: section too short");
789
30
790
30
    Elf_Note note(*nhdr);
791
30
    if (nhdr->n_type != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU") {
792
0
      data = data.slice(nhdr->getSize());
793
0
      continue;
794
0
    }
795
30
796
30
    uint32_t featureAndType = config->emachine == EM_AARCH64
797
30
                                  ? 
GNU_PROPERTY_AARCH64_FEATURE_1_AND20
798
30
                                  : 
GNU_PROPERTY_X86_FEATURE_1_AND10
;
799
30
800
30
    // Read a body of a NOTE record, which consists of type-length-value fields.
801
30
    ArrayRef<uint8_t> desc = note.getDesc();
802
61
    while (!desc.empty()) {
803
31
      if (desc.size() < 8)
804
0
        fatal(toString(obj) + ": .note.gnu.property: section too short");
805
31
806
31
      uint32_t type = read32le(desc.data());
807
31
      uint32_t size = read32le(desc.data() + 4);
808
31
809
31
      if (type == featureAndType) {
810
30
        // We found a FEATURE_1_AND field. There may be more than one of these
811
30
        // in a .note.gnu.propery section, for a relocatable object we
812
30
        // accumulate the bits set.
813
30
        featuresSet |= read32le(desc.data() + 8);
814
30
      }
815
31
816
31
      // On 64-bit, a payload may be followed by a 4-byte padding to make its
817
31
      // size a multiple of 8.
818
31
      if (ELFT::Is64Bits)
819
31
        size = alignTo(size, 8);
820
31
821
31
      desc = desc.slice(size + 8); // +8 for Type and Size
822
31
    }
823
30
824
30
    // Go to next NOTE record to look for more FEATURE_1_AND descriptions.
825
30
    data = data.slice(nhdr->getSize());
826
30
  }
827
28
828
28
  return featuresSet;
829
28
}
Unexecuted instantiation: InputFiles.cpp:unsigned int readAndFeatures<llvm::object::ELFType<(llvm::support::endianness)0, true> >(lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >*, llvm::ArrayRef<unsigned char>)
830
831
template <class ELFT>
832
2.16k
InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &sec) {
833
2.16k
  uint32_t idx = sec.sh_info;
834
2.16k
  if (idx >= this->sections.size())
835
0
    fatal(toString(this) + ": invalid relocated section index: " + Twine(idx));
836
2.16k
  InputSectionBase *target = this->sections[idx];
837
2.16k
838
2.16k
  // Strictly speaking, a relocation section must be included in the
839
2.16k
  // group of the section it relocates. However, LLVM 3.3 and earlier
840
2.16k
  // would fail to do so, so we gracefully handle that case.
841
2.16k
  if (target == &InputSection::discarded)
842
5
    return nullptr;
843
2.15k
844
2.15k
  if (!target)
845
0
    fatal(toString(this) + ": unsupported relocation reference");
846
2.15k
  return target;
847
2.15k
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >::getRelocTarget(llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false> > const&)
Line
Count
Source
832
424
InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &sec) {
833
424
  uint32_t idx = sec.sh_info;
834
424
  if (idx >= this->sections.size())
835
0
    fatal(toString(this) + ": invalid relocated section index: " + Twine(idx));
836
424
  InputSectionBase *target = this->sections[idx];
837
424
838
424
  // Strictly speaking, a relocation section must be included in the
839
424
  // group of the section it relocates. However, LLVM 3.3 and earlier
840
424
  // would fail to do so, so we gracefully handle that case.
841
424
  if (target == &InputSection::discarded)
842
0
    return nullptr;
843
424
844
424
  if (!target)
845
0
    fatal(toString(this) + ": unsupported relocation reference");
846
424
  return target;
847
424
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >::getRelocTarget(llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false> > const&)
Line
Count
Source
832
130
InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &sec) {
833
130
  uint32_t idx = sec.sh_info;
834
130
  if (idx >= this->sections.size())
835
0
    fatal(toString(this) + ": invalid relocated section index: " + Twine(idx));
836
130
  InputSectionBase *target = this->sections[idx];
837
130
838
130
  // Strictly speaking, a relocation section must be included in the
839
130
  // group of the section it relocates. However, LLVM 3.3 and earlier
840
130
  // would fail to do so, so we gracefully handle that case.
841
130
  if (target == &InputSection::discarded)
842
0
    return nullptr;
843
130
844
130
  if (!target)
845
0
    fatal(toString(this) + ": unsupported relocation reference");
846
130
  return target;
847
130
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >::getRelocTarget(llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true> > const&)
Line
Count
Source
832
1.49k
InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &sec) {
833
1.49k
  uint32_t idx = sec.sh_info;
834
1.49k
  if (idx >= this->sections.size())
835
0
    fatal(toString(this) + ": invalid relocated section index: " + Twine(idx));
836
1.49k
  InputSectionBase *target = this->sections[idx];
837
1.49k
838
1.49k
  // Strictly speaking, a relocation section must be included in the
839
1.49k
  // group of the section it relocates. However, LLVM 3.3 and earlier
840
1.49k
  // would fail to do so, so we gracefully handle that case.
841
1.49k
  if (target == &InputSection::discarded)
842
5
    return nullptr;
843
1.49k
844
1.49k
  if (!target)
845
0
    fatal(toString(this) + ": unsupported relocation reference");
846
1.49k
  return target;
847
1.49k
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >::getRelocTarget(llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true> > const&)
Line
Count
Source
832
108
InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &sec) {
833
108
  uint32_t idx = sec.sh_info;
834
108
  if (idx >= this->sections.size())
835
0
    fatal(toString(this) + ": invalid relocated section index: " + Twine(idx));
836
108
  InputSectionBase *target = this->sections[idx];
837
108
838
108
  // Strictly speaking, a relocation section must be included in the
839
108
  // group of the section it relocates. However, LLVM 3.3 and earlier
840
108
  // would fail to do so, so we gracefully handle that case.
841
108
  if (target == &InputSection::discarded)
842
0
    return nullptr;
843
108
844
108
  if (!target)
845
0
    fatal(toString(this) + ": unsupported relocation reference");
846
108
  return target;
847
108
}
848
849
// Create a regular InputSection class that has the same contents
850
// as a given section.
851
3
static InputSection *toRegularSection(MergeInputSection *sec) {
852
3
  return make<InputSection>(sec->file, sec->flags, sec->type, sec->alignment,
853
3
                            sec->data(), sec->name);
854
3
}
855
856
template <class ELFT>
857
339k
InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &sec) {
858
339k
  StringRef name = getSectionName(sec);
859
339k
860
339k
  switch (sec.sh_type) {
861
339k
  case SHT_ARM_ATTRIBUTES: {
862
105
    if (config->emachine != EM_ARM)
863
2
      break;
864
103
    ARMAttributeParser attributes;
865
103
    ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(&sec));
866
103
    attributes.Parse(contents, /*isLittle*/ config->ekind == ELF32LEKind);
867
103
    updateSupportedARMFeatures(attributes);
868
103
    updateARMVFPArgs(attributes, this);
869
103
870
103
    // FIXME: Retain the first attribute section we see. The eglibc ARM
871
103
    // dynamic loaders require the presence of an attribute section for dlopen
872
103
    // to work. In a full implementation we would merge all attribute sections.
873
103
    if (in.armAttributes == nullptr) {
874
75
      in.armAttributes = make<InputSection>(*this, sec, name);
875
75
      return in.armAttributes;
876
75
    }
877
28
    return &InputSection::discarded;
878
28
  }
879
28
  case SHT_LLVM_DEPENDENT_LIBRARIES: {
880
11
    if (config->relocatable)
881
2
      break;
882
9
    ArrayRef<char> data =
883
9
        CHECK(this->getObj().template getSectionContentsAsArray<char>(&sec), this);
884
9
    if (!data.empty() && data.back() != '\0') {
885
1
      error(toString(this) +
886
1
            ": corrupted dependent libraries section (unterminated string): " +
887
1
            name);
888
1
      return &InputSection::discarded;
889
1
    }
890
23
    
for (const char *d = data.begin(), *e = data.end(); 8
d < e;) {
891
15
      StringRef s(d);
892
15
      addDependentLibrary(s, this);
893
15
      d += s.size() + 1;
894
15
    }
895
8
    return &InputSection::discarded;
896
8
  }
897
2.16k
  case SHT_RELA:
898
2.16k
  case SHT_REL: {
899
2.16k
    // Find a relocation target section and associate this section with that.
900
2.16k
    // Target may have been discarded if it is in a different section group
901
2.16k
    // and the group is discarded, even though it's a violation of the
902
2.16k
    // spec. We handle that situation gracefully by discarding dangling
903
2.16k
    // relocation sections.
904
2.16k
    InputSectionBase *target = getRelocTarget(sec);
905
2.16k
    if (!target)
906
5
      return nullptr;
907
2.15k
908
2.15k
    // This section contains relocation information.
909
2.15k
    // If -r is given, we do not interpret or apply relocation
910
2.15k
    // but just copy relocation sections to output.
911
2.15k
    if (config->relocatable) {
912
87
      InputSection *relocSec = make<InputSection>(*this, sec, name);
913
87
      // We want to add a dependency to target, similar like we do for
914
87
      // -emit-relocs below. This is useful for the case when linker script
915
87
      // contains the "/DISCARD/". It is perhaps uncommon to use a script with
916
87
      // -r, but we faced it in the Linux kernel and have to handle such case
917
87
      // and not to crash.
918
87
      target->dependentSections.push_back(relocSec);
919
87
      return relocSec;
920
87
    }
921
2.06k
922
2.06k
    if (target->firstRelocation)
923
0
      fatal(toString(this) +
924
0
            ": multiple relocation sections to one section are not supported");
925
2.06k
926
2.06k
    // ELF spec allows mergeable sections with relocations, but they are
927
2.06k
    // rare, and it is in practice hard to merge such sections by contents,
928
2.06k
    // because applying relocations at end of linking changes section
929
2.06k
    // contents. So, we simply handle such sections as non-mergeable ones.
930
2.06k
    // Degrading like this is acceptable because section merging is optional.
931
2.06k
    if (auto *ms = dyn_cast<MergeInputSection>(target)) {
932
3
      target = toRegularSection(ms);
933
3
      this->sections[sec.sh_info] = target;
934
3
    }
935
2.06k
936
2.06k
    if (sec.sh_type == SHT_RELA) {
937
1.62k
      ArrayRef<Elf_Rela> rels = CHECK(getObj().relas(&sec), this);
938
1.62k
      target->firstRelocation = rels.begin();
939
1.62k
      target->numRelocations = rels.size();
940
1.62k
      target->areRelocsRela = true;
941
1.62k
    } else {
942
447
      ArrayRef<Elf_Rel> rels = CHECK(getObj().rels(&sec), this);
943
447
      target->firstRelocation = rels.begin();
944
447
      target->numRelocations = rels.size();
945
447
      target->areRelocsRela = false;
946
447
    }
947
2.06k
    assert(isUInt<31>(target->numRelocations));
948
2.06k
949
2.06k
    // Relocation sections processed by the linker are usually removed
950
2.06k
    // from the output, so returning `nullptr` for the normal case.
951
2.06k
    // However, if -emit-relocs is given, we need to leave them in the output.
952
2.06k
    // (Some post link analysis tools need this information.)
953
2.06k
    if (config->emitRelocs) {
954
39
      InputSection *relocSec = make<InputSection>(*this, sec, name);
955
39
      // We will not emit relocation section if target was discarded.
956
39
      target->dependentSections.push_back(relocSec);
957
39
      return relocSec;
958
39
    }
959
2.02k
    return nullptr;
960
2.02k
  }
961
337k
  }
962
337k
963
337k
  // The GNU linker uses .note.GNU-stack section as a marker indicating
964
337k
  // that the code in the object file does not expect that the stack is
965
337k
  // executable (in terms of NX bit). If all input files have the marker,
966
337k
  // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
967
337k
  // make the stack non-executable. Most object files have this section as
968
337k
  // of 2017.
969
337k
  //
970
337k
  // But making the stack non-executable is a norm today for security
971
337k
  // reasons. Failure to do so may result in a serious security issue.
972
337k
  // Therefore, we make LLD always add PT_GNU_STACK unless it is
973
337k
  // explicitly told to do otherwise (by -z execstack). Because the stack
974
337k
  // executable-ness is controlled solely by command line options,
975
337k
  // .note.GNU-stack sections are simply ignored.
976
337k
  if (name == ".note.GNU-stack")
977
248
    return &InputSection::discarded;
978
337k
979
337k
  // Object files that use processor features such as Intel Control-Flow
980
337k
  // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a
981
337k
  // .note.gnu.property section containing a bitfield of feature bits like the
982
337k
  // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag.
983
337k
  //
984
337k
  // Since we merge bitmaps from multiple object files to create a new
985
337k
  // .note.gnu.property containing a single AND'ed bitmap, we discard an input
986
337k
  // file's .note.gnu.property section.
987
337k
  if (name == ".note.gnu.property") {
988
36
    ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(&sec));
989
36
    this->andFeatures = readAndFeatures(this, contents);
990
36
    return &InputSection::discarded;
991
36
  }
992
337k
993
337k
  // Split stacks is a feature to support a discontiguous stack,
994
337k
  // commonly used in the programming language Go. For the details,
995
337k
  // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled
996
337k
  // for split stack will include a .note.GNU-split-stack section.
997
337k
  if (name == ".note.GNU-split-stack") {
998
27
    if (config->relocatable) {
999
2
      error("cannot mix split-stack and non-split-stack in a relocatable link");
1000
2
      return &InputSection::discarded;
1001
2
    }
1002
25
    this->splitStack = true;
1003
25
    return &InputSection::discarded;
1004
25
  }
1005
337k
1006
337k
  // An object file cmpiled for split stack, but where some of the
1007
337k
  // functions were compiled with the no_split_stack_attribute will
1008
337k
  // include a .note.GNU-no-split-stack section.
1009
337k
  if (name == ".note.GNU-no-split-stack") {
1010
1
    this->someNoSplitStack = true;
1011
1
    return &InputSection::discarded;
1012
1
  }
1013
337k
1014
337k
  // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
1015
337k
  // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
1016
337k
  // sections. Drop those sections to avoid duplicate symbol errors.
1017
337k
  // FIXME: This is glibc PR20543, we should remove this hack once that has been
1018
337k
  // fixed for a while.
1019
337k
  if (name == ".gnu.linkonce.t.__x86.get_pc_thunk.bx" ||
1020
337k
      
name == ".gnu.linkonce.t.__i686.get_pc_thunk.bx"337k
)
1021
5
    return &InputSection::discarded;
1022
337k
1023
337k
  // If we are creating a new .build-id section, strip existing .build-id
1024
337k
  // sections so that the output won't have more than one .build-id.
1025
337k
  // This is not usually a problem because input object files normally don't
1026
337k
  // have .build-id sections, but you can create such files by
1027
337k
  // "ld.{bfd,gold,lld} -r --build-id", and we want to guard against it.
1028
337k
  if (name == ".note.gnu.build-id" && 
config->buildId != BuildIdKind::None1
)
1029
1
    return &InputSection::discarded;
1030
337k
1031
337k
  // The linker merges EH (exception handling) frames and creates a
1032
337k
  // .eh_frame_hdr section for runtime. So we handle them with a special
1033
337k
  // class. For relocatable outputs, they are just passed through.
1034
337k
  if (name == ".eh_frame" && 
!config->relocatable120
)
1035
116
    return make<EhInputSection>(*this, sec, name);
1036
337k
1037
337k
  if (shouldMerge(sec))
1038
130
    return make<MergeInputSection>(*this, sec, name);
1039
337k
  return make<InputSection>(*this, sec, name);
1040
337k
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >::createInputSection(llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false> > const&)
Line
Count
Source
857
1.85k
InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &sec) {
858
1.85k
  StringRef name = getSectionName(sec);
859
1.85k
860
1.85k
  switch (sec.sh_type) {
861
1.85k
  case SHT_ARM_ATTRIBUTES: {
862
105
    if (config->emachine != EM_ARM)
863
2
      break;
864
103
    ARMAttributeParser attributes;
865
103
    ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(&sec));
866
103
    attributes.Parse(contents, /*isLittle*/ config->ekind == ELF32LEKind);
867
103
    updateSupportedARMFeatures(attributes);
868
103
    updateARMVFPArgs(attributes, this);
869
103
870
103
    // FIXME: Retain the first attribute section we see. The eglibc ARM
871
103
    // dynamic loaders require the presence of an attribute section for dlopen
872
103
    // to work. In a full implementation we would merge all attribute sections.
873
103
    if (in.armAttributes == nullptr) {
874
75
      in.armAttributes = make<InputSection>(*this, sec, name);
875
75
      return in.armAttributes;
876
75
    }
877
28
    return &InputSection::discarded;
878
28
  }
879
28
  case SHT_LLVM_DEPENDENT_LIBRARIES: {
880
0
    if (config->relocatable)
881
0
      break;
882
0
    ArrayRef<char> data =
883
0
        CHECK(this->getObj().template getSectionContentsAsArray<char>(&sec), this);
884
0
    if (!data.empty() && data.back() != '\0') {
885
0
      error(toString(this) +
886
0
            ": corrupted dependent libraries section (unterminated string): " +
887
0
            name);
888
0
      return &InputSection::discarded;
889
0
    }
890
0
    for (const char *d = data.begin(), *e = data.end(); d < e;) {
891
0
      StringRef s(d);
892
0
      addDependentLibrary(s, this);
893
0
      d += s.size() + 1;
894
0
    }
895
0
    return &InputSection::discarded;
896
0
  }
897
424
  case SHT_RELA:
898
424
  case SHT_REL: {
899
424
    // Find a relocation target section and associate this section with that.
900
424
    // Target may have been discarded if it is in a different section group
901
424
    // and the group is discarded, even though it's a violation of the
902
424
    // spec. We handle that situation gracefully by discarding dangling
903
424
    // relocation sections.
904
424
    InputSectionBase *target = getRelocTarget(sec);
905
424
    if (!target)
906
0
      return nullptr;
907
424
908
424
    // This section contains relocation information.
909
424
    // If -r is given, we do not interpret or apply relocation
910
424
    // but just copy relocation sections to output.
911
424
    if (config->relocatable) {
912
19
      InputSection *relocSec = make<InputSection>(*this, sec, name);
913
19
      // We want to add a dependency to target, similar like we do for
914
19
      // -emit-relocs below. This is useful for the case when linker script
915
19
      // contains the "/DISCARD/". It is perhaps uncommon to use a script with
916
19
      // -r, but we faced it in the Linux kernel and have to handle such case
917
19
      // and not to crash.
918
19
      target->dependentSections.push_back(relocSec);
919
19
      return relocSec;
920
19
    }
921
405
922
405
    if (target->firstRelocation)
923
0
      fatal(toString(this) +
924
0
            ": multiple relocation sections to one section are not supported");
925
405
926
405
    // ELF spec allows mergeable sections with relocations, but they are
927
405
    // rare, and it is in practice hard to merge such sections by contents,
928
405
    // because applying relocations at end of linking changes section
929
405
    // contents. So, we simply handle such sections as non-mergeable ones.
930
405
    // Degrading like this is acceptable because section merging is optional.
931
405
    if (auto *ms = dyn_cast<MergeInputSection>(target)) {
932
0
      target = toRegularSection(ms);
933
0
      this->sections[sec.sh_info] = target;
934
0
    }
935
405
936
405
    if (sec.sh_type == SHT_RELA) {
937
42
      ArrayRef<Elf_Rela> rels = CHECK(getObj().relas(&sec), this);
938
42
      target->firstRelocation = rels.begin();
939
42
      target->numRelocations = rels.size();
940
42
      target->areRelocsRela = true;
941
363
    } else {
942
363
      ArrayRef<Elf_Rel> rels = CHECK(getObj().rels(&sec), this);
943
363
      target->firstRelocation = rels.begin();
944
363
      target->numRelocations = rels.size();
945
363
      target->areRelocsRela = false;
946
363
    }
947
405
    assert(isUInt<31>(target->numRelocations));
948
405
949
405
    // Relocation sections processed by the linker are usually removed
950
405
    // from the output, so returning `nullptr` for the normal case.
951
405
    // However, if -emit-relocs is given, we need to leave them in the output.
952
405
    // (Some post link analysis tools need this information.)
953
405
    if (config->emitRelocs) {
954
6
      InputSection *relocSec = make<InputSection>(*this, sec, name);
955
6
      // We will not emit relocation section if target was discarded.
956
6
      target->dependentSections.push_back(relocSec);
957
6
      return relocSec;
958
6
    }
959
399
    return nullptr;
960
399
  }
961
1.32k
  }
962
1.32k
963
1.32k
  // The GNU linker uses .note.GNU-stack section as a marker indicating
964
1.32k
  // that the code in the object file does not expect that the stack is
965
1.32k
  // executable (in terms of NX bit). If all input files have the marker,
966
1.32k
  // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
967
1.32k
  // make the stack non-executable. Most object files have this section as
968
1.32k
  // of 2017.
969
1.32k
  //
970
1.32k
  // But making the stack non-executable is a norm today for security
971
1.32k
  // reasons. Failure to do so may result in a serious security issue.
972
1.32k
  // Therefore, we make LLD always add PT_GNU_STACK unless it is
973
1.32k
  // explicitly told to do otherwise (by -z execstack). Because the stack
974
1.32k
  // executable-ness is controlled solely by command line options,
975
1.32k
  // .note.GNU-stack sections are simply ignored.
976
1.32k
  if (name == ".note.GNU-stack")
977
4
    return &InputSection::discarded;
978
1.32k
979
1.32k
  // Object files that use processor features such as Intel Control-Flow
980
1.32k
  // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a
981
1.32k
  // .note.gnu.property section containing a bitfield of feature bits like the
982
1.32k
  // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag.
983
1.32k
  //
984
1.32k
  // Since we merge bitmaps from multiple object files to create a new
985
1.32k
  // .note.gnu.property containing a single AND'ed bitmap, we discard an input
986
1.32k
  // file's .note.gnu.property section.
987
1.32k
  if (name == ".note.gnu.property") {
988
8
    ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(&sec));
989
8
    this->andFeatures = readAndFeatures(this, contents);
990
8
    return &InputSection::discarded;
991
8
  }
992
1.31k
993
1.31k
  // Split stacks is a feature to support a discontiguous stack,
994
1.31k
  // commonly used in the programming language Go. For the details,
995
1.31k
  // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled
996
1.31k
  // for split stack will include a .note.GNU-split-stack section.
997
1.31k
  if (name == ".note.GNU-split-stack") {
998
0
    if (config->relocatable) {
999
0
      error("cannot mix split-stack and non-split-stack in a relocatable link");
1000
0
      return &InputSection::discarded;
1001
0
    }
1002
0
    this->splitStack = true;
1003
0
    return &InputSection::discarded;
1004
0
  }
1005
1.31k
1006
1.31k
  // An object file cmpiled for split stack, but where some of the
1007
1.31k
  // functions were compiled with the no_split_stack_attribute will
1008
1.31k
  // include a .note.GNU-no-split-stack section.
1009
1.31k
  if (name == ".note.GNU-no-split-stack") {
1010
0
    this->someNoSplitStack = true;
1011
0
    return &InputSection::discarded;
1012
0
  }
1013
1.31k
1014
1.31k
  // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
1015
1.31k
  // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
1016
1.31k
  // sections. Drop those sections to avoid duplicate symbol errors.
1017
1.31k
  // FIXME: This is glibc PR20543, we should remove this hack once that has been
1018
1.31k
  // fixed for a while.
1019
1.31k
  if (name == ".gnu.linkonce.t.__x86.get_pc_thunk.bx" ||
1020
1.31k
      name == ".gnu.linkonce.t.__i686.get_pc_thunk.bx")
1021
1
    return &InputSection::discarded;
1022
1.31k
1023
1.31k
  // If we are creating a new .build-id section, strip existing .build-id
1024
1.31k
  // sections so that the output won't have more than one .build-id.
1025
1.31k
  // This is not usually a problem because input object files normally don't
1026
1.31k
  // have .build-id sections, but you can create such files by
1027
1.31k
  // "ld.{bfd,gold,lld} -r --build-id", and we want to guard against it.
1028
1.31k
  if (name == ".note.gnu.build-id" && 
config->buildId != BuildIdKind::None0
)
1029
0
    return &InputSection::discarded;
1030
1.31k
1031
1.31k
  // The linker merges EH (exception handling) frames and creates a
1032
1.31k
  // .eh_frame_hdr section for runtime. So we handle them with a special
1033
1.31k
  // class. For relocatable outputs, they are just passed through.
1034
1.31k
  if (name == ".eh_frame" && 
!config->relocatable4
)
1035
4
    return make<EhInputSection>(*this, sec, name);
1036
1.31k
1037
1.31k
  if (shouldMerge(sec))
1038
5
    return make<MergeInputSection>(*this, sec, name);
1039
1.30k
  return make<InputSection>(*this, sec, name);
1040
1.30k
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >::createInputSection(llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false> > const&)
Line
Count
Source
857
1.09k
InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &sec) {
858
1.09k
  StringRef name = getSectionName(sec);
859
1.09k
860
1.09k
  switch (sec.sh_type) {
861
1.09k
  case SHT_ARM_ATTRIBUTES: {
862
0
    if (config->emachine != EM_ARM)
863
0
      break;
864
0
    ARMAttributeParser attributes;
865
0
    ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(&sec));
866
0
    attributes.Parse(contents, /*isLittle*/ config->ekind == ELF32LEKind);
867
0
    updateSupportedARMFeatures(attributes);
868
0
    updateARMVFPArgs(attributes, this);
869
0
870
0
    // FIXME: Retain the first attribute section we see. The eglibc ARM
871
0
    // dynamic loaders require the presence of an attribute section for dlopen
872
0
    // to work. In a full implementation we would merge all attribute sections.
873
0
    if (in.armAttributes == nullptr) {
874
0
      in.armAttributes = make<InputSection>(*this, sec, name);
875
0
      return in.armAttributes;
876
0
    }
877
0
    return &InputSection::discarded;
878
0
  }
879
0
  case SHT_LLVM_DEPENDENT_LIBRARIES: {
880
0
    if (config->relocatable)
881
0
      break;
882
0
    ArrayRef<char> data =
883
0
        CHECK(this->getObj().template getSectionContentsAsArray<char>(&sec), this);
884
0
    if (!data.empty() && data.back() != '\0') {
885
0
      error(toString(this) +
886
0
            ": corrupted dependent libraries section (unterminated string): " +
887
0
            name);
888
0
      return &InputSection::discarded;
889
0
    }
890
0
    for (const char *d = data.begin(), *e = data.end(); d < e;) {
891
0
      StringRef s(d);
892
0
      addDependentLibrary(s, this);
893
0
      d += s.size() + 1;
894
0
    }
895
0
    return &InputSection::discarded;
896
0
  }
897
130
  case SHT_RELA:
898
130
  case SHT_REL: {
899
130
    // Find a relocation target section and associate this section with that.
900
130
    // Target may have been discarded if it is in a different section group
901
130
    // and the group is discarded, even though it's a violation of the
902
130
    // spec. We handle that situation gracefully by discarding dangling
903
130
    // relocation sections.
904
130
    InputSectionBase *target = getRelocTarget(sec);
905
130
    if (!target)
906
0
      return nullptr;
907
130
908
130
    // This section contains relocation information.
909
130
    // If -r is given, we do not interpret or apply relocation
910
130
    // but just copy relocation sections to output.
911
130
    if (config->relocatable) {
912
10
      InputSection *relocSec = make<InputSection>(*this, sec, name);
913
10
      // We want to add a dependency to target, similar like we do for
914
10
      // -emit-relocs below. This is useful for the case when linker script
915
10
      // contains the "/DISCARD/". It is perhaps uncommon to use a script with
916
10
      // -r, but we faced it in the Linux kernel and have to handle such case
917
10
      // and not to crash.
918
10
      target->dependentSections.push_back(relocSec);
919
10
      return relocSec;
920
10
    }
921
120
922
120
    if (target->firstRelocation)
923
0
      fatal(toString(this) +
924
0
            ": multiple relocation sections to one section are not supported");
925
120
926
120
    // ELF spec allows mergeable sections with relocations, but they are
927
120
    // rare, and it is in practice hard to merge such sections by contents,
928
120
    // because applying relocations at end of linking changes section
929
120
    // contents. So, we simply handle such sections as non-mergeable ones.
930
120
    // Degrading like this is acceptable because section merging is optional.
931
120
    if (auto *ms = dyn_cast<MergeInputSection>(target)) {
932
0
      target = toRegularSection(ms);
933
0
      this->sections[sec.sh_info] = target;
934
0
    }
935
120
936
120
    if (sec.sh_type == SHT_RELA) {
937
37
      ArrayRef<Elf_Rela> rels = CHECK(getObj().relas(&sec), this);
938
37
      target->firstRelocation = rels.begin();
939
37
      target->numRelocations = rels.size();
940
37
      target->areRelocsRela = true;
941
83
    } else {
942
83
      ArrayRef<Elf_Rel> rels = CHECK(getObj().rels(&sec), this);
943
83
      target->firstRelocation = rels.begin();
944
83
      target->numRelocations = rels.size();
945
83
      target->areRelocsRela = false;
946
83
    }
947
120
    assert(isUInt<31>(target->numRelocations));
948
120
949
120
    // Relocation sections processed by the linker are usually removed
950
120
    // from the output, so returning `nullptr` for the normal case.
951
120
    // However, if -emit-relocs is given, we need to leave them in the output.
952
120
    // (Some post link analysis tools need this information.)
953
120
    if (config->emitRelocs) {
954
0
      InputSection *relocSec = make<InputSection>(*this, sec, name);
955
0
      // We will not emit relocation section if target was discarded.
956
0
      target->dependentSections.push_back(relocSec);
957
0
      return relocSec;
958
0
    }
959
120
    return nullptr;
960
120
  }
961
964
  }
962
964
963
964
  // The GNU linker uses .note.GNU-stack section as a marker indicating
964
964
  // that the code in the object file does not expect that the stack is
965
964
  // executable (in terms of NX bit). If all input files have the marker,
966
964
  // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
967
964
  // make the stack non-executable. Most object files have this section as
968
964
  // of 2017.
969
964
  //
970
964
  // But making the stack non-executable is a norm today for security
971
964
  // reasons. Failure to do so may result in a serious security issue.
972
964
  // Therefore, we make LLD always add PT_GNU_STACK unless it is
973
964
  // explicitly told to do otherwise (by -z execstack). Because the stack
974
964
  // executable-ness is controlled solely by command line options,
975
964
  // .note.GNU-stack sections are simply ignored.
976
964
  if (name == ".note.GNU-stack")
977
10
    return &InputSection::discarded;
978
954
979
954
  // Object files that use processor features such as Intel Control-Flow
980
954
  // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a
981
954
  // .note.gnu.property section containing a bitfield of feature bits like the
982
954
  // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag.
983
954
  //
984
954
  // Since we merge bitmaps from multiple object files to create a new
985
954
  // .note.gnu.property containing a single AND'ed bitmap, we discard an input
986
954
  // file's .note.gnu.property section.
987
954
  if (name == ".note.gnu.property") {
988
0
    ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(&sec));
989
0
    this->andFeatures = readAndFeatures(this, contents);
990
0
    return &InputSection::discarded;
991
0
  }
992
954
993
954
  // Split stacks is a feature to support a discontiguous stack,
994
954
  // commonly used in the programming language Go. For the details,
995
954
  // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled
996
954
  // for split stack will include a .note.GNU-split-stack section.
997
954
  if (name == ".note.GNU-split-stack") {
998
0
    if (config->relocatable) {
999
0
      error("cannot mix split-stack and non-split-stack in a relocatable link");
1000
0
      return &InputSection::discarded;
1001
0
    }
1002
0
    this->splitStack = true;
1003
0
    return &InputSection::discarded;
1004
0
  }
1005
954
1006
954
  // An object file cmpiled for split stack, but where some of the
1007
954
  // functions were compiled with the no_split_stack_attribute will
1008
954
  // include a .note.GNU-no-split-stack section.
1009
954
  if (name == ".note.GNU-no-split-stack") {
1010
0
    this->someNoSplitStack = true;
1011
0
    return &InputSection::discarded;
1012
0
  }
1013
954
1014
954
  // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
1015
954
  // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
1016
954
  // sections. Drop those sections to avoid duplicate symbol errors.
1017
954
  // FIXME: This is glibc PR20543, we should remove this hack once that has been
1018
954
  // fixed for a while.
1019
954
  if (name == ".gnu.linkonce.t.__x86.get_pc_thunk.bx" ||
1020
954
      name == ".gnu.linkonce.t.__i686.get_pc_thunk.bx")
1021
0
    return &InputSection::discarded;
1022
954
1023
954
  // If we are creating a new .build-id section, strip existing .build-id
1024
954
  // sections so that the output won't have more than one .build-id.
1025
954
  // This is not usually a problem because input object files normally don't
1026
954
  // have .build-id sections, but you can create such files by
1027
954
  // "ld.{bfd,gold,lld} -r --build-id", and we want to guard against it.
1028
954
  if (name == ".note.gnu.build-id" && 
config->buildId != BuildIdKind::None0
)
1029
0
    return &InputSection::discarded;
1030
954
1031
954
  // The linker merges EH (exception handling) frames and creates a
1032
954
  // .eh_frame_hdr section for runtime. So we handle them with a special
1033
954
  // class. For relocatable outputs, they are just passed through.
1034
954
  if (name == ".eh_frame" && 
!config->relocatable0
)
1035
0
    return make<EhInputSection>(*this, sec, name);
1036
954
1037
954
  if (shouldMerge(sec))
1038
1
    return make<MergeInputSection>(*this, sec, name);
1039
953
  return make<InputSection>(*this, sec, name);
1040
953
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >::createInputSection(llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true> > const&)
Line
Count
Source
857
336k
InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &sec) {
858
336k
  StringRef name = getSectionName(sec);
859
336k
860
336k
  switch (sec.sh_type) {
861
336k
  case SHT_ARM_ATTRIBUTES: {
862
0
    if (config->emachine != EM_ARM)
863
0
      break;
864
0
    ARMAttributeParser attributes;
865
0
    ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(&sec));
866
0
    attributes.Parse(contents, /*isLittle*/ config->ekind == ELF32LEKind);
867
0
    updateSupportedARMFeatures(attributes);
868
0
    updateARMVFPArgs(attributes, this);
869
0
870
0
    // FIXME: Retain the first attribute section we see. The eglibc ARM
871
0
    // dynamic loaders require the presence of an attribute section for dlopen
872
0
    // to work. In a full implementation we would merge all attribute sections.
873
0
    if (in.armAttributes == nullptr) {
874
0
      in.armAttributes = make<InputSection>(*this, sec, name);
875
0
      return in.armAttributes;
876
0
    }
877
0
    return &InputSection::discarded;
878
0
  }
879
11
  case SHT_LLVM_DEPENDENT_LIBRARIES: {
880
11
    if (config->relocatable)
881
2
      break;
882
9
    ArrayRef<char> data =
883
9
        CHECK(this->getObj().template getSectionContentsAsArray<char>(&sec), this);
884
9
    if (!data.empty() && data.back() != '\0') {
885
1
      error(toString(this) +
886
1
            ": corrupted dependent libraries section (unterminated string): " +
887
1
            name);
888
1
      return &InputSection::discarded;
889
1
    }
890
23
    
for (const char *d = data.begin(), *e = data.end(); 8
d < e;) {
891
15
      StringRef s(d);
892
15
      addDependentLibrary(s, this);
893
15
      d += s.size() + 1;
894
15
    }
895
8
    return &InputSection::discarded;
896
8
  }
897
1.49k
  case SHT_RELA:
898
1.49k
  case SHT_REL: {
899
1.49k
    // Find a relocation target section and associate this section with that.
900
1.49k
    // Target may have been discarded if it is in a different section group
901
1.49k
    // and the group is discarded, even though it's a violation of the
902
1.49k
    // spec. We handle that situation gracefully by discarding dangling
903
1.49k
    // relocation sections.
904
1.49k
    InputSectionBase *target = getRelocTarget(sec);
905
1.49k
    if (!target)
906
5
      return nullptr;
907
1.49k
908
1.49k
    // This section contains relocation information.
909
1.49k
    // If -r is given, we do not interpret or apply relocation
910
1.49k
    // but just copy relocation sections to output.
911
1.49k
    if (config->relocatable) {
912
56
      InputSection *relocSec = make<InputSection>(*this, sec, name);
913
56
      // We want to add a dependency to target, similar like we do for
914
56
      // -emit-relocs below. This is useful for the case when linker script
915
56
      // contains the "/DISCARD/". It is perhaps uncommon to use a script with
916
56
      // -r, but we faced it in the Linux kernel and have to handle such case
917
56
      // and not to crash.
918
56
      target->dependentSections.push_back(relocSec);
919
56
      return relocSec;
920
56
    }
921
1.43k
922
1.43k
    if (target->firstRelocation)
923
0
      fatal(toString(this) +
924
0
            ": multiple relocation sections to one section are not supported");
925
1.43k
926
1.43k
    // ELF spec allows mergeable sections with relocations, but they are
927
1.43k
    // rare, and it is in practice hard to merge such sections by contents,
928
1.43k
    // because applying relocations at end of linking changes section
929
1.43k
    // contents. So, we simply handle such sections as non-mergeable ones.
930
1.43k
    // Degrading like this is acceptable because section merging is optional.
931
1.43k
    if (auto *ms = dyn_cast<MergeInputSection>(target)) {
932
3
      target = toRegularSection(ms);
933
3
      this->sections[sec.sh_info] = target;
934
3
    }
935
1.43k
936
1.43k
    if (sec.sh_type == SHT_RELA) {
937
1.43k
      ArrayRef<Elf_Rela> rels = CHECK(getObj().relas(&sec), this);
938
1.43k
      target->firstRelocation = rels.begin();
939
1.43k
      target->numRelocations = rels.size();
940
1.43k
      target->areRelocsRela = true;
941
1.43k
    } else {
942
1
      ArrayRef<Elf_Rel> rels = CHECK(getObj().rels(&sec), this);
943
1
      target->firstRelocation = rels.begin();
944
1
      target->numRelocations = rels.size();
945
1
      target->areRelocsRela = false;
946
1
    }
947
1.43k
    assert(isUInt<31>(target->numRelocations));
948
1.43k
949
1.43k
    // Relocation sections processed by the linker are usually removed
950
1.43k
    // from the output, so returning `nullptr` for the normal case.
951
1.43k
    // However, if -emit-relocs is given, we need to leave them in the output.
952
1.43k
    // (Some post link analysis tools need this information.)
953
1.43k
    if (config->emitRelocs) {
954
33
      InputSection *relocSec = make<InputSection>(*this, sec, name);
955
33
      // We will not emit relocation section if target was discarded.
956
33
      target->dependentSections.push_back(relocSec);
957
33
      return relocSec;
958
33
    }
959
1.40k
    return nullptr;
960
1.40k
  }
961
334k
  }
962
334k
963
334k
  // The GNU linker uses .note.GNU-stack section as a marker indicating
964
334k
  // that the code in the object file does not expect that the stack is
965
334k
  // executable (in terms of NX bit). If all input files have the marker,
966
334k
  // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
967
334k
  // make the stack non-executable. Most object files have this section as
968
334k
  // of 2017.
969
334k
  //
970
334k
  // But making the stack non-executable is a norm today for security
971
334k
  // reasons. Failure to do so may result in a serious security issue.
972
334k
  // Therefore, we make LLD always add PT_GNU_STACK unless it is
973
334k
  // explicitly told to do otherwise (by -z execstack). Because the stack
974
334k
  // executable-ness is controlled solely by command line options,
975
334k
  // .note.GNU-stack sections are simply ignored.
976
334k
  if (name == ".note.GNU-stack")
977
234
    return &InputSection::discarded;
978
334k
979
334k
  // Object files that use processor features such as Intel Control-Flow
980
334k
  // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a
981
334k
  // .note.gnu.property section containing a bitfield of feature bits like the
982
334k
  // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag.
983
334k
  //
984
334k
  // Since we merge bitmaps from multiple object files to create a new
985
334k
  // .note.gnu.property containing a single AND'ed bitmap, we discard an input
986
334k
  // file's .note.gnu.property section.
987
334k
  if (name == ".note.gnu.property") {
988
28
    ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(&sec));
989
28
    this->andFeatures = readAndFeatures(this, contents);
990
28
    return &InputSection::discarded;
991
28
  }
992
334k
993
334k
  // Split stacks is a feature to support a discontiguous stack,
994
334k
  // commonly used in the programming language Go. For the details,
995
334k
  // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled
996
334k
  // for split stack will include a .note.GNU-split-stack section.
997
334k
  if (name == ".note.GNU-split-stack") {
998
19
    if (config->relocatable) {
999
2
      error("cannot mix split-stack and non-split-stack in a relocatable link");
1000
2
      return &InputSection::discarded;
1001
2
    }
1002
17
    this->splitStack = true;
1003
17
    return &InputSection::discarded;
1004
17
  }
1005
334k
1006
334k
  // An object file cmpiled for split stack, but where some of the
1007
334k
  // functions were compiled with the no_split_stack_attribute will
1008
334k
  // include a .note.GNU-no-split-stack section.
1009
334k
  if (name == ".note.GNU-no-split-stack") {
1010
1
    this->someNoSplitStack = true;
1011
1
    return &InputSection::discarded;
1012
1
  }
1013
334k
1014
334k
  // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
1015
334k
  // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
1016
334k
  // sections. Drop those sections to avoid duplicate symbol errors.
1017
334k
  // FIXME: This is glibc PR20543, we should remove this hack once that has been
1018
334k
  // fixed for a while.
1019
334k
  if (name == ".gnu.linkonce.t.__x86.get_pc_thunk.bx" ||
1020
334k
      
name == ".gnu.linkonce.t.__i686.get_pc_thunk.bx"334k
)
1021
4
    return &InputSection::discarded;
1022
334k
1023
334k
  // If we are creating a new .build-id section, strip existing .build-id
1024
334k
  // sections so that the output won't have more than one .build-id.
1025
334k
  // This is not usually a problem because input object files normally don't
1026
334k
  // have .build-id sections, but you can create such files by
1027
334k
  // "ld.{bfd,gold,lld} -r --build-id", and we want to guard against it.
1028
334k
  if (name == ".note.gnu.build-id" && 
config->buildId != BuildIdKind::None1
)
1029
1
    return &InputSection::discarded;
1030
334k
1031
334k
  // The linker merges EH (exception handling) frames and creates a
1032
334k
  // .eh_frame_hdr section for runtime. So we handle them with a special
1033
334k
  // class. For relocatable outputs, they are just passed through.
1034
334k
  if (name == ".eh_frame" && 
!config->relocatable112
)
1035
108
    return make<EhInputSection>(*this, sec, name);
1036
334k
1037
334k
  if (shouldMerge(sec))
1038
124
    return make<MergeInputSection>(*this, sec, name);
1039
334k
  return make<InputSection>(*this, sec, name);
1040
334k
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >::createInputSection(llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true> > const&)
Line
Count
Source
857
520
InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &sec) {
858
520
  StringRef name = getSectionName(sec);
859
520
860
520
  switch (sec.sh_type) {
861
520
  case SHT_ARM_ATTRIBUTES: {
862
0
    if (config->emachine != EM_ARM)
863
0
      break;
864
0
    ARMAttributeParser attributes;
865
0
    ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(&sec));
866
0
    attributes.Parse(contents, /*isLittle*/ config->ekind == ELF32LEKind);
867
0
    updateSupportedARMFeatures(attributes);
868
0
    updateARMVFPArgs(attributes, this);
869
0
870
0
    // FIXME: Retain the first attribute section we see. The eglibc ARM
871
0
    // dynamic loaders require the presence of an attribute section for dlopen
872
0
    // to work. In a full implementation we would merge all attribute sections.
873
0
    if (in.armAttributes == nullptr) {
874
0
      in.armAttributes = make<InputSection>(*this, sec, name);
875
0
      return in.armAttributes;
876
0
    }
877
0
    return &InputSection::discarded;
878
0
  }
879
0
  case SHT_LLVM_DEPENDENT_LIBRARIES: {
880
0
    if (config->relocatable)
881
0
      break;
882
0
    ArrayRef<char> data =
883
0
        CHECK(this->getObj().template getSectionContentsAsArray<char>(&sec), this);
884
0
    if (!data.empty() && data.back() != '\0') {
885
0
      error(toString(this) +
886
0
            ": corrupted dependent libraries section (unterminated string): " +
887
0
            name);
888
0
      return &InputSection::discarded;
889
0
    }
890
0
    for (const char *d = data.begin(), *e = data.end(); d < e;) {
891
0
      StringRef s(d);
892
0
      addDependentLibrary(s, this);
893
0
      d += s.size() + 1;
894
0
    }
895
0
    return &InputSection::discarded;
896
0
  }
897
108
  case SHT_RELA:
898
108
  case SHT_REL: {
899
108
    // Find a relocation target section and associate this section with that.
900
108
    // Target may have been discarded if it is in a different section group
901
108
    // and the group is discarded, even though it's a violation of the
902
108
    // spec. We handle that situation gracefully by discarding dangling
903
108
    // relocation sections.
904
108
    InputSectionBase *target = getRelocTarget(sec);
905
108
    if (!target)
906
0
      return nullptr;
907
108
908
108
    // This section contains relocation information.
909
108
    // If -r is given, we do not interpret or apply relocation
910
108
    // but just copy relocation sections to output.
911
108
    if (config->relocatable) {
912
2
      InputSection *relocSec = make<InputSection>(*this, sec, name);
913
2
      // We want to add a dependency to target, similar like we do for
914
2
      // -emit-relocs below. This is useful for the case when linker script
915
2
      // contains the "/DISCARD/". It is perhaps uncommon to use a script with
916
2
      // -r, but we faced it in the Linux kernel and have to handle such case
917
2
      // and not to crash.
918
2
      target->dependentSections.push_back(relocSec);
919
2
      return relocSec;
920
2
    }
921
106
922
106
    if (target->firstRelocation)
923
0
      fatal(toString(this) +
924
0
            ": multiple relocation sections to one section are not supported");
925
106
926
106
    // ELF spec allows mergeable sections with relocations, but they are
927
106
    // rare, and it is in practice hard to merge such sections by contents,
928
106
    // because applying relocations at end of linking changes section
929
106
    // contents. So, we simply handle such sections as non-mergeable ones.
930
106
    // Degrading like this is acceptable because section merging is optional.
931
106
    if (auto *ms = dyn_cast<MergeInputSection>(target)) {
932
0
      target = toRegularSection(ms);
933
0
      this->sections[sec.sh_info] = target;
934
0
    }
935
106
936
106
    if (sec.sh_type == SHT_RELA) {
937
106
      ArrayRef<Elf_Rela> rels = CHECK(getObj().relas(&sec), this);
938
106
      target->firstRelocation = rels.begin();
939
106
      target->numRelocations = rels.size();
940
106
      target->areRelocsRela = true;
941
106
    } else {
942
0
      ArrayRef<Elf_Rel> rels = CHECK(getObj().rels(&sec), this);
943
0
      target->firstRelocation = rels.begin();
944
0
      target->numRelocations = rels.size();
945
0
      target->areRelocsRela = false;
946
0
    }
947
106
    assert(isUInt<31>(target->numRelocations));
948
106
949
106
    // Relocation sections processed by the linker are usually removed
950
106
    // from the output, so returning `nullptr` for the normal case.
951
106
    // However, if -emit-relocs is given, we need to leave them in the output.
952
106
    // (Some post link analysis tools need this information.)
953
106
    if (config->emitRelocs) {
954
0
      InputSection *relocSec = make<InputSection>(*this, sec, name);
955
0
      // We will not emit relocation section if target was discarded.
956
0
      target->dependentSections.push_back(relocSec);
957
0
      return relocSec;
958
0
    }
959
106
    return nullptr;
960
106
  }
961
412
  }
962
412
963
412
  // The GNU linker uses .note.GNU-stack section as a marker indicating
964
412
  // that the code in the object file does not expect that the stack is
965
412
  // executable (in terms of NX bit). If all input files have the marker,
966
412
  // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
967
412
  // make the stack non-executable. Most object files have this section as
968
412
  // of 2017.
969
412
  //
970
412
  // But making the stack non-executable is a norm today for security
971
412
  // reasons. Failure to do so may result in a serious security issue.
972
412
  // Therefore, we make LLD always add PT_GNU_STACK unless it is
973
412
  // explicitly told to do otherwise (by -z execstack). Because the stack
974
412
  // executable-ness is controlled solely by command line options,
975
412
  // .note.GNU-stack sections are simply ignored.
976
412
  if (name == ".note.GNU-stack")
977
0
    return &InputSection::discarded;
978
412
979
412
  // Object files that use processor features such as Intel Control-Flow
980
412
  // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a
981
412
  // .note.gnu.property section containing a bitfield of feature bits like the
982
412
  // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag.
983
412
  //
984
412
  // Since we merge bitmaps from multiple object files to create a new
985
412
  // .note.gnu.property containing a single AND'ed bitmap, we discard an input
986
412
  // file's .note.gnu.property section.
987
412
  if (name == ".note.gnu.property") {
988
0
    ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(&sec));
989
0
    this->andFeatures = readAndFeatures(this, contents);
990
0
    return &InputSection::discarded;
991
0
  }
992
412
993
412
  // Split stacks is a feature to support a discontiguous stack,
994
412
  // commonly used in the programming language Go. For the details,
995
412
  // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled
996
412
  // for split stack will include a .note.GNU-split-stack section.
997
412
  if (name == ".note.GNU-split-stack") {
998
8
    if (config->relocatable) {
999
0
      error("cannot mix split-stack and non-split-stack in a relocatable link");
1000
0
      return &InputSection::discarded;
1001
0
    }
1002
8
    this->splitStack = true;
1003
8
    return &InputSection::discarded;
1004
8
  }
1005
404
1006
404
  // An object file cmpiled for split stack, but where some of the
1007
404
  // functions were compiled with the no_split_stack_attribute will
1008
404
  // include a .note.GNU-no-split-stack section.
1009
404
  if (name == ".note.GNU-no-split-stack") {
1010
0
    this->someNoSplitStack = true;
1011
0
    return &InputSection::discarded;
1012
0
  }
1013
404
1014
404
  // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
1015
404
  // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
1016
404
  // sections. Drop those sections to avoid duplicate symbol errors.
1017
404
  // FIXME: This is glibc PR20543, we should remove this hack once that has been
1018
404
  // fixed for a while.
1019
404
  if (name == ".gnu.linkonce.t.__x86.get_pc_thunk.bx" ||
1020
404
      name == ".gnu.linkonce.t.__i686.get_pc_thunk.bx")
1021
0
    return &InputSection::discarded;
1022
404
1023
404
  // If we are creating a new .build-id section, strip existing .build-id
1024
404
  // sections so that the output won't have more than one .build-id.
1025
404
  // This is not usually a problem because input object files normally don't
1026
404
  // have .build-id sections, but you can create such files by
1027
404
  // "ld.{bfd,gold,lld} -r --build-id", and we want to guard against it.
1028
404
  if (name == ".note.gnu.build-id" && 
config->buildId != BuildIdKind::None0
)
1029
0
    return &InputSection::discarded;
1030
404
1031
404
  // The linker merges EH (exception handling) frames and creates a
1032
404
  // .eh_frame_hdr section for runtime. So we handle them with a special
1033
404
  // class. For relocatable outputs, they are just passed through.
1034
404
  if (name == ".eh_frame" && 
!config->relocatable4
)
1035
4
    return make<EhInputSection>(*this, sec, name);
1036
400
1037
400
  if (shouldMerge(sec))
1038
0
    return make<MergeInputSection>(*this, sec, name);
1039
400
  return make<InputSection>(*this, sec, name);
1040
400
}
1041
1042
template <class ELFT>
1043
339k
StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &sec) {
1044
339k
  return CHECK(getObj().getSectionName(&sec, sectionStringTable), this);
1045
339k
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >::getSectionName(llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)1, false> > const&)
Line
Count
Source
1043
1.85k
StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &sec) {
1044
1.85k
  return CHECK(getObj().getSectionName(&sec, sectionStringTable), this);
1045
1.85k
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >::getSectionName(llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)0, false> > const&)
Line
Count
Source
1043
1.09k
StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &sec) {
1044
1.09k
  return CHECK(getObj().getSectionName(&sec, sectionStringTable), this);
1045
1.09k
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >::getSectionName(llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)1, true> > const&)
Line
Count
Source
1043
336k
StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &sec) {
1044
336k
  return CHECK(getObj().getSectionName(&sec, sectionStringTable), this);
1045
336k
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >::getSectionName(llvm::object::Elf_Shdr_Impl<llvm::object::ELFType<(llvm::support::endianness)0, true> > const&)
Line
Count
Source
1043
520
StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &sec) {
1044
520
  return CHECK(getObj().getSectionName(&sec, sectionStringTable), this);
1045
520
}
1046
1047
// Initialize this->Symbols. this->Symbols is a parallel array as
1048
// its corresponding ELF symbol table.
1049
3.47k
template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
1050
3.47k
  ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1051
3.47k
  this->symbols.resize(eSyms.size());
1052
3.47k
1053
3.47k
  // Our symbol table may have already been partially initialized
1054
3.47k
  // because of LazyObjFile.
1055
92.1k
  for (size_t i = 0, end = eSyms.size(); i != end; 
++i88.7k
)
1056
88.7k
    if (!this->symbols[i] && 
eSyms[i].getBinding() != STB_LOCAL88.7k
)
1057
16.7k
      this->symbols[i] =
1058
16.7k
          symtab->insert(CHECK(eSyms[i].getName(this->stringTable), this));
1059
3.47k
1060
3.47k
  // Fill this->Symbols. A symbol is either local or global.
1061
92.1k
  for (size_t i = 0, end = eSyms.size(); i != end; 
++i88.7k
) {
1062
88.7k
    const Elf_Sym &eSym = eSyms[i];
1063
88.7k
1064
88.7k
    // Read symbol attributes.
1065
88.7k
    uint32_t secIdx = getSectionIndex(eSym);
1066
88.7k
    if (secIdx >= this->sections.size())
1067
0
      fatal(toString(this) + ": invalid section index: " + Twine(secIdx));
1068
88.7k
1069
88.7k
    InputSectionBase *sec = this->sections[secIdx];
1070
88.7k
    uint8_t binding = eSym.getBinding();
1071
88.7k
    uint8_t stOther = eSym.st_other;
1072
88.7k
    uint8_t type = eSym.getType();
1073
88.7k
    uint64_t value = eSym.st_value;
1074
88.7k
    uint64_t size = eSym.st_size;
1075
88.7k
    StringRefZ name = this->stringTable.data() + eSym.st_name;
1076
88.7k
1077
88.7k
    // Handle local symbols. Local symbols are not added to the symbol
1078
88.7k
    // table because they are not visible from other object files. We
1079
88.7k
    // allocate symbol instances and add their pointers to Symbols.
1080
88.7k
    if (binding == STB_LOCAL) {
1081
71.9k
      if (eSym.getType() == STT_FILE)
1082
236
        sourceFile = CHECK(eSym.getName(this->stringTable), this);
1083
71.9k
1084
71.9k
      if (this->stringTable.size() <= eSym.st_name)
1085
0
        fatal(toString(this) + ": invalid symbol name offset");
1086
71.9k
1087
71.9k
      if (eSym.st_shndx == SHN_UNDEF)
1088
3.47k
        this->symbols[i] = make<Undefined>(this, name, binding, stOther, type);
1089
68.4k
      else if (sec == &InputSection::discarded)
1090
62
        this->symbols[i] = make<Undefined>(this, name, binding, stOther, type,
1091
62
                                           /*DiscardedSecIdx=*/secIdx);
1092
68.3k
      else
1093
68.3k
        this->symbols[i] =
1094
68.3k
            make<Defined>(this, name, binding, stOther, type, value, size, sec);
1095
71.9k
      continue;
1096
71.9k
    }
1097
16.8k
1098
16.8k
    // Handle global undefined symbols.
1099
16.8k
    if (eSym.st_shndx == SHN_UNDEF) {
1100
1.84k
      this->symbols[i]->resolve(Undefined{this, name, binding, stOther, type});
1101
1.84k
      continue;
1102
1.84k
    }
1103
14.9k
1104
14.9k
    // Handle global common symbols.
1105
14.9k
    if (eSym.st_shndx == SHN_COMMON) {
1106
125
      if (value == 0 || value >= UINT32_MAX)
1107
125
        fatal(toString(this) + ": common symbol '" + StringRef(name.data) +
1108
0
              "' has invalid alignment: " + Twine(value));
1109
125
      this->symbols[i]->resolve(
1110
125
          CommonSymbol{this, name, binding, stOther, type, value, size});
1111
125
      continue;
1112
125
    }
1113
14.8k
1114
14.8k
    // If a defined symbol is in a discarded section, handle it as if it
1115
14.8k
    // were an undefined symbol. Such symbol doesn't comply with the
1116
14.8k
    // standard, but in practice, a .eh_frame often directly refer
1117
14.8k
    // COMDAT member sections, and if a comdat group is discarded, some
1118
14.8k
    // defined symbol in a .eh_frame becomes dangling symbols.
1119
14.8k
    if (sec == &InputSection::discarded) {
1120
21
      this->symbols[i]->resolve(
1121
21
          Undefined{this, name, binding, stOther, type, secIdx});
1122
21
      continue;
1123
21
    }
1124
14.8k
1125
14.8k
    // Handle global defined symbols.
1126
14.8k
    if (binding == STB_GLOBAL || 
binding == STB_WEAK98
||
1127
14.8k
        
binding == STB_GNU_UNIQUE3
) {
1128
14.8k
      this->symbols[i]->resolve(
1129
14.8k
          Defined{this, name, binding, stOther, type, value, size, sec});
1130
14.8k
      continue;
1131
14.8k
    }
1132
0
1133
0
    fatal(toString(this) + ": unexpected binding: " + Twine((int)binding));
1134
0
  }
1135
3.47k
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, false> >::initializeSymbols()
Line
Count
Source
1049
460
template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
1050
460
  ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1051
460
  this->symbols.resize(eSyms.size());
1052
460
1053
460
  // Our symbol table may have already been partially initialized
1054
460
  // because of LazyObjFile.
1055
3.08k
  for (size_t i = 0, end = eSyms.size(); i != end; 
++i2.62k
)
1056
2.62k
    if (!this->symbols[i] && eSyms[i].getBinding() != STB_LOCAL)
1057
1.26k
      this->symbols[i] =
1058
1.26k
          symtab->insert(CHECK(eSyms[i].getName(this->stringTable), this));
1059
460
1060
460
  // Fill this->Symbols. A symbol is either local or global.
1061
3.08k
  for (size_t i = 0, end = eSyms.size(); i != end; 
++i2.62k
) {
1062
2.62k
    const Elf_Sym &eSym = eSyms[i];
1063
2.62k
1064
2.62k
    // Read symbol attributes.
1065
2.62k
    uint32_t secIdx = getSectionIndex(eSym);
1066
2.62k
    if (secIdx >= this->sections.size())
1067
0
      fatal(toString(this) + ": invalid section index: " + Twine(secIdx));
1068
2.62k
1069
2.62k
    InputSectionBase *sec = this->sections[secIdx];
1070
2.62k
    uint8_t binding = eSym.getBinding();
1071
2.62k
    uint8_t stOther = eSym.st_other;
1072
2.62k
    uint8_t type = eSym.getType();
1073
2.62k
    uint64_t value = eSym.st_value;
1074
2.62k
    uint64_t size = eSym.st_size;
1075
2.62k
    StringRefZ name = this->stringTable.data() + eSym.st_name;
1076
2.62k
1077
2.62k
    // Handle local symbols. Local symbols are not added to the symbol
1078
2.62k
    // table because they are not visible from other object files. We
1079
2.62k
    // allocate symbol instances and add their pointers to Symbols.
1080
2.62k
    if (binding == STB_LOCAL) {
1081
1.35k
      if (eSym.getType() == STT_FILE)
1082
3
        sourceFile = CHECK(eSym.getName(this->stringTable), this);
1083
1.35k
1084
1.35k
      if (this->stringTable.size() <= eSym.st_name)
1085
0
        fatal(toString(this) + ": invalid symbol name offset");
1086
1.35k
1087
1.35k
      if (eSym.st_shndx == SHN_UNDEF)
1088
460
        this->symbols[i] = make<Undefined>(this, name, binding, stOther, type);
1089
897
      else if (sec == &InputSection::discarded)
1090
0
        this->symbols[i] = make<Undefined>(this, name, binding, stOther, type,
1091
0
                                           /*DiscardedSecIdx=*/secIdx);
1092
897
      else
1093
897
        this->symbols[i] =
1094
897
            make<Defined>(this, name, binding, stOther, type, value, size, sec);
1095
1.35k
      continue;
1096
1.35k
    }
1097
1.26k
1098
1.26k
    // Handle global undefined symbols.
1099
1.26k
    if (eSym.st_shndx == SHN_UNDEF) {
1100
267
      this->symbols[i]->resolve(Undefined{this, name, binding, stOther, type});
1101
267
      continue;
1102
267
    }
1103
1.00k
1104
1.00k
    // Handle global common symbols.
1105
1.00k
    if (eSym.st_shndx == SHN_COMMON) {
1106
6
      if (value == 0 || value >= UINT32_MAX)
1107
6
        fatal(toString(this) + ": common symbol '" + StringRef(name.data) +
1108
0
              "' has invalid alignment: " + Twine(value));
1109
6
      this->symbols[i]->resolve(
1110
6
          CommonSymbol{this, name, binding, stOther, type, value, size});
1111
6
      continue;
1112
6
    }
1113
995
1114
995
    // If a defined symbol is in a discarded section, handle it as if it
1115
995
    // were an undefined symbol. Such symbol doesn't comply with the
1116
995
    // standard, but in practice, a .eh_frame often directly refer
1117
995
    // COMDAT member sections, and if a comdat group is discarded, some
1118
995
    // defined symbol in a .eh_frame becomes dangling symbols.
1119
995
    if (sec == &InputSection::discarded) {
1120
1
      this->symbols[i]->resolve(
1121
1
          Undefined{this, name, binding, stOther, type, secIdx});
1122
1
      continue;
1123
1
    }
1124
994
1125
994
    // Handle global defined symbols.
1126
994
    if (binding == STB_GLOBAL || 
binding == STB_WEAK1
||
1127
994
        
binding == STB_GNU_UNIQUE0
) {
1128
994
      this->symbols[i]->resolve(
1129
994
          Defined{this, name, binding, stOther, type, value, size, sec});
1130
994
      continue;
1131
994
    }
1132
0
1133
0
    fatal(toString(this) + ": unexpected binding: " + Twine((int)binding));
1134
0
  }
1135
460
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, false> >::initializeSymbols()
Line
Count
Source
1049
210
template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
1050
210
  ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1051
210
  this->symbols.resize(eSyms.size());
1052
210
1053
210
  // Our symbol table may have already been partially initialized
1054
210
  // because of LazyObjFile.
1055
1.04k
  for (size_t i = 0, end = eSyms.size(); i != end; 
++i830
)
1056
830
    if (!this->symbols[i] && eSyms[i].getBinding() != STB_LOCAL)
1057
485
      this->symbols[i] =
1058
485
          symtab->insert(CHECK(eSyms[i].getName(this->stringTable), this));
1059
210
1060
210
  // Fill this->Symbols. A symbol is either local or global.
1061
1.04k
  for (size_t i = 0, end = eSyms.size(); i != end; 
++i830
) {
1062
830
    const Elf_Sym &eSym = eSyms[i];
1063
830
1064
830
    // Read symbol attributes.
1065
830
    uint32_t secIdx = getSectionIndex(eSym);
1066
830
    if (secIdx >= this->sections.size())
1067
0
      fatal(toString(this) + ": invalid section index: " + Twine(secIdx));
1068
830
1069
830
    InputSectionBase *sec = this->sections[secIdx];
1070
830
    uint8_t binding = eSym.getBinding();
1071
830
    uint8_t stOther = eSym.st_other;
1072
830
    uint8_t type = eSym.getType();
1073
830
    uint64_t value = eSym.st_value;
1074
830
    uint64_t size = eSym.st_size;
1075
830
    StringRefZ name = this->stringTable.data() + eSym.st_name;
1076
830
1077
830
    // Handle local symbols. Local symbols are not added to the symbol
1078
830
    // table because they are not visible from other object files. We
1079
830
    // allocate symbol instances and add their pointers to Symbols.
1080
830
    if (binding == STB_LOCAL) {
1081
345
      if (eSym.getType() == STT_FILE)
1082
0
        sourceFile = CHECK(eSym.getName(this->stringTable), this);
1083
345
1084
345
      if (this->stringTable.size() <= eSym.st_name)
1085
0
        fatal(toString(this) + ": invalid symbol name offset");
1086
345
1087
345
      if (eSym.st_shndx == SHN_UNDEF)
1088
210
        this->symbols[i] = make<Undefined>(this, name, binding, stOther, type);
1089
135
      else if (sec == &InputSection::discarded)
1090
0
        this->symbols[i] = make<Undefined>(this, name, binding, stOther, type,
1091
0
                                           /*DiscardedSecIdx=*/secIdx);
1092
135
      else
1093
135
        this->symbols[i] =
1094
135
            make<Defined>(this, name, binding, stOther, type, value, size, sec);
1095
345
      continue;
1096
345
    }
1097
485
1098
485
    // Handle global undefined symbols.
1099
485
    if (eSym.st_shndx == SHN_UNDEF) {
1100
142
      this->symbols[i]->resolve(Undefined{this, name, binding, stOther, type});
1101
142
      continue;
1102
142
    }
1103
343
1104
343
    // Handle global common symbols.
1105
343
    if (eSym.st_shndx == SHN_COMMON) {
1106
0
      if (value == 0 || value >= UINT32_MAX)
1107
0
        fatal(toString(this) + ": common symbol '" + StringRef(name.data) +
1108
0
              "' has invalid alignment: " + Twine(value));
1109
0
      this->symbols[i]->resolve(
1110
0
          CommonSymbol{this, name, binding, stOther, type, value, size});
1111
0
      continue;
1112
0
    }
1113
343
1114
343
    // If a defined symbol is in a discarded section, handle it as if it
1115
343
    // were an undefined symbol. Such symbol doesn't comply with the
1116
343
    // standard, but in practice, a .eh_frame often directly refer
1117
343
    // COMDAT member sections, and if a comdat group is discarded, some
1118
343
    // defined symbol in a .eh_frame becomes dangling symbols.
1119
343
    if (sec == &InputSection::discarded) {
1120
0
      this->symbols[i]->resolve(
1121
0
          Undefined{this, name, binding, stOther, type, secIdx});
1122
0
      continue;
1123
0
    }
1124
343
1125
343
    // Handle global defined symbols.
1126
343
    if (binding == STB_GLOBAL || 
binding == STB_WEAK2
||
1127
343
        
binding == STB_GNU_UNIQUE0
) {
1128
343
      this->symbols[i]->resolve(
1129
343
          Defined{this, name, binding, stOther, type, value, size, sec});
1130
343
      continue;
1131
343
    }
1132
0
1133
0
    fatal(toString(this) + ": unexpected binding: " + Twine((int)binding));
1134
0
  }
1135
210
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)1, true> >::initializeSymbols()
Line
Count
Source
1049
2.66k
template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
1050
2.66k
  ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1051
2.66k
  this->symbols.resize(eSyms.size());
1052
2.66k
1053
2.66k
  // Our symbol table may have already been partially initialized
1054
2.66k
  // because of LazyObjFile.
1055
77.3k
  for (size_t i = 0, end = eSyms.size(); i != end; 
++i74.7k
)
1056
74.7k
    if (!this->symbols[i] && 
eSyms[i].getBinding() != STB_LOCAL74.7k
)
1057
4.73k
      this->symbols[i] =
1058
4.73k
          symtab->insert(CHECK(eSyms[i].getName(this->stringTable), this));
1059
2.66k
1060
2.66k
  // Fill this->Symbols. A symbol is either local or global.
1061
77.3k
  for (size_t i = 0, end = eSyms.size(); i != end; 
++i74.7k
) {
1062
74.7k
    const Elf_Sym &eSym = eSyms[i];
1063
74.7k
1064
74.7k
    // Read symbol attributes.
1065
74.7k
    uint32_t secIdx = getSectionIndex(eSym);
1066
74.7k
    if (secIdx >= this->sections.size())
1067
0
      fatal(toString(this) + ": invalid section index: " + Twine(secIdx));
1068
74.7k
1069
74.7k
    InputSectionBase *sec = this->sections[secIdx];
1070
74.7k
    uint8_t binding = eSym.getBinding();
1071
74.7k
    uint8_t stOther = eSym.st_other;
1072
74.7k
    uint8_t type = eSym.getType();
1073
74.7k
    uint64_t value = eSym.st_value;
1074
74.7k
    uint64_t size = eSym.st_size;
1075
74.7k
    StringRefZ name = this->stringTable.data() + eSym.st_name;
1076
74.7k
1077
74.7k
    // Handle local symbols. Local symbols are not added to the symbol
1078
74.7k
    // table because they are not visible from other object files. We
1079
74.7k
    // allocate symbol instances and add their pointers to Symbols.
1080
74.7k
    if (binding == STB_LOCAL) {
1081
69.9k
      if (eSym.getType() == STT_FILE)
1082
232
        sourceFile = CHECK(eSym.getName(this->stringTable), this);
1083
69.9k
1084
69.9k
      if (this->stringTable.size() <= eSym.st_name)
1085
0
        fatal(toString(this) + ": invalid symbol name offset");
1086
69.9k
1087
69.9k
      if (eSym.st_shndx == SHN_UNDEF)
1088
2.66k
        this->symbols[i] = make<Undefined>(this, name, binding, stOther, type);
1089
67.3k
      else if (sec == &InputSection::discarded)
1090
62
        this->symbols[i] = make<Undefined>(this, name, binding, stOther, type,
1091
62
                                           /*DiscardedSecIdx=*/secIdx);
1092
67.2k
      else
1093
67.2k
        this->symbols[i] =
1094
67.2k
            make<Defined>(this, name, binding, stOther, type, value, size, sec);
1095
69.9k
      continue;
1096
69.9k
    }
1097
4.75k
1098
4.75k
    // Handle global undefined symbols.
1099
4.75k
    if (eSym.st_shndx == SHN_UNDEF) {
1100
1.32k
      this->symbols[i]->resolve(Undefined{this, name, binding, stOther, type});
1101
1.32k
      continue;
1102
1.32k
    }
1103
3.42k
1104
3.42k
    // Handle global common symbols.
1105
3.42k
    if (eSym.st_shndx == SHN_COMMON) {
1106
113
      if (value == 0 || value >= UINT32_MAX)
1107
113
        fatal(toString(this) + ": common symbol '" + StringRef(name.data) +
1108
0
              "' has invalid alignment: " + Twine(value));
1109
113
      this->symbols[i]->resolve(
1110
113
          CommonSymbol{this, name, binding, stOther, type, value, size});
1111
113
      continue;
1112
113
    }
1113
3.31k
1114
3.31k
    // If a defined symbol is in a discarded section, handle it as if it
1115
3.31k
    // were an undefined symbol. Such symbol doesn't comply with the
1116
3.31k
    // standard, but in practice, a .eh_frame often directly refer
1117
3.31k
    // COMDAT member sections, and if a comdat group is discarded, some
1118
3.31k
    // defined symbol in a .eh_frame becomes dangling symbols.
1119
3.31k
    if (sec == &InputSection::discarded) {
1120
20
      this->symbols[i]->resolve(
1121
20
          Undefined{this, name, binding, stOther, type, secIdx});
1122
20
      continue;
1123
20
    }
1124
3.29k
1125
3.29k
    // Handle global defined symbols.
1126
3.29k
    if (binding == STB_GLOBAL || 
binding == STB_WEAK95
||
1127
3.29k
        
binding == STB_GNU_UNIQUE3
) {
1128
3.29k
      this->symbols[i]->resolve(
1129
3.29k
          Defined{this, name, binding, stOther, type, value, size, sec});
1130
3.29k
      continue;
1131
3.29k
    }
1132
0
1133
0
    fatal(toString(this) + ": unexpected binding: " + Twine((int)binding));
1134
0
  }
1135
2.66k
}
lld::elf::ObjFile<llvm::object::ELFType<(llvm::support::endianness)0, true> >::initializeSymbols()
Line
Count
Source
1049
138
template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
1050
138
  ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1051
138
  this->symbols.resize(eSyms.size());
1052
138
1053
138
  // Our symbol table may have already been partially initialized
1054
138
  // because of LazyObjFile.
1055
10.6k
  for (size_t i = 0, end = eSyms.size(); i != end; 
++i10.5k
)
1056
10.5k
    if (!this->symbols[i] && eSyms[i].getBinding() != STB_LOCAL)
1057
10.3k
      this->symbols[i] =
1058
10.3k
          symtab->insert(CHECK(eSyms[i].getName(this->stringTable), this));
1059
138
1060
138
  // Fill this->Symbols. A symbol is either local or global.
1061
10.6k
  for (size_t i = 0, end = eSyms.size(); i != end; 
++i10.5k
) {
1062
10.5k
    const Elf_Sym &eSym = eSyms[i];
1063
10.5k
1064
10.5k
    // Read symbol attributes.
1065
10.5k
    uint32_t secIdx = getSectionIndex(eSym);
1066
10.5k
    if (secIdx >= this->sections.size())
1067
0
      fatal(toString(this) + ": invalid section index: " + Twine(secIdx));
1068
10.5k
1069
10.5k
    InputSectionBase *sec = this->sections[secIdx];
1070
10.5k
    uint8_t binding = eSym.getBinding();
1071
10.5k
    uint8_t stOther = eSym.st_other;
1072
10.5k
    uint8_t type = eSym.getType();
1073
10.5k
    uint64_t value = eSym.st_value;
1074
10.5k
    uint64_t size = eSym.st_size;
1075
10.5k
    StringRefZ name = this->stringTable.data() + eSym.st_name;
1076
10.5k
1077
10.5k
    // Handle local symbols. Local symbols are not added to the symbol
1078
10.5k
    // table because they are not visible from other object files. We
1079
10.5k
    // allocate symbol instances and add their pointers to Symbols.
1080
10.5k
    if (binding == STB_LOCAL) {
1081
236
      if (eSym.getType() == STT_FILE)
1082
1
        sourceFile = CHECK(eSym.getName(this->stringTable), this);
1083
236
1084
236
      if (this->stringTable.size() <= eSym.st_name)
1085
0
        fatal(toString(this) + ": invalid symbol name offset");
1086
236
1087
236
      if (eSym.st_shndx == SHN_UNDEF)
1088
138
        this->symbols[i] = make<Undefined>(this, name, binding, stOther, type);
1089
98
      else if (sec == &InputSection::discarded)
1090
0
        this->symbols[i] = make<Undefined>(this, name, binding, stOther, type,
1091
0
                                           /*DiscardedSecIdx=*/secIdx);
1092
98
      else
1093
98
        this->symbols[i] =
1094
98
            make<Defined>(this, name, binding, stOther, type, value, size, sec);
1095
236
      continue;
1096
236
    }
1097
10.3k
1098
10.3k
    // Handle global undefined symbols.
1099
10.3k
    if (eSym.st_shndx == SHN_UNDEF) {
1100
111
      this->symbols[i]->resolve(Undefined{this, name, binding, stOther, type});
1101
111
      continue;
1102
111
    }
1103
10.1k
1104
10.1k
    // Handle global common symbols.
1105
10.1k
    if (eSym.st_shndx == SHN_COMMON) {
1106
6
      if (value == 0 || value >= UINT32_MAX)
1107
6
        fatal(toString(this) + ": common symbol '" + StringRef(name.data) +
1108
0
              "' has invalid alignment: " + Twine(value));
1109
6
      this->symbols[i]->resolve(
1110
6
          CommonSymbol{this, name, binding, stOther, type, value, size});
1111
6
      continue;
1112
6
    }
1113
10.1k
1114
10.1k
    // If a defined symbol is in a discarded section, handle it as if it
1115
10.1k
    // were an undefined symbol. Such symbol doesn't comply with the
1116
10.1k
    // standard, but in practice, a .eh_frame often directly refer
1117
10.1k
    // COMDAT member sections, and if a comdat group is discarded, some
1118
10.1k
    // defined symbol in a .eh_frame becomes dangling symbols.
1119
10.1k
    if (sec == &InputSection::discarded) {
1120
0
      this->symbols[i]->resolve(
1121
0
          Undefined{this, name, binding, stOther, type, secIdx});
1122
0
      continue;
1123
0
    }
1124
10.1k
1125
10.1k
    // Handle global defined symbols.
1126
10.1k
    if (binding == STB_GLOBAL || 
binding == STB_WEAK0
||
1127
10.1k
        
binding == STB_GNU_UNIQUE0
) {
1128
10.1k
      this->symbols[i]->resolve(
1129
10.1k
          Defined{this, name, binding, stOther, type, value, size, sec});
1130
10.1k
      continue;
1131
10.1k
    }
1132
0
1133
0
    fatal(toString(this) + ": unexpected binding: " + Twine((int)binding));
1134
0
  }
1135
138
}
1136
1137
ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&file)
1138
    : InputFile(ArchiveKind, file->getMemoryBufferRef()),
1139
121
      file(std::move(file)) {}
1140
1141
118
void ArchiveFile::parse() {
1142
118
  for (const Archive::Symbol &sym : file->symbols())
1143
219
    symtab->addSymbol(LazyArchive{*this, sym});
1144
118
}
1145
1146
// Returns a buffer pointing to a member file containing a given symbol.
1147
100
void ArchiveFile::fetch(const Archive::Symbol &sym) {
1148
100
  Archive::Child c =
1149
100
      CHECK(sym.getMember(), toString(this) +
1150
100
                                 ": could not get the member for symbol " +
1151
100
                                 toELFString(sym));
1152
100
1153
100
  if (!seen.insert(c.getChildOffset()).second)
1154
3
    return;
1155
97
1156
97
  MemoryBufferRef mb =
1157
97
      CHECK(c.getMemoryBufferRef(),
1158
97
            toString(this) +
1159
97
                ": could not get the buffer for the member defining symbol " +
1160
97
                toELFString(sym));
1161
97
1162
97
  if (tar && 
c.getParent()->isThin()1
)
1163
1
    tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
1164
97
1165
97
  InputFile *file = createObjectFile(
1166
97
      mb, getName(), c.getParent()->isThin() ? 
03
:
c.getChildOffset()94
);
1167
97
  file->groupId = groupId;
1168
97
  parseFile(file);
1169
97
}
1170
1171
unsigned SharedFile::vernauxNum;
1172
1173
// Parse the version definitions in the object file if present, and return a
1174
// vector whose nth element contains a pointer to the Elf_Verdef for version
1175
// identifier n. Version identifiers that are not definitions map to nullptr.
1176
template <typename ELFT>
1177
static std::vector<const void *> parseVerdefs(const uint8_t *base,
1178
403
                                              const typename ELFT::Shdr *sec) {
1179
403
  if (!sec)
1180
387
    return {};
1181
16
1182
16
  // We cannot determine the largest verdef identifier without inspecting
1183
16
  // every Elf_Verdef, but both bfd and gold assign verdef identifiers
1184
16
  // sequentially starting from 1, so we predict that the largest identifier
1185
16
  // will be verdefCount.
1186
16
  unsigned verdefCount = sec->sh_info;
1187
16
  std::vector<const void *> verdefs(verdefCount + 1);
1188
16
1189
16
  // Build the Verdefs array by following the chain of Elf_Verdef objects
1190
16
  // from the start of the .gnu.version_d section.
1191
16
  const uint8_t *verdef = base + sec->sh_offset;
1192
68
  for (unsigned i = 0; i != verdefCount; 
++i52
) {
1193
52
    auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef);
1194
52
    verdef += curVerdef->vd_next;
1195
52
    unsigned verdefIndex = curVerdef->vd_ndx;
1196
52
    verdefs.resize(verdefIndex + 1);
1197
52
    verdefs[verdefIndex] = curVerdef;
1198
52
  }
1199
16
  return verdefs;
1200
16
}
InputFiles.cpp:std::__1::vector<void const*, std::__1::allocator<void const*> > parseVerdefs<llvm::object::ELFType<(llvm::support::endianness)1, false> >(unsigned char const*, llvm::object::ELFType<(llvm::support::endianness)1, false>::Shdr const*)
Line
Count
Source
1178
64
                                              const typename ELFT::Shdr *sec) {
1179
64
  if (!sec)
1180
64
    return {};
1181
0
1182
0
  // We cannot determine the largest verdef identifier without inspecting
1183
0
  // every Elf_Verdef, but both bfd and gold assign verdef identifiers
1184
0
  // sequentially starting from 1, so we predict that the largest identifier
1185
0
  // will be verdefCount.
1186
0
  unsigned verdefCount = sec->sh_info;
1187
0
  std::vector<const void *> verdefs(verdefCount + 1);
1188
0
1189
0
  // Build the Verdefs array by following the chain of Elf_Verdef objects
1190
0
  // from the start of the .gnu.version_d section.
1191
0
  const uint8_t *verdef = base + sec->sh_offset;
1192
0
  for (unsigned i = 0; i != verdefCount; ++i) {
1193
0
    auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef);
1194
0
    verdef += curVerdef->vd_next;
1195
0
    unsigned verdefIndex = curVerdef->vd_ndx;
1196
0
    verdefs.resize(verdefIndex + 1);
1197
0
    verdefs[verdefIndex] = curVerdef;
1198
0
  }
1199
0
  return verdefs;
1200
0
}
InputFiles.cpp:std::__1::vector<void const*, std::__1::allocator<void const*> > parseVerdefs<llvm::object::ELFType<(llvm::support::endianness)0, false> >(unsigned char const*, llvm::object::ELFType<(llvm::support::endianness)0, false>::Shdr const*)
Line
Count
Source
1178
29
                                              const typename ELFT::Shdr *sec) {
1179
29
  if (!sec)
1180
28
    return {};
1181
1
1182
1
  // We cannot determine the largest verdef identifier without inspecting
1183
1
  // every Elf_Verdef, but both bfd and gold assign verdef identifiers
1184
1
  // sequentially starting from 1, so we predict that the largest identifier
1185
1
  // will be verdefCount.
1186
1
  unsigned verdefCount = sec->sh_info;
1187
1
  std::vector<const void *> verdefs(verdefCount + 1);
1188
1
1189
1
  // Build the Verdefs array by following the chain of Elf_Verdef objects
1190
1
  // from the start of the .gnu.version_d section.
1191
1
  const uint8_t *verdef = base + sec->sh_offset;
1192
3
  for (unsigned i = 0; i != verdefCount; 
++i2
) {
1193
2
    auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef);
1194
2
    verdef += curVerdef->vd_next;
1195
2
    unsigned verdefIndex = curVerdef->vd_ndx;
1196
2
    verdefs.resize(verdefIndex + 1);
1197
2
    verdefs[verdefIndex] = curVerdef;
1198
2
  }
1199
1
  return verdefs;
1200
1
}
InputFiles.cpp:std::__1::vector<void const*, std::__1::allocator<void const*> > parseVerdefs<llvm::object::ELFType<(llvm::support::endianness)1, true> >(unsigned char const*, llvm::object::ELFType<(llvm::support::endianness)1, true>::Shdr const*)
Line
Count
Source
1178
295
                                              const typename ELFT::Shdr *sec) {
1179
295
  if (!sec)
1180
281
    return {};
1181
14
1182
14
  // We cannot determine the largest verdef identifier without inspecting
1183
14
  // every Elf_Verdef, but both bfd and gold assign verdef identifiers
1184
14
  // sequentially starting from 1, so we predict that the largest identifier
1185
14
  // will be verdefCount.
1186
14
  unsigned verdefCount = sec->sh_info;
1187
14
  std::vector<const void *> verdefs(verdefCount + 1);
1188
14
1189
14
  // Build the Verdefs array by following the chain of Elf_Verdef objects
1190
14
  // from the start of the .gnu.version_d section.
1191
14
  const uint8_t *verdef = base + sec->sh_offset;
1192
56
  for (unsigned i = 0; i != verdefCount; 
++i42
) {
1193
42
    auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef);
1194
42
    verdef += curVerdef->vd_next;
1195
42
    unsigned verdefIndex = curVerdef->vd_ndx;
1196
42
    verdefs.resize(verdefIndex + 1);
1197
42
    verdefs[verdefIndex] = curVerdef;
1198
42
  }
1199
14
  return verdefs;
1200
14
}
InputFiles.cpp:std::__1::vector<void const*, std::__1::allocator<void const*> > parseVerdefs<llvm::object::ELFType<(llvm::support::endianness)0, true> >(unsigned char const*, llvm::object::ELFType<(llvm::support::endianness)0, true>::Shdr const*)
Line
Count
Source
1178
15
                                              const typename ELFT::Shdr *sec) {
1179
15
  if (!sec)
1180
14
    return {};
1181
1
1182
1
  // We cannot determine the largest verdef identifier without inspecting
1183
1
  // every Elf_Verdef, but both bfd and gold assign verdef identifiers
1184
1
  // sequentially starting from 1, so we predict that the largest identifier
1185
1
  // will be verdefCount.
1186
1
  unsigned verdefCount = sec->sh_info;
1187
1
  std::vector<const void *> verdefs(verdefCount + 1);
1188
1
1189
1
  // Build the Verdefs array by following the chain of Elf_Verdef objects
1190
1
  // from the start of the .gnu.version_d section.
1191
1
  const uint8_t *verdef = base + sec->sh_offset;
1192
9
  for (unsigned i = 0; i != verdefCount; 
++i8
) {
1193
8
    auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef);
1194
8
    verdef += curVerdef->vd_next;
1195
8
    unsigned verdefIndex = curVerdef->vd_ndx;
1196
8
    verdefs.resize(verdefIndex + 1);
1197
8
    verdefs[verdefIndex] = curVerdef;
1198
8
  }
1199
1
  return verdefs;
1200
1
}
1201
1202
// We do not usually care about alignments of data in shared object
1203
// files because the loader takes care of it. However, if we promote a
1204
// DSO symbol to point to .bss due to copy relocation, we need to keep
1205
// the original alignment requirements. We infer it in this function.
1206
template <typename ELFT>
1207
static uint64_t getAlignment(ArrayRef<typename ELFT::Shdr> sections,
1208
904
                             const typename ELFT::Sym &sym) {
1209
904
  uint64_t ret = UINT64_MAX;
1210
904
  if (sym.st_value)
1211
832
    ret = 1ULL << countTrailingZeros((uint64_t)sym.st_value);
1212
904
  if (0 < sym.st_shndx && sym.st_shndx < sections.size())
1213
846
    ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign);
1214
904
  return (ret > UINT32_MAX) ? 
046
:
ret858
;
1215
904
}
InputFiles.cpp:unsigned long long getAlignment<llvm::object::ELFType<(llvm::support::endianness)1, false> >(llvm::ArrayRef<llvm::object::ELFType<(llvm::support::endianness)1, false>::Shdr>, llvm::object::ELFType<(llvm::support::endianness)1, false>::Sym const&)
Line
Count
Source
1208
133
                             const typename ELFT::Sym &sym) {
1209
133
  uint64_t ret = UINT64_MAX;
1210
133
  if (sym.st_value)
1211
124
    ret = 1ULL << countTrailingZeros((uint64_t)sym.st_value);
1212
133
  if (0 < sym.st_shndx && sym.st_shndx < sections.size())
1213
133
    ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign);
1214
133
  return (ret > UINT32_MAX) ? 
00
: ret;
1215
133
}
InputFiles.cpp:unsigned long long getAlignment<llvm::object::ELFType<(llvm::support::endianness)0, false> >(llvm::ArrayRef<llvm::object::ELFType<(llvm::support::endianness)0, false>::Shdr>, llvm::object::ELFType<(llvm::support::endianness)0, false>::Sym const&)
Line
Count
Source
1208
110
                             const typename ELFT::Sym &sym) {
1209
110
  uint64_t ret = UINT64_MAX;
1210
110
  if (sym.st_value)
1211
106
    ret = 1ULL << countTrailingZeros((uint64_t)sym.st_value);
1212
110
  if (0 < sym.st_shndx && sym.st_shndx < sections.size())
1213
108
    ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign);
1214
110
  return (ret > UINT32_MAX) ? 
01
:
ret109
;
1215
110
}
InputFiles.cpp:unsigned long long getAlignment<llvm::object::ELFType<(llvm::support::endianness)1, true> >(llvm::ArrayRef<llvm::object::ELFType<(llvm::support::endianness)1, true>::Shdr>, llvm::object::ELFType<(llvm::support::endianness)1, true>::Sym const&)
Line
Count
Source
1208
575
                             const typename ELFT::Sym &sym) {
1209
575
  uint64_t ret = UINT64_MAX;
1210
575
  if (sym.st_value)
1211
559
    ret = 1ULL << countTrailingZeros((uint64_t)sym.st_value);
1212
575
  if (0 < sym.st_shndx && sym.st_shndx < sections.size())
1213
560
    ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign);
1214
575
  return (ret > UINT32_MAX) ? 
04
:
ret571
;
1215
575
}
InputFiles.cpp:unsigned long long getAlignment<llvm::object::ELFType<(llvm::support::endianness)0, true> >(llvm::ArrayRef<llvm::object::ELFType<(llvm::support::endianness)0, true>::Shdr>, llvm::object::ELFType<(llvm::support::endianness)0, true>::Sym const&)
Line
Count
Source
1208
86
                             const typename ELFT::Sym &sym) {
1209
86
  uint64_t ret = UINT64_MAX;
1210
86
  if (sym.st_value)
1211
43
    ret = 1ULL << countTrailingZeros((uint64_t)sym.st_value);
1212
86
  if (0 < sym.st_shndx && sym.st_shndx < sections.size())
1213
45
    ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign);
1214
86
  return (ret > UINT32_MAX) ? 
041
:
ret45
;
1215
86
}
1216
1217
// Fully parse the shared object file.
1218
//
1219
// This function parses symbol versions. If a DSO has version information,
1220
// the file has a ".gnu.version_d" section which contains symbol version
1221
// definitions. Each symbol is associated to one version through a table in
1222
// ".gnu.version" section. That table is a parallel array for the symbol
1223
// table, and each table entry contains an index in ".gnu.version_d".
1224
//
1225
// The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for
1226
// VER_NDX_GLOBAL. There's no table entry for these special versions in
1227
// ".gnu.version_d".
1228
//
1229
// The file format for symbol versioning is perhaps a bit more complicated
1230
// than necessary, but you can easily understand the code if you wrap your
1231
// head around the data structure described above.
1232
407
template <class ELFT> void SharedFile::parse() {
1233
407
  using Elf_Dyn = typename ELFT::Dyn;
1234
407
  using Elf_Shdr = typename ELFT::Shdr;
1235
407
  using Elf_Sym = typename ELFT::Sym;
1236
407
  using Elf_Verdef = typename ELFT::Verdef;
1237
407
  using Elf_Versym = typename ELFT::Versym;
1238
407
1239
407
  ArrayRef<Elf_Dyn> dynamicTags;
1240
407
  const ELFFile<ELFT> obj = this->getObj<ELFT>();
1241
407
  ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
1242
407
1243
407
  const Elf_Shdr *versymSec = nullptr;
1244
407
  const Elf_Shdr *verdefSec = nullptr;
1245
407
1246
407
  // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
1247
4.84k
  for (const Elf_Shdr &sec : sections) {
1248
4.84k
    switch (sec.sh_type) {
1249
4.84k
    default:
1250
4.40k
      continue;
1251
4.84k
    case SHT_DYNAMIC:
1252
405
      dynamicTags =
1253
405
          CHECK(obj.template getSectionContentsAsArray<Elf_Dyn>(&sec), this);
1254
405
      break;
1255
4.84k
    case SHT_GNU_versym:
1256
17
      versymSec = &sec;
1257
17
      break;
1258
4.84k
    case SHT_GNU_verdef:
1259
16
      verdefSec = &sec;
1260
16
      break;
1261
4.84k
    }
1262
4.84k
  }
1263
407
1264
407
  if (versymSec && 
numELFSyms == 017
) {
1265
1
    error("SHT_GNU_versym should be associated with symbol table");
1266
1
    return;
1267
1
  }
1268
406
1269
406
  // Search for a DT_SONAME tag to initialize this->soName.
1270
3.37k
  
for (const Elf_Dyn &dyn : dynamicTags)406
{
1271
3.37k
    if (dyn.d_tag == DT_NEEDED) {
1272
7
      uint64_t val = dyn.getVal();
1273
7
      if (val >= this->stringTable.size())
1274
0
        fatal(toString(this) + ": invalid DT_NEEDED entry");
1275
7
      dtNeeded.push_back(this->stringTable.data() + val);
1276
3.36k
    } else if (dyn.d_tag == DT_SONAME) {
1277
83
      uint64_t val = dyn.getVal();
1278
83
      if (val >= this->stringTable.size())
1279
0
        fatal(toString(this) + ": invalid DT_SONAME entry");
1280
83
      soName = this->stringTable.data() + val;
1281
83
    }
1282
3.37k
  }
1283
406
1284
406
  // DSOs are uniquified not by filename but by soname.
1285
406
  DenseMap<StringRef, SharedFile *>::iterator it;
1286
406
  bool wasInserted;
1287
406
  std::tie(it, wasInserted) = symtab->soNames.try_emplace(soName, this);
1288
406
1289
406
  // If a DSO appears more than once on the command line with and without
1290
406
  // --as-needed, --no-as-needed takes precedence over --as-needed because a
1291
406
  // user can add an extra DSO with --no-as-needed to force it to be added to
1292
406
  // the dependency list.
1293
406
  it->second->isNeeded |= isNeeded;
1294
406
  if (!wasInserted)
1295
3
    return;
1296
403
1297
403
  sharedFiles.push_back(this);
1298
403
1299
403
  verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec);
1300
403
1301
403
  // Parse ".gnu.version" section which is a parallel array for the symbol
1302
403
  // table. If a given file doesn't have a ".gnu.version" section, we use
1303
403
  // VER_NDX_GLOBAL.
1304
403
  size_t size = numELFSyms - firstGlobal;
1305
403
  std::vector<uint32_t> versyms(size, VER_NDX_GLOBAL);
1306
403
  if (versymSec) {
1307
16
    ArrayRef<Elf_Versym> versym =
1308
16
        CHECK(obj.template getSectionContentsAsArray<Elf_Versym>(versymSec),
1309
16
              this)
1310
16
            .slice(firstGlobal);
1311
139
    for (size_t i = 0; i < size; 
++i123
)
1312
123
      versyms[i] = versym[i].vs_index;
1313
16
  }
1314
403
1315
403
  // System libraries can have a lot of symbols with versions. Using a
1316
403
  // fixed buffer for computing the versions name (foo@ver) can save a
1317
403
  // lot of allocations.
1318
403
  SmallString<0> versionedNameBuffer;
1319
403
1320
403
  // Add symbols to the symbol table.
1321
403
  ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>();
1322
1.36k
  for (size_t i = 0; i < syms.size(); 
++i957
) {
1323
957
    const Elf_Sym &sym = syms[i];
1324
957
1325
957
    // ELF spec requires that all local symbols precede weak or global
1326
957
    // symbols in each symbol table, and the index of first non-local symbol
1327
957
    // is stored to sh_info. If a local symbol appears after some non-local
1328
957
    // symbol, that's a violation of the spec.
1329
957
    StringRef name = CHECK(sym.getName(this->stringTable), this);
1330
957
    if (sym.getBinding() == STB_LOCAL) {
1331
3
      warn("found local symbol '" + name +
1332
3
           "' in global part of symbol table in file " + toString(this));
1333
3
      continue;
1334
3
    }
1335
954
1336
954
    if (sym.isUndefined()) {
1337
49
      Symbol *s = symtab->addSymbol(
1338
49
          Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()});
1339
49
      s->exportDynamic = true;
1340
49
      continue;
1341
49
    }
1342
905
1343
905
    // MIPS BFD linker puts _gp_disp symbol into DSO files and incorrectly
1344
905
    // assigns VER_NDX_LOCAL to this section global symbol. Here is a
1345
905
    // workaround for this bug.
1346
905
    uint32_t idx = versyms[i] & ~VERSYM_HIDDEN;
1347
905
    if (config->emachine == EM_MIPS && 
idx == VER_NDX_LOCAL179
&&
1348
905
        
name == "_gp_disp"2
)
1349
1
      continue;
1350
904
1351
904
    uint32_t alignment = getAlignment<ELFT>(sections, sym);
1352
904
    if (!(versyms[i] & VERSYM_HIDDEN)) {
1353
885
      symtab->addSymbol(SharedSymbol{*this, name, sym.getBinding(),
1354
885
                                     sym.st_other, sym.getType(), sym.st_value,
1355
885
                                     sym.st_size, alignment, idx});
1356
885
    }
1357
904
1358
904
    // Also add the symbol with the versioned name to handle undefined symbols
1359
904
    // with explicit versions.
1360
904
    if (idx == VER_NDX_GLOBAL)
1361
827
      continue;
1362
77
1363
77
    if (idx >= verdefs.size() || 
idx == VER_NDX_LOCAL61
) {
1364
17
      error("corrupt input file: version definition index " + Twine(idx) +
1365
17
            " for symbol " + name + " is out of bounds\n>>> defined in " +
1366
17
            toString(this));
1367
17
      continue;
1368
17
    }
1369
60
1370
60
    StringRef verName =
1371
60
        this->stringTable.data() +
1372
60
        reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name;
1373
60
    versionedNameBuffer.clear();
1374
60
    name = (name + "@" + verName).toStringRef(versionedNameBuffer);
1375
60
    symtab->addSymbol(SharedSymbol{*this, saver.save(name), sym.getBinding(),
1376
60
                                   sym.st_other, sym.getType(), sym.st_value,
1377
60
                                   sym.st_size, alignment, idx});
1378
60
  }
1379
403
}
void lld::elf::SharedFile::parse<llvm::object::ELFType<(llvm::support::endianness)1, false> >()
Line
Count
Source
1232
65
template <class ELFT> void SharedFile::parse() {
1233
65
  using Elf_Dyn = typename ELFT::Dyn;
1234
65
  using Elf_Shdr = typename ELFT::Shdr;
1235
65
  using Elf_Sym = typename ELFT::Sym;
1236
65
  using Elf_Verdef = typename ELFT::Verdef;
1237
65
  using Elf_Versym = typename ELFT::Versym;
1238
65
1239
65
  ArrayRef<Elf_Dyn> dynamicTags;
1240
65
  const ELFFile<ELFT> obj = this->getObj<ELFT>();
1241
65
  ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
1242
65
1243
65
  const Elf_Shdr *versymSec = nullptr;
1244
65
  const Elf_Shdr *verdefSec = nullptr;
1245
65
1246
65
  // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
1247
740
  for (const Elf_Shdr &sec : sections) {
1248
740
    switch (sec.sh_type) {
1249
740
    default:
1250
675
      continue;
1251
740
    case SHT_DYNAMIC:
1252
65
      dynamicTags =
1253
65
          CHECK(obj.template getSectionContentsAsArray<Elf_Dyn>(&sec), this);
1254
65
      break;
1255
740
    case SHT_GNU_versym:
1256
0
      versymSec = &sec;
1257
0
      break;
1258
740
    case SHT_GNU_verdef:
1259
0
      verdefSec = &sec;
1260
0
      break;
1261
740
    }
1262
740
  }
1263
65
1264
65
  if (versymSec && 
numELFSyms == 00
) {
1265
0
    error("SHT_GNU_versym should be associated with symbol table");
1266
0
    return;
1267
0
  }
1268
65
1269
65
  // Search for a DT_SONAME tag to initialize this->soName.
1270
494
  
for (const Elf_Dyn &dyn : dynamicTags)65
{
1271
494
    if (dyn.d_tag == DT_NEEDED) {
1272
0
      uint64_t val = dyn.getVal();
1273
0
      if (val >= this->stringTable.size())
1274
0
        fatal(toString(this) + ": invalid DT_NEEDED entry");
1275
0
      dtNeeded.push_back(this->stringTable.data() + val);
1276
494
    } else if (dyn.d_tag == DT_SONAME) {
1277
21
      uint64_t val = dyn.getVal();
1278
21
      if (val >= this->stringTable.size())
1279
0
        fatal(toString(this) + ": invalid DT_SONAME entry");
1280
21
      soName = this->stringTable.data() + val;
1281
21
    }
1282
494
  }
1283
65
1284
65
  // DSOs are uniquified not by filename but by soname.
1285
65
  DenseMap<StringRef, SharedFile *>::iterator it;
1286
65
  bool wasInserted;
1287
65
  std::tie(it, wasInserted) = symtab->soNames.try_emplace(soName, this);
1288
65
1289
65
  // If a DSO appears more than once on the command line with and without
1290
65
  // --as-needed, --no-as-needed takes precedence over --as-needed because a
1291
65
  // user can add an extra DSO with --no-as-needed to force it to be added to
1292
65
  // the dependency list.
1293
65
  it->second->isNeeded |= isNeeded;
1294
65
  if (!wasInserted)
1295
1
    return;
1296
64
1297
64
  sharedFiles.push_back(this);
1298
64
1299
64
  verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec);
1300
64
1301
64
  // Parse ".gnu.version" section which is a parallel array for the symbol
1302
64
  // table. If a given file doesn't have a ".gnu.version" section, we use
1303
64
  // VER_NDX_GLOBAL.
1304
64
  size_t size = numELFSyms - firstGlobal;
1305
64
  std::vector<uint32_t> versyms(size, VER_NDX_GLOBAL);
1306
64
  if (versymSec) {
1307
0
    ArrayRef<Elf_Versym> versym =
1308
0
        CHECK(obj.template getSectionContentsAsArray<Elf_Versym>(versymSec),
1309
0
              this)
1310
0
            .slice(firstGlobal);
1311
0
    for (size_t i = 0; i < size; ++i)
1312
0
      versyms[i] = versym[i].vs_index;
1313
0
  }
1314
64
1315
64
  // System libraries can have a lot of symbols with versions. Using a
1316
64
  // fixed buffer for computing the versions name (foo@ver) can save a
1317
64
  // lot of allocations.
1318
64
  SmallString<0> versionedNameBuffer;
1319
64
1320
64
  // Add symbols to the symbol table.
1321
64
  ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>();
1322
200
  for (size_t i = 0; i < syms.size(); 
++i136
) {
1323
136
    const Elf_Sym &sym = syms[i];
1324
136
1325
136
    // ELF spec requires that all local symbols precede weak or global
1326
136
    // symbols in each symbol table, and the index of first non-local symbol
1327
136
    // is stored to sh_info. If a local symbol appears after some non-local
1328
136
    // symbol, that's a violation of the spec.
1329
136
    StringRef name = CHECK(sym.getName(this->stringTable), this);
1330
136
    if (sym.getBinding() == STB_LOCAL) {
1331
0
      warn("found local symbol '" + name +
1332
0
           "' in global part of symbol table in file " + toString(this));
1333
0
      continue;
1334
0
    }
1335
136
1336
136
    if (sym.isUndefined()) {
1337
3
      Symbol *s = symtab->addSymbol(
1338
3
          Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()});
1339
3
      s->exportDynamic = true;
1340
3
      continue;
1341
3
    }
1342
133
1343
133
    // MIPS BFD linker puts _gp_disp symbol into DSO files and incorrectly
1344
133
    // assigns VER_NDX_LOCAL to this section global symbol. Here is a
1345
133
    // workaround for this bug.
1346
133
    uint32_t idx = versyms[i] & ~VERSYM_HIDDEN;
1347
133
    if (config->emachine == EM_MIPS && 
idx == VER_NDX_LOCAL4
&&
1348
133
        
name == "_gp_disp"0
)
1349
0
      continue;
1350
133
1351
133
    uint32_t alignment = getAlignment<ELFT>(sections, sym);
1352
133
    if (!(versyms[i] & VERSYM_HIDDEN)) {
1353
133
      symtab->addSymbol(SharedSymbol{*this, name, sym.getBinding(),
1354
133
                                     sym.st_other, sym.getType(), sym.st_value,
1355
133
                                     sym.st_size, alignment, idx});
1356
133
    }
1357
133
1358
133
    // Also add the symbol with the versioned name to handle undefined symbols
1359
133
    // with explicit versions.
1360
133
    if (idx == VER_NDX_GLOBAL)
1361
133
      continue;
1362
0
1363
0
    if (idx >= verdefs.size() || idx == VER_NDX_LOCAL) {
1364
0
      error("corrupt input file: version definition index " + Twine(idx) +
1365
0
            " for symbol " + name + " is out of bounds\n>>> defined in " +
1366
0
            toString(this));
1367
0
      continue;
1368
0
    }
1369
0
1370
0
    StringRef verName =
1371
0
        this->stringTable.data() +
1372
0
        reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name;
1373
0
    versionedNameBuffer.clear();
1374
0
    name = (name + "@" + verName).toStringRef(versionedNameBuffer);
1375
0
    symtab->addSymbol(SharedSymbol{*this, saver.save(name), sym.getBinding(),
1376
0
                                   sym.st_other, sym.getType(), sym.st_value,
1377
0
                                   sym.st_size, alignment, idx});
1378
0
  }
1379
64
}
void lld::elf::SharedFile::parse<llvm::object::ELFType<(llvm::support::endianness)0, false> >()
Line
Count
Source
1232
29
template <class ELFT> void SharedFile::parse() {
1233
29
  using Elf_Dyn = typename ELFT::Dyn;
1234
29
  using Elf_Shdr = typename ELFT::Shdr;
1235
29
  using Elf_Sym = typename ELFT::Sym;
1236
29
  using Elf_Verdef = typename ELFT::Verdef;
1237
29
  using Elf_Versym = typename ELFT::Versym;
1238
29
1239
29
  ArrayRef<Elf_Dyn> dynamicTags;
1240
29
  const ELFFile<ELFT> obj = this->getObj<ELFT>();
1241
29
  ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
1242
29
1243
29
  const Elf_Shdr *versymSec = nullptr;
1244
29
  const Elf_Shdr *verdefSec = nullptr;
1245
29
1246
29
  // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
1247
417
  for (const Elf_Shdr &sec : sections) {
1248
417
    switch (sec.sh_type) {
1249
417
    default:
1250
386
      continue;
1251
417
    case SHT_DYNAMIC:
1252
29
      dynamicTags =
1253
29
          CHECK(obj.template getSectionContentsAsArray<Elf_Dyn>(&sec), this);
1254
29
      break;
1255
417
    case SHT_GNU_versym:
1256
1
      versymSec = &sec;
1257
1
      break;
1258
417
    case SHT_GNU_verdef:
1259
1
      verdefSec = &sec;
1260
1
      break;
1261
417
    }
1262
417
  }
1263
29
1264
29
  if (versymSec && 
numELFSyms == 01
) {
1265
0
    error("SHT_GNU_versym should be associated with symbol table");
1266
0
    return;
1267
0
  }
1268
29
1269
29
  // Search for a DT_SONAME tag to initialize this->soName.
1270
365
  
for (const Elf_Dyn &dyn : dynamicTags)29
{
1271
365
    if (dyn.d_tag == DT_NEEDED) {
1272
0
      uint64_t val = dyn.getVal();
1273
0
      if (val >= this->stringTable.size())
1274
0
        fatal(toString(this) + ": invalid DT_NEEDED entry");
1275
0
      dtNeeded.push_back(this->stringTable.data() + val);
1276
365
    } else if (dyn.d_tag == DT_SONAME) {
1277
4
      uint64_t val = dyn.getVal();
1278
4
      if (val >= this->stringTable.size())
1279
0
        fatal(toString(this) + ": invalid DT_SONAME entry");
1280
4
      soName = this->stringTable.data() + val;
1281
4
    }
1282
365
  }
1283
29
1284
29
  // DSOs are uniquified not by filename but by soname.
1285
29
  DenseMap<StringRef, SharedFile *>::iterator it;
1286
29
  bool wasInserted;
1287
29
  std::tie(it, wasInserted) = symtab->soNames.try_emplace(soName, this);
1288
29
1289
29
  // If a DSO appears more than once on the command line with and without
1290
29
  // --as-needed, --no-as-needed takes precedence over --as-needed because a
1291
29
  // user can add an extra DSO with --no-as-needed to force it to be added to
1292
29
  // the dependency list.
1293
29
  it->second->isNeeded |= isNeeded;
1294
29
  if (!wasInserted)
1295
0
    return;
1296
29
1297
29
  sharedFiles.push_back(this);
1298
29
1299
29
  verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec);
1300
29
1301
29
  // Parse ".gnu.version" section which is a parallel array for the symbol
1302
29
  // table. If a given file doesn't have a ".gnu.version" section, we use
1303
29
  // VER_NDX_GLOBAL.
1304
29
  size_t size = numELFSyms - firstGlobal;
1305
29
  std::vector<uint32_t> versyms(size, VER_NDX_GLOBAL);
1306
29
  if (versymSec) {
1307
1
    ArrayRef<Elf_Versym> versym =
1308
1
        CHECK(obj.template getSectionContentsAsArray<Elf_Versym>(versymSec),
1309
1
              this)
1310
1
            .slice(firstGlobal);
1311
10
    for (size_t i = 0; i < size; 
++i9
)
1312
9
      versyms[i] = versym[i].vs_index;
1313
1
  }
1314
29
1315
29
  // System libraries can have a lot of symbols with versions. Using a
1316
29
  // fixed buffer for computing the versions name (foo@ver) can save a
1317
29
  // lot of allocations.
1318
29
  SmallString<0> versionedNameBuffer;
1319
29
1320
29
  // Add symbols to the symbol table.
1321
29
  ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>();
1322
140
  for (size_t i = 0; i < syms.size(); 
++i111
) {
1323
111
    const Elf_Sym &sym = syms[i];
1324
111
1325
111
    // ELF spec requires that all local symbols precede weak or global
1326
111
    // symbols in each symbol table, and the index of first non-local symbol
1327
111
    // is stored to sh_info. If a local symbol appears after some non-local
1328
111
    // symbol, that's a violation of the spec.
1329
111
    StringRef name = CHECK(sym.getName(this->stringTable), this);
1330
111
    if (sym.getBinding() == STB_LOCAL) {
1331
0
      warn("found local symbol '" + name +
1332
0
           "' in global part of symbol table in file " + toString(this));
1333
0
      continue;
1334
0
    }
1335
111
1336
111
    if (sym.isUndefined()) {
1337
0
      Symbol *s = symtab->addSymbol(
1338
0
          Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()});
1339
0
      s->exportDynamic = true;
1340
0
      continue;
1341
0
    }
1342
111
1343
111
    // MIPS BFD linker puts _gp_disp symbol into DSO files and incorrectly
1344
111
    // assigns VER_NDX_LOCAL to this section global symbol. Here is a
1345
111
    // workaround for this bug.
1346
111
    uint32_t idx = versyms[i] & ~VERSYM_HIDDEN;
1347
111
    if (config->emachine == EM_MIPS && 
idx == VER_NDX_LOCAL99
&&
1348
111
        
name == "_gp_disp"1
)
1349
1
      continue;
1350
110
1351
110
    uint32_t alignment = getAlignment<ELFT>(sections, sym);
1352
110
    if (!(versyms[i] & VERSYM_HIDDEN)) {
1353
110
      symtab->addSymbol(SharedSymbol{*this, name, sym.getBinding(),
1354
110
                                     sym.st_other, sym.getType(), sym.st_value,
1355
110
                                     sym.st_size, alignment, idx});
1356
110
    }
1357
110
1358
110
    // Also add the symbol with the versioned name to handle undefined symbols
1359
110
    // with explicit versions.
1360
110
    if (idx == VER_NDX_GLOBAL)
1361
108
      continue;
1362
2
1363
2
    if (idx >= verdefs.size() || idx == VER_NDX_LOCAL) {
1364
0
      error("corrupt input file: version definition index " + Twine(idx) +
1365
0
            " for symbol " + name + " is out of bounds\n>>> defined in " +
1366
0
            toString(this));
1367
0
      continue;
1368
0
    }
1369
2
1370
2
    StringRef verName =
1371
2
        this->stringTable.data() +
1372
2
        reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name;
1373
2
    versionedNameBuffer.clear();
1374
2
    name = (name + "@" + verName).toStringRef(versionedNameBuffer);
1375
2
    symtab->addSymbol(SharedSymbol{*this, saver.save(name), sym.getBinding(),
1376
2
                                   sym.st_other, sym.getType(), sym.st_value,
1377
2
                                   sym.st_size, alignment, idx});
1378
2
  }
1379
29
}
void lld::elf::SharedFile::parse<llvm::object::ELFType<(llvm::support::endianness)1, true> >()
Line
Count
Source
1232
298
template <class ELFT> void SharedFile::parse() {
1233
298
  using Elf_Dyn = typename ELFT::Dyn;
1234
298
  using Elf_Shdr = typename ELFT::Shdr;
1235
298
  using Elf_Sym = typename ELFT::Sym;
1236
298
  using Elf_Verdef = typename ELFT::Verdef;
1237
298
  using Elf_Versym = typename ELFT::Versym;
1238
298
1239
298
  ArrayRef<Elf_Dyn> dynamicTags;
1240
298
  const ELFFile<ELFT> obj = this->getObj<ELFT>();
1241
298
  ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
1242
298
1243
298
  const Elf_Shdr *versymSec = nullptr;
1244
298
  const Elf_Shdr *verdefSec = nullptr;
1245
298
1246
298
  // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
1247
3.46k
  for (const Elf_Shdr &sec : sections) {
1248
3.46k
    switch (sec.sh_type) {
1249
3.46k
    default:
1250
3.14k
      continue;
1251
3.46k
    case SHT_DYNAMIC:
1252
296
      dynamicTags =
1253
296
          CHECK(obj.template getSectionContentsAsArray<Elf_Dyn>(&sec), this);
1254
296
      break;
1255
3.46k
    case SHT_GNU_versym:
1256
15
      versymSec = &sec;
1257
15
      break;
1258
3.46k
    case SHT_GNU_verdef:
1259
14
      verdefSec = &sec;
1260
14
      break;
1261
3.46k
    }
1262
3.46k
  }
1263
298
1264
298
  if (versymSec && 
numELFSyms == 015
) {
1265
1
    error("SHT_GNU_versym should be associated with symbol table");
1266
1
    return;
1267
1
  }
1268
297
1269
297
  // Search for a DT_SONAME tag to initialize this->soName.
1270
2.35k
  
for (const Elf_Dyn &dyn : dynamicTags)297
{
1271
2.35k
    if (dyn.d_tag == DT_NEEDED) {
1272
5
      uint64_t val = dyn.getVal();
1273
5
      if (val >= this->stringTable.size())
1274
0
        fatal(toString(this) + ": invalid DT_NEEDED entry");
1275
5
      dtNeeded.push_back(this->stringTable.data() + val);
1276
2.34k
    } else if (dyn.d_tag == DT_SONAME) {
1277
56
      uint64_t val = dyn.getVal();
1278
56
      if (val >= this->stringTable.size())
1279
0
        fatal(toString(this) + ": invalid DT_SONAME entry");
1280
56
      soName = this->stringTable.data() + val;
1281
56
    }
1282
2.35k
  }
1283
297
1284
297
  // DSOs are uniquified not by filename but by soname.
1285
297
  DenseMap<StringRef, SharedFile *>::iterator it;
1286
297
  bool wasInserted;
1287
297
  std::tie(it, wasInserted) = symtab->soNames.try_emplace(soName, this);
1288
297
1289
297
  // If a DSO appears more than once on the command line with and without
1290
297
  // --as-needed, --no-as-needed takes precedence over --as-needed because a
1291
297
  // user can add an extra DSO with --no-as-needed to force it to be added to
1292
297
  // the dependency list.
1293
297
  it->second->isNeeded |= isNeeded;
1294
297
  if (!wasInserted)
1295
2
    return;
1296
295
1297
295
  sharedFiles.push_back(this);
1298
295
1299
295
  verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec);
1300
295
1301
295
  // Parse ".gnu.version" section which is a parallel array for the symbol
1302
295
  // table. If a given file doesn't have a ".gnu.version" section, we use
1303
295
  // VER_NDX_GLOBAL.
1304
295
  size_t size = numELFSyms - firstGlobal;
1305
295
  std::vector<uint32_t> versyms(size, VER_NDX_GLOBAL);
1306
295
  if (versymSec) {
1307
14
    ArrayRef<Elf_Versym> versym =
1308
14
        CHECK(obj.template getSectionContentsAsArray<Elf_Versym>(versymSec),
1309
14
              this)
1310
14
            .slice(firstGlobal);
1311
70
    for (size_t i = 0; i < size; 
++i56
)
1312
56
      versyms[i] = versym[i].vs_index;
1313
14
  }
1314
295
1315
295
  // System libraries can have a lot of symbols with versions. Using a
1316
295
  // fixed buffer for computing the versions name (foo@ver) can save a
1317
295
  // lot of allocations.
1318
295
  SmallString<0> versionedNameBuffer;
1319
295
1320
295
  // Add symbols to the symbol table.
1321
295
  ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>();
1322
919
  for (size_t i = 0; i < syms.size(); 
++i624
) {
1323
624
    const Elf_Sym &sym = syms[i];
1324
624
1325
624
    // ELF spec requires that all local symbols precede weak or global
1326
624
    // symbols in each symbol table, and the index of first non-local symbol
1327
624
    // is stored to sh_info. If a local symbol appears after some non-local
1328
624
    // symbol, that's a violation of the spec.
1329
624
    StringRef name = CHECK(sym.getName(this->stringTable), this);
1330
624
    if (sym.getBinding() == STB_LOCAL) {
1331
3
      warn("found local symbol '" + name +
1332
3
           "' in global part of symbol table in file " + toString(this));
1333
3
      continue;
1334
3
    }
1335
621
1336
621
    if (sym.isUndefined()) {
1337
46
      Symbol *s = symtab->addSymbol(
1338
46
          Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()});
1339
46
      s->exportDynamic = true;
1340
46
      continue;
1341
46
    }
1342
575
1343
575
    // MIPS BFD linker puts _gp_disp symbol into DSO files and incorrectly
1344
575
    // assigns VER_NDX_LOCAL to this section global symbol. Here is a
1345
575
    // workaround for this bug.
1346
575
    uint32_t idx = versyms[i] & ~VERSYM_HIDDEN;
1347
575
    if (config->emachine == EM_MIPS && 
idx == VER_NDX_LOCAL0
&&
1348
575
        
name == "_gp_disp"0
)
1349
0
      continue;
1350
575
1351
575
    uint32_t alignment = getAlignment<ELFT>(sections, sym);
1352
575
    if (!(versyms[i] & VERSYM_HIDDEN)) {
1353
556
      symtab->addSymbol(SharedSymbol{*this, name, sym.getBinding(),
1354
556
                                     sym.st_other, sym.getType(), sym.st_value,
1355
556
                                     sym.st_size, alignment, idx});
1356
556
    }
1357
575
1358
575
    // Also add the symbol with the versioned name to handle undefined symbols
1359
575
    // with explicit versions.
1360
575
    if (idx == VER_NDX_GLOBAL)
1361
534
      continue;
1362
41
1363
41
    if (idx >= verdefs.size() || idx == VER_NDX_LOCAL) {
1364
0
      error("corrupt input file: version definition index " + Twine(idx) +
1365
0
            " for symbol " + name + " is out of bounds\n>>> defined in " +
1366
0
            toString(this));
1367
0
      continue;
1368
0
    }
1369
41
1370
41
    StringRef verName =
1371
41
        this->stringTable.data() +
1372
41
        reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name;
1373
41
    versionedNameBuffer.clear();
1374
41
    name = (name + "@" + verName).toStringRef(versionedNameBuffer);
1375
41
    symtab->addSymbol(SharedSymbol{*this, saver.save(name), sym.getBinding(),
1376
41
                                   sym.st_other, sym.getType(), sym.st_value,
1377
41
                                   sym.st_size, alignment, idx});
1378
41
  }
1379
295
}
void lld::elf::SharedFile::parse<llvm::object::ELFType<(llvm::support::endianness)0, true> >()
Line
Count
Source
1232
15
template <class ELFT> void SharedFile::parse() {
1233
15
  using Elf_Dyn = typename ELFT::Dyn;
1234
15
  using Elf_Shdr = typename ELFT::Shdr;
1235
15
  using Elf_Sym = typename ELFT::Sym;
1236
15
  using Elf_Verdef = typename ELFT::Verdef;
1237
15
  using Elf_Versym = typename ELFT::Versym;
1238
15
1239
15
  ArrayRef<Elf_Dyn> dynamicTags;
1240
15
  const ELFFile<ELFT> obj = this->getObj<ELFT>();
1241
15
  ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
1242
15
1243
15
  const Elf_Shdr *versymSec = nullptr;
1244
15
  const Elf_Shdr *verdefSec = nullptr;
1245
15
1246
15
  // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
1247
218
  for (const Elf_Shdr &sec : sections) {
1248
218
    switch (sec.sh_type) {
1249
218
    default:
1250
201
      continue;
1251
218
    case SHT_DYNAMIC:
1252
15
      dynamicTags =
1253
15
          CHECK(obj.template getSectionContentsAsArray<Elf_Dyn>(&sec), this);
1254
15
      break;
1255
218
    case SHT_GNU_versym:
1256
1
      versymSec = &sec;
1257
1
      break;
1258
218
    case SHT_GNU_verdef:
1259
1
      verdefSec = &sec;
1260
1
      break;
1261
218
    }
1262
218
  }
1263
15
1264
15
  if (versymSec && 
numELFSyms == 01
) {
1265
0
    error("SHT_GNU_versym should be associated with symbol table");
1266
0
    return;
1267
0
  }
1268
15
1269
15
  // Search for a DT_SONAME tag to initialize this->soName.
1270
161
  
for (const Elf_Dyn &dyn : dynamicTags)15
{
1271
161
    if (dyn.d_tag == DT_NEEDED) {
1272
2
      uint64_t val = dyn.getVal();
1273
2
      if (val >= this->stringTable.size())
1274
0
        fatal(toString(this) + ": invalid DT_NEEDED entry");
1275
2
      dtNeeded.push_back(this->stringTable.data() + val);
1276
159
    } else if (dyn.d_tag == DT_SONAME) {
1277
2
      uint64_t val = dyn.getVal();
1278
2
      if (val >= this->stringTable.size())
1279
0
        fatal(toString(this) + ": invalid DT_SONAME entry");
1280
2
      soName = this->stringTable.data() + val;
1281
2
    }
1282
161
  }
1283
15
1284
15
  // DSOs are uniquified not by filename but by soname.
1285
15
  DenseMap<StringRef, SharedFile *>::iterator it;
1286
15
  bool wasInserted;
1287
15
  std::tie(it, wasInserted) = symtab->soNames.try_emplace(soName, this);
1288
15
1289
15
  // If a DSO appears more than once on the command line with and without
1290
15
  // --as-needed, --no-as-needed takes precedence over --as-needed because a
1291
15
  // user can add an extra DSO with --no-as-needed to force it to be added to
1292
15
  // the dependency list.
1293
15
  it->second->isNeeded |= isNeeded;
1294
15
  if (!wasInserted)
1295
0
    return;
1296
15
1297
15
  sharedFiles.push_back(this);
1298
15
1299
15
  verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec);
1300
15
1301
15
  // Parse ".gnu.version" section which is a parallel array for the symbol
1302
15
  // table. If a given file doesn't have a ".gnu.version" section, we use
1303
15
  // VER_NDX_GLOBAL.
1304
15
  size_t size = numELFSyms - firstGlobal;
1305
15
  std::vector<uint32_t> versyms(size, VER_NDX_GLOBAL);
1306
15
  if (versymSec) {
1307
1
    ArrayRef<Elf_Versym> versym =
1308
1
        CHECK(obj.template getSectionContentsAsArray<Elf_Versym>(versymSec),
1309
1
              this)
1310
1
            .slice(firstGlobal);
1311
59
    for (size_t i = 0; i < size; 
++i58
)
1312
58
      versyms[i] = versym[i].vs_index;
1313
1
  }
1314
15
1315
15
  // System libraries can have a lot of symbols with versions. Using a
1316
15
  // fixed buffer for computing the versions name (foo@ver) can save a
1317
15
  // lot of allocations.
1318
15
  SmallString<0> versionedNameBuffer;
1319
15
1320
15
  // Add symbols to the symbol table.
1321
15
  ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>();
1322
101
  for (size_t i = 0; i < syms.size(); 
++i86
) {
1323
86
    const Elf_Sym &sym = syms[i];
1324
86
1325
86
    // ELF spec requires that all local symbols precede weak or global
1326
86
    // symbols in each symbol table, and the index of first non-local symbol
1327
86
    // is stored to sh_info. If a local symbol appears after some non-local
1328
86
    // symbol, that's a violation of the spec.
1329
86
    StringRef name = CHECK(sym.getName(this->stringTable), this);
1330
86
    if (sym.getBinding() == STB_LOCAL) {
1331
0
      warn("found local symbol '" + name +
1332
0
           "' in global part of symbol table in file " + toString(this));
1333
0
      continue;
1334
0
    }
1335
86
1336
86
    if (sym.isUndefined()) {
1337
0
      Symbol *s = symtab->addSymbol(
1338
0
          Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()});
1339
0
      s->exportDynamic = true;
1340
0
      continue;
1341
0
    }
1342
86
1343
86
    // MIPS BFD linker puts _gp_disp symbol into DSO files and incorrectly
1344
86
    // assigns VER_NDX_LOCAL to this section global symbol. Here is a
1345
86
    // workaround for this bug.
1346
86
    uint32_t idx = versyms[i] & ~VERSYM_HIDDEN;
1347
86
    if (config->emachine == EM_MIPS && 
idx == VER_NDX_LOCAL76
&&
1348
86
        
name == "_gp_disp"1
)
1349
0
      continue;
1350
86
1351
86
    uint32_t alignment = getAlignment<ELFT>(sections, sym);
1352
86
    if (!(versyms[i] & VERSYM_HIDDEN)) {
1353
86
      symtab->addSymbol(SharedSymbol{*this, name, sym.getBinding(),
1354
86
                                     sym.st_other, sym.getType(), sym.st_value,
1355
86
                                     sym.st_size, alignment, idx});
1356
86
    }
1357
86
1358
86
    // Also add the symbol with the versioned name to handle undefined symbols
1359
86
    // with explicit versions.
1360
86
    if (idx == VER_NDX_GLOBAL)
1361
52
      continue;
1362
34
1363
34
    if (idx >= verdefs.size() || 
idx == VER_NDX_LOCAL18
) {
1364
17
      error("corrupt input file: version definition index " + Twine(idx) +
1365
17
            " for symbol " + name + " is out of bounds\n>>> defined in " +