Coverage Report

Created: 2019-05-22 02:55

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/COFF/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 "Chunks.h"
11
#include "Config.h"
12
#include "DebugTypes.h"
13
#include "Driver.h"
14
#include "SymbolTable.h"
15
#include "Symbols.h"
16
#include "lld/Common/ErrorHandler.h"
17
#include "lld/Common/Memory.h"
18
#include "llvm-c/lto.h"
19
#include "llvm/ADT/SmallVector.h"
20
#include "llvm/ADT/Triple.h"
21
#include "llvm/ADT/Twine.h"
22
#include "llvm/BinaryFormat/COFF.h"
23
#include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
24
#include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
25
#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
26
#include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
27
#include "llvm/Object/Binary.h"
28
#include "llvm/Object/COFF.h"
29
#include "llvm/Support/Casting.h"
30
#include "llvm/Support/Endian.h"
31
#include "llvm/Support/Error.h"
32
#include "llvm/Support/ErrorOr.h"
33
#include "llvm/Support/FileSystem.h"
34
#include "llvm/Support/Path.h"
35
#include "llvm/Target/TargetOptions.h"
36
#include <cstring>
37
#include <system_error>
38
#include <utility>
39
40
using namespace llvm;
41
using namespace llvm::COFF;
42
using namespace llvm::codeview;
43
using namespace llvm::object;
44
using namespace llvm::support::endian;
45
46
using llvm::Triple;
47
using llvm::support::ulittle32_t;
48
49
namespace lld {
50
namespace coff {
51
52
std::vector<ObjFile *> ObjFile::Instances;
53
std::vector<ImportFile *> ImportFile::Instances;
54
std::vector<BitcodeFile *> BitcodeFile::Instances;
55
56
/// Checks that Source is compatible with being a weak alias to Target.
57
/// If Source is Undefined and has no weak alias set, makes it a weak
58
/// alias to Target.
59
static void checkAndSetWeakAlias(SymbolTable *Symtab, InputFile *F,
60
7
                                 Symbol *Source, Symbol *Target) {
61
7
  if (auto *U = dyn_cast<Undefined>(Source)) {
62
7
    if (U->WeakAlias && 
U->WeakAlias != Target2
) {
63
2
      // Weak aliases as produced by GCC are named in the form
64
2
      // .weak.<weaksymbol>.<othersymbol>, where <othersymbol> is the name
65
2
      // of another symbol emitted near the weak symbol.
66
2
      // Just use the definition from the first object file that defined
67
2
      // this weak symbol.
68
2
      if (Config->MinGW)
69
2
        return;
70
0
      Symtab->reportDuplicate(Source, F);
71
0
    }
72
7
    U->WeakAlias = Target;
73
5
  }
74
7
}
75
76
48
ArchiveFile::ArchiveFile(MemoryBufferRef M) : InputFile(ArchiveKind, M) {}
77
78
48
void ArchiveFile::parse() {
79
48
  // Parse a MemoryBufferRef as an archive file.
80
48
  File = CHECK(Archive::create(MB), this);
81
48
82
48
  // Read the symbol table to construct Lazy objects.
83
48
  for (const Archive::Symbol &Sym : File->symbols())
84
253
    Symtab->addLazy(this, Sym);
85
48
}
86
87
// Returns a buffer pointing to a member file containing a given symbol.
88
75
void ArchiveFile::addMember(const Archive::Symbol *Sym) {
89
75
  const Archive::Child &C =
90
75
      CHECK(Sym->getMember(),
91
75
            "could not get the member for symbol " + Sym->getName());
92
75
93
75
  // Return an empty buffer if we have already returned the same buffer.
94
75
  if (!Seen.insert(C.getChildOffset()).second)
95
0
    return;
96
75
97
75
  Driver->enqueueArchiveMember(C, Sym->getName(), getName());
98
75
}
99
100
1
std::vector<MemoryBufferRef> getArchiveMembers(Archive *File) {
101
1
  std::vector<MemoryBufferRef> V;
102
1
  Error Err = Error::success();
103
1
  for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
104
1
    Archive::Child C =
105
1
        CHECK(COrErr,
106
1
              File->getFileName() + ": could not get the child of the archive");
107
1
    MemoryBufferRef MBRef =
108
1
        CHECK(C.getMemoryBufferRef(),
109
1
              File->getFileName() +
110
1
                  ": could not get the buffer for a child of the archive");
111
1
    V.push_back(MBRef);
112
1
  }
113
1
  if (Err)
114
0
    fatal(File->getFileName() +
115
0
          ": Archive::children failed: " + toString(std::move(Err)));
116
1
  return V;
117
1
}
118
119
383
void ObjFile::parse() {
120
383
  // Parse a memory buffer as a COFF file.
121
383
  std::unique_ptr<Binary> Bin = CHECK(createBinary(MB), this);
122
383
123
383
  if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
124
383
    Bin.release();
125
383
    COFFObj.reset(Obj);
126
383
  } else {
127
0
    fatal(toString(this) + " is not a COFF file");
128
0
  }
129
383
130
383
  // Read section and symbol tables.
131
383
  initializeChunks();
132
383
  initializeSymbols();
133
383
  initializeFlags();
134
383
  initializeDependencies();
135
383
}
136
137
2.74k
const coff_section* ObjFile::getSection(uint32_t I) {
138
2.74k
  const coff_section *Sec;
139
2.74k
  if (auto EC = COFFObj->getSection(I, Sec))
140
0
    fatal("getSection failed: #" + Twine(I) + ": " + EC.message());
141
2.74k
  return Sec;
142
2.74k
}
143
144
// We set SectionChunk pointers in the SparseChunks vector to this value
145
// temporarily to mark comdat sections as having an unknown resolution. As we
146
// walk the object file's symbol table, once we visit either a leader symbol or
147
// an associative section definition together with the parent comdat's leader,
148
// we set the pointer to either nullptr (to mark the section as discarded) or a
149
// valid SectionChunk for that section.
150
static SectionChunk *const PendingComdat = reinterpret_cast<SectionChunk *>(1);
151
152
383
void ObjFile::initializeChunks() {
153
383
  uint32_t NumSections = COFFObj->getNumberOfSections();
154
383
  Chunks.reserve(NumSections);
155
383
  SparseChunks.resize(NumSections + 1);
156
1.76k
  for (uint32_t I = 1; I < NumSections + 1; 
++I1.37k
) {
157
1.37k
    const coff_section *Sec = getSection(I);
158
1.37k
    if (Sec->Characteristics & IMAGE_SCN_LNK_COMDAT)
159
245
      SparseChunks[I] = PendingComdat;
160
1.13k
    else
161
1.13k
      SparseChunks[I] = readSection(I, nullptr, "");
162
1.37k
  }
163
383
}
164
165
SectionChunk *ObjFile::readSection(uint32_t SectionNumber,
166
                                   const coff_aux_section_definition *Def,
167
1.35k
                                   StringRef LeaderName) {
168
1.35k
  const coff_section *Sec = getSection(SectionNumber);
169
1.35k
170
1.35k
  StringRef Name;
171
1.35k
  if (Expected<StringRef> E = COFFObj->getSectionName(Sec))
172
1.35k
    Name = *E;
173
0
  else
174
0
    fatal("getSectionName failed: #" + Twine(SectionNumber) + ": " +
175
0
          toString(E.takeError()));
176
1.35k
177
1.35k
  if (Name == ".drectve") {
178
90
    ArrayRef<uint8_t> Data;
179
90
    cantFail(COFFObj->getSectionContents(Sec, Data));
180
90
    Directives = StringRef((const char *)Data.data(), Data.size());
181
90
    return nullptr;
182
90
  }
183
1.26k
184
1.26k
  if (Name == ".llvm_addrsig") {
185
1
    AddrsigSec = Sec;
186
1
    return nullptr;
187
1
  }
188
1.26k
189
1.26k
  // Object files may have DWARF debug info or MS CodeView debug info
190
1.26k
  // (or both).
191
1.26k
  //
192
1.26k
  // DWARF sections don't need any special handling from the perspective
193
1.26k
  // of the linker; they are just a data section containing relocations.
194
1.26k
  // We can just link them to complete debug info.
195
1.26k
  //
196
1.26k
  // CodeView needs linker support. We need to interpret debug info,
197
1.26k
  // and then write it to a separate .pdb file.
198
1.26k
199
1.26k
  // Ignore DWARF debug info unless /debug is given.
200
1.26k
  if (!Config->Debug && 
Name.startswith(".debug_")994
)
201
16
    return nullptr;
202
1.24k
203
1.24k
  if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
204
12
    return nullptr;
205
1.23k
  auto *C = make<SectionChunk>(this, Sec);
206
1.23k
  if (Def)
207
221
    C->Checksum = Def->CheckSum;
208
1.23k
209
1.23k
  // CodeView sections are stored to a different vector because they are not
210
1.23k
  // linked in the regular manner.
211
1.23k
  if (C->isCodeView())
212
103
    DebugChunks.push_back(C);
213
1.13k
  else if (Name == ".gfids$y")
214
8
    GuardFidChunks.push_back(C);
215
1.12k
  else if (Name == ".gljmp$y")
216
2
    GuardLJmpChunks.push_back(C);
217
1.12k
  else if (Name == ".sxdata")
218
2
    SXDataChunks.push_back(C);
219
1.12k
  else if (Config->TailMerge && 
Sec->NumberOfRelocations == 0895
&&
220
1.12k
           
Name == ".rdata"740
&&
LeaderName.startswith("??_C@")22
)
221
10
    // COFF sections that look like string literal sections (i.e. no
222
10
    // relocations, in .rdata, leader symbol name matches the MSVC name mangling
223
10
    // for string literals) are subject to string tail merging.
224
10
    MergeChunk::addSection(C);
225
1.11k
  else
226
1.11k
    Chunks.push_back(C);
227
1.23k
228
1.23k
  return C;
229
1.23k
}
230
231
void ObjFile::readAssociativeDefinition(
232
56
    COFFSymbolRef Sym, const coff_aux_section_definition *Def) {
233
56
  readAssociativeDefinition(Sym, Def, Def->getNumber(Sym.isBigObj()));
234
56
}
235
236
void ObjFile::readAssociativeDefinition(COFFSymbolRef Sym,
237
                                        const coff_aux_section_definition *Def,
238
58
                                        uint32_t ParentIndex) {
239
58
  SectionChunk *Parent = SparseChunks[ParentIndex];
240
58
  int32_t SectionNumber = Sym.getSectionNumber();
241
58
242
58
  auto Diag = [&]() {
243
1
    StringRef Name, ParentName;
244
1
    COFFObj->getSymbolName(Sym, Name);
245
1
246
1
    const coff_section *ParentSec = getSection(ParentIndex);
247
1
    if (Expected<StringRef> E = COFFObj->getSectionName(ParentSec))
248
1
      ParentName = *E;
249
1
    error(toString(this) + ": associative comdat " + Name + " (sec " +
250
1
          Twine(SectionNumber) + ") has invalid reference to section " +
251
1
          ParentName + " (sec " + Twine(ParentIndex) + ")");
252
1
  };
253
58
254
58
  if (Parent == PendingComdat) {
255
1
    // This can happen if an associative comdat refers to another associative
256
1
    // comdat that appears after it (invalid per COFF spec) or to a section
257
1
    // without any symbols.
258
1
    Diag();
259
1
    return;
260
1
  }
261
57
262
57
  // Check whether the parent is prevailing. If it is, so are we, and we read
263
57
  // the section; otherwise mark it as discarded.
264
57
  if (Parent) {
265
52
    SectionChunk *C = readSection(SectionNumber, Def, "");
266
52
    SparseChunks[SectionNumber] = C;
267
52
    if (C) {
268
52
      C->Selection = IMAGE_COMDAT_SELECT_ASSOCIATIVE;
269
52
      Parent->addAssociative(C);
270
52
    }
271
52
  } else {
272
5
    SparseChunks[SectionNumber] = nullptr;
273
5
  }
274
57
}
275
276
void ObjFile::recordPrevailingSymbolForMingw(
277
3
    COFFSymbolRef Sym, DenseMap<StringRef, uint32_t> &PrevailingSectionMap) {
278
3
  // For comdat symbols in executable sections, where this is the copy
279
3
  // of the section chunk we actually include instead of discarding it,
280
3
  // add the symbol to a map to allow using it for implicitly
281
3
  // associating .[px]data$<func> sections to it.
282
3
  int32_t SectionNumber = Sym.getSectionNumber();
283
3
  SectionChunk *SC = SparseChunks[SectionNumber];
284
3
  if (SC && SC->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE) {
285
1
    StringRef Name;
286
1
    COFFObj->getSymbolName(Sym, Name);
287
1
    PrevailingSectionMap[Name] = SectionNumber;
288
1
  }
289
3
}
290
291
void ObjFile::maybeAssociateSEHForMingw(
292
    COFFSymbolRef Sym, const coff_aux_section_definition *Def,
293
8
    const DenseMap<StringRef, uint32_t> &PrevailingSectionMap) {
294
8
  StringRef Name;
295
8
  COFFObj->getSymbolName(Sym, Name);
296
8
  if (Name.consume_front(".pdata$") || 
Name.consume_front(".xdata$")6
) {
297
4
    // For MinGW, treat .[px]data$<func> as implicitly associative to
298
4
    // the symbol <func>.
299
4
    auto ParentSym = PrevailingSectionMap.find(Name);
300
4
    if (ParentSym != PrevailingSectionMap.end())
301
2
      readAssociativeDefinition(Sym, Def, ParentSym->second);
302
4
  }
303
8
}
304
305
2.17k
Symbol *ObjFile::createRegular(COFFSymbolRef Sym) {
306
2.17k
  SectionChunk *SC = SparseChunks[Sym.getSectionNumber()];
307
2.17k
  if (Sym.isExternal()) {
308
490
    StringRef Name;
309
490
    COFFObj->getSymbolName(Sym, Name);
310
490
    if (SC)
311
489
      return Symtab->addRegular(this, Name, Sym.getGeneric(), SC);
312
1
    // For MinGW symbols named .weak.* that point to a discarded section,
313
1
    // don't create an Undefined symbol. If nothing ever refers to the symbol,
314
1
    // everything should be fine. If something actually refers to the symbol
315
1
    // (e.g. the undefined weak alias), linking will fail due to undefined
316
1
    // references at the end.
317
1
    if (Config->MinGW && Name.startswith(".weak."))
318
1
      return nullptr;
319
0
    return Symtab->addUndefined(Name, this, false);
320
0
  }
321
1.68k
  if (SC)
322
1.57k
    return make<DefinedRegular>(this, /*Name*/ "", /*IsCOMDAT*/ false,
323
1.57k
                                /*IsExternal*/ false, Sym.getGeneric(), SC);
324
107
  return nullptr;
325
107
}
326
327
383
void ObjFile::initializeSymbols() {
328
383
  uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
329
383
  Symbols.resize(NumSymbols);
330
383
331
383
  SmallVector<std::pair<Symbol *, uint32_t>, 8> WeakAliases;
332
383
  std::vector<uint32_t> PendingIndexes;
333
383
  PendingIndexes.reserve(NumSymbols);
334
383
335
383
  DenseMap<StringRef, uint32_t> PrevailingSectionMap;
336
383
  std::vector<const coff_aux_section_definition *> ComdatDefs(
337
383
      COFFObj->getNumberOfSections() + 1);
338
383
339
3.09k
  for (uint32_t I = 0; I < NumSymbols; 
++I2.71k
) {
340
2.71k
    COFFSymbolRef COFFSym = check(COFFObj->getSymbol(I));
341
2.71k
    bool PrevailingComdat;
342
2.71k
    if (COFFSym.isUndefined()) {
343
150
      Symbols[I] = createUndefined(COFFSym);
344
2.56k
    } else if (COFFSym.isWeakExternal()) {
345
6
      Symbols[I] = createUndefined(COFFSym);
346
6
      uint32_t TagIndex = COFFSym.getAux<coff_aux_weak_external>()->TagIndex;
347
6
      WeakAliases.emplace_back(Symbols[I], TagIndex);
348
2.55k
    } else if (Optional<Symbol *> OptSym =
349
2.29k
                   createDefined(COFFSym, ComdatDefs, PrevailingComdat)) {
350
2.29k
      Symbols[I] = *OptSym;
351
2.29k
      if (Config->MinGW && 
PrevailingComdat164
)
352
3
        recordPrevailingSymbolForMingw(COFFSym, PrevailingSectionMap);
353
2.29k
    } else {
354
261
      // createDefined() returns None if a symbol belongs to a section that
355
261
      // was pending at the point when the symbol was read. This can happen in
356
261
      // two cases:
357
261
      // 1) section definition symbol for a comdat leader;
358
261
      // 2) symbol belongs to a comdat section associated with another section.
359
261
      // In both of these cases, we can expect the section to be resolved by
360
261
      // the time we finish visiting the remaining symbols in the symbol
361
261
      // table. So we postpone the handling of this symbol until that time.
362
261
      PendingIndexes.push_back(I);
363
261
    }
364
2.71k
    I += COFFSym.getNumberOfAuxSymbols();
365
2.71k
  }
366
383
367
383
  for (uint32_t I : PendingIndexes) {
368
261
    COFFSymbolRef Sym = check(COFFObj->getSymbol(I));
369
261
    if (const coff_aux_section_definition *Def = Sym.getSectionDefinition()) {
370
245
      if (Def->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
371
56
        readAssociativeDefinition(Sym, Def);
372
189
      else if (Config->MinGW)
373
8
        maybeAssociateSEHForMingw(Sym, Def, PrevailingSectionMap);
374
245
    }
375
261
    if (SparseChunks[Sym.getSectionNumber()] == PendingComdat) {
376
4
      StringRef Name;
377
4
      COFFObj->getSymbolName(Sym, Name);
378
4
      log("comdat section " + Name +
379
4
          " without leader and unassociated, discarding");
380
4
      continue;
381
4
    }
382
257
    Symbols[I] = createRegular(Sym);
383
257
  }
384
383
385
383
  for (auto &KV : WeakAliases) {
386
6
    Symbol *Sym = KV.first;
387
6
    uint32_t Idx = KV.second;
388
6
    checkAndSetWeakAlias(Symtab, this, Sym, Symbols[Idx]);
389
6
  }
390
383
}
391
392
156
Symbol *ObjFile::createUndefined(COFFSymbolRef Sym) {
393
156
  StringRef Name;
394
156
  COFFObj->getSymbolName(Sym, Name);
395
156
  return Symtab->addUndefined(Name, this, Sym.isWeakExternal());
396
156
}
397
398
void ObjFile::handleComdatSelection(COFFSymbolRef Sym, COMDATType &Selection,
399
173
                                    bool &Prevailing, DefinedRegular *Leader) {
400
173
  if (Prevailing)
401
152
    return;
402
21
  // There's already an existing comdat for this symbol: `Leader`.
403
21
  // Use the comdats's selection field to determine if the new
404
21
  // symbol in `Sym` should be discarded, produce a duplicate symbol
405
21
  // error, etc.
406
21
407
21
  SectionChunk *LeaderChunk = nullptr;
408
21
  COMDATType LeaderSelection = IMAGE_COMDAT_SELECT_ANY;
409
21
410
21
  if (Leader->Data) {
411
21
    LeaderChunk = Leader->getChunk();
412
21
    LeaderSelection = LeaderChunk->Selection;
413
21
  } else {
414
0
    // FIXME: comdats from LTO files don't know their selection; treat them
415
0
    // as "any".
416
0
    Selection = LeaderSelection;
417
0
  }
418
21
419
21
  if ((Selection == IMAGE_COMDAT_SELECT_ANY &&
420
21
       
LeaderSelection == IMAGE_COMDAT_SELECT_LARGEST7
) ||
421
21
      
(20
Selection == IMAGE_COMDAT_SELECT_LARGEST20
&&
422
20
       
LeaderSelection == IMAGE_COMDAT_SELECT_ANY8
)) {
423
2
    // cl.exe picks "any" for vftables when building with /GR- and
424
2
    // "largest" when building with /GR. To be able to link object files
425
2
    // compiled with each flag, "any" and "largest" are merged as "largest".
426
2
    LeaderSelection = Selection = IMAGE_COMDAT_SELECT_LARGEST;
427
2
  }
428
21
429
21
  // Other than that, comdat selections must match.  This is a bit more
430
21
  // strict than link.exe which allows merging "any" and "largest" if "any"
431
21
  // is the first symbol the linker sees, and it allows merging "largest"
432
21
  // with everything (!) if "largest" is the first symbol the linker sees.
433
21
  // Making this symmetric independent of which selection is seen first
434
21
  // seems better though.
435
21
  // (This behavior matches ModuleLinker::getComdatResult().)
436
21
  if (Selection != LeaderSelection) {
437
1
    log(("conflicting comdat type for " + toString(*Leader) + ": " +
438
1
         Twine((int)LeaderSelection) + " in " + toString(Leader->getFile()) +
439
1
         " and " + Twine((int)Selection) + " in " + toString(this))
440
1
            .str());
441
1
    Symtab->reportDuplicate(Leader, this);
442
1
    return;
443
1
  }
444
20
445
20
  switch (Selection) {
446
20
  case IMAGE_COMDAT_SELECT_NODUPLICATES:
447
1
    Symtab->reportDuplicate(Leader, this);
448
1
    break;
449
20
450
20
  case IMAGE_COMDAT_SELECT_ANY:
451
6
    // Nothing to do.
452
6
    break;
453
20
454
20
  case IMAGE_COMDAT_SELECT_SAME_SIZE:
455
1
    if (LeaderChunk->getSize() != getSection(Sym)->SizeOfRawData)
456
1
      Symtab->reportDuplicate(Leader, this);
457
1
    break;
458
20
459
20
  case IMAGE_COMDAT_SELECT_EXACT_MATCH: {
460
3
    SectionChunk NewChunk(this, getSection(Sym));
461
3
    // link.exe only compares section contents here and doesn't complain
462
3
    // if the two comdat sections have e.g. different alignment.
463
3
    // Match that.
464
3
    if (LeaderChunk->getContents() != NewChunk.getContents())
465
2
      Symtab->reportDuplicate(Leader, this);
466
3
    break;
467
20
  }
468
20
469
20
  case IMAGE_COMDAT_SELECT_ASSOCIATIVE:
470
0
    // createDefined() is never called for IMAGE_COMDAT_SELECT_ASSOCIATIVE.
471
0
    // (This means lld-link doesn't produce duplicate symbol errors for
472
0
    // associative comdats while link.exe does, but associate comdats
473
0
    // are never extern in practice.)
474
0
    llvm_unreachable("createDefined not called for associative comdats");
475
20
476
20
  case IMAGE_COMDAT_SELECT_LARGEST:
477
9
    if (LeaderChunk->getSize() < getSection(Sym)->SizeOfRawData) {
478
5
      // Replace the existing comdat symbol with the new one.
479
5
      StringRef Name;
480
5
      COFFObj->getSymbolName(Sym, Name);
481
5
      // FIXME: This is incorrect: With /opt:noref, the previous sections
482
5
      // make it into the final executable as well. Correct handling would
483
5
      // be to undo reading of the whole old section that's being replaced,
484
5
      // or doing one pass that determines what the final largest comdat
485
5
      // is for all IMAGE_COMDAT_SELECT_LARGEST comdats and then reading
486
5
      // only the largest one.
487
5
      replaceSymbol<DefinedRegular>(Leader, this, Name, /*IsCOMDAT*/ true,
488
5
                                    /*IsExternal*/ true, Sym.getGeneric(),
489
5
                                    nullptr);
490
5
      Prevailing = true;
491
5
    }
492
9
    break;
493
20
494
20
  case IMAGE_COMDAT_SELECT_NEWEST:
495
0
    llvm_unreachable("should have been rejected earlier");
496
20
  }
497
20
}
498
499
Optional<Symbol *> ObjFile::createDefined(
500
    COFFSymbolRef Sym,
501
    std::vector<const coff_aux_section_definition *> &ComdatDefs,
502
2.55k
    bool &Prevailing) {
503
2.55k
  Prevailing = false;
504
2.55k
  auto GetName = [&]() {
505
491
    StringRef S;
506
491
    COFFObj->getSymbolName(Sym, S);
507
491
    return S;
508
491
  };
509
2.55k
510
2.55k
  if (Sym.isCommon()) {
511
11
    auto *C = make<CommonChunk>(Sym);
512
11
    Chunks.push_back(C);
513
11
    return Symtab->addCommon(this, GetName(), Sym.getValue(), Sym.getGeneric(),
514
11
                             C);
515
11
  }
516
2.54k
517
2.54k
  if (Sym.isAbsolute()) {
518
138
    StringRef Name = GetName();
519
138
520
138
    // Skip special symbols.
521
138
    if (Name == "@comp.id")
522
36
      return nullptr;
523
102
    if (Name == "@feat.00") {
524
98
      Feat00Flags = Sym.getValue();
525
98
      return nullptr;
526
98
    }
527
4
528
4
    if (Sym.isExternal())
529
4
      return Symtab->addAbsolute(Name, Sym);
530
0
    return make<DefinedAbsolute>(Name, Sym);
531
0
  }
532
2.40k
533
2.40k
  int32_t SectionNumber = Sym.getSectionNumber();
534
2.40k
  if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
535
47
    return nullptr;
536
2.36k
537
2.36k
  if (llvm::COFF::isReservedSectionNumber(SectionNumber))
538
0
    fatal(toString(this) + ": " + GetName() +
539
0
          " should not refer to special section " + Twine(SectionNumber));
540
2.36k
541
2.36k
  if ((uint32_t)SectionNumber >= SparseChunks.size())
542
0
    fatal(toString(this) + ": " + GetName() +
543
0
          " should not refer to non-existent section " + Twine(SectionNumber));
544
2.36k
545
2.36k
  // Comdat handling.
546
2.36k
  // A comdat symbol consists of two symbol table entries.
547
2.36k
  // The first symbol entry has the name of the section (e.g. .text), fixed
548
2.36k
  // values for the other fields, and one auxilliary record.
549
2.36k
  // The second symbol entry has the name of the comdat symbol, called the
550
2.36k
  // "comdat leader".
551
2.36k
  // When this function is called for the first symbol entry of a comdat,
552
2.36k
  // it sets ComdatDefs and returns None, and when it's called for the second
553
2.36k
  // symbol entry it reads ComdatDefs and then sets it back to nullptr.
554
2.36k
555
2.36k
  // Handle comdat leader.
556
2.36k
  if (const coff_aux_section_definition *Def = ComdatDefs[SectionNumber]) {
557
185
    ComdatDefs[SectionNumber] = nullptr;
558
185
    DefinedRegular *Leader;
559
185
560
185
    if (Sym.isExternal()) {
561
173
      std::tie(Leader, Prevailing) =
562
173
          Symtab->addComdat(this, GetName(), Sym.getGeneric());
563
173
    } else {
564
12
      Leader = make<DefinedRegular>(this, /*Name*/ "", /*IsCOMDAT*/ false,
565
12
                                    /*IsExternal*/ false, Sym.getGeneric());
566
12
      Prevailing = true;
567
12
    }
568
185
569
185
    if (Def->Selection < (int)IMAGE_COMDAT_SELECT_NODUPLICATES ||
570
185
        // Intentionally ends at IMAGE_COMDAT_SELECT_LARGEST: link.exe
571
185
        // doesn't understand IMAGE_COMDAT_SELECT_NEWEST either.
572
185
        Def->Selection > (int)IMAGE_COMDAT_SELECT_LARGEST) {
573
0
      fatal("unknown comdat type " + std::to_string((int)Def->Selection) +
574
0
            " for " + GetName() + " in " + toString(this));
575
0
    }
576
185
    COMDATType Selection = (COMDATType)Def->Selection;
577
185
578
185
    if (Leader->isCOMDAT())
579
173
      handleComdatSelection(Sym, Selection, Prevailing, Leader);
580
185
581
185
    if (Prevailing) {
582
169
      SectionChunk *C = readSection(SectionNumber, Def, GetName());
583
169
      SparseChunks[SectionNumber] = C;
584
169
      C->Sym = cast<DefinedRegular>(Leader);
585
169
      C->Selection = Selection;
586
169
      cast<DefinedRegular>(Leader)->Data = &C->Repl;
587
169
    } else {
588
16
      SparseChunks[SectionNumber] = nullptr;
589
16
    }
590
185
    return Leader;
591
185
  }
592
2.17k
593
2.17k
  // Prepare to handle the comdat leader symbol by setting the section's
594
2.17k
  // ComdatDefs pointer if we encounter a non-associative comdat.
595
2.17k
  if (SparseChunks[SectionNumber] == PendingComdat) {
596
261
    if (const coff_aux_section_definition *Def = Sym.getSectionDefinition()) {
597
245
      if (Def->Selection != IMAGE_COMDAT_SELECT_ASSOCIATIVE)
598
189
        ComdatDefs[SectionNumber] = Def;
599
245
    }
600
261
    return None;
601
261
  }
602
1.91k
603
1.91k
  return createRegular(Sym);
604
1.91k
}
605
606
349
MachineTypes ObjFile::getMachineType() {
607
349
  if (COFFObj)
608
349
    return static_cast<MachineTypes>(COFFObj->getMachine());
609
0
  return IMAGE_FILE_MACHINE_UNKNOWN;
610
0
}
611
612
509
ArrayRef<uint8_t> ObjFile::getDebugSection(StringRef SecName) {
613
509
  if (SectionChunk *Sec = SectionChunk::findByName(DebugChunks, SecName))
614
77
    return Sec->consumeDebugMagic();
615
432
  return {};
616
432
}
617
618
// OBJ files systematically store critical informations in a .debug$S stream,
619
// even if the TU was compiled with no debug info. At least two records are
620
// always there. S_OBJNAME stores a 32-bit signature, which is loaded into the
621
// PCHSignature member. S_COMPILE3 stores compile-time cmd-line flags. This is
622
// currently used to initialize the HotPatchable member.
623
383
void ObjFile::initializeFlags() {
624
383
  ArrayRef<uint8_t> Data = getDebugSection(".debug$S");
625
383
  if (Data.empty())
626
335
    return;
627
48
628
48
  DebugSubsectionArray Subsections;
629
48
630
48
  BinaryStreamReader Reader(Data, support::little);
631
48
  ExitOnError ExitOnErr;
632
48
  ExitOnErr(Reader.readArray(Subsections, Data.size()));
633
48
634
175
  for (const DebugSubsectionRecord &SS : Subsections) {
635
175
    if (SS.kind() != DebugSubsectionKind::Symbols)
636
78
      continue;
637
97
638
97
    unsigned Offset = 0;
639
97
640
97
    // Only parse the first two records. We are only looking for S_OBJNAME
641
97
    // and S_COMPILE3, and they usually appear at the beginning of the
642
97
    // stream.
643
258
    for (unsigned I = 0; I < 2; 
++I161
) {
644
194
      Expected<CVSymbol> Sym = readSymbolFromStream(SS.getRecordData(), Offset);
645
194
      if (!Sym) {
646
33
        consumeError(Sym.takeError());
647
33
        return;
648
33
      }
649
161
      if (Sym->kind() == SymbolKind::S_COMPILE3) {
650
43
        auto CS =
651
43
            cantFail(SymbolDeserializer::deserializeAs<Compile3Sym>(Sym.get()));
652
43
        HotPatchable =
653
43
            (CS.Flags & CompileSym3Flags::HotPatch) != CompileSym3Flags::None;
654
43
      }
655
161
      if (Sym->kind() == SymbolKind::S_OBJNAME) {
656
32
        auto ObjName = cantFail(SymbolDeserializer::deserializeAs<ObjNameSym>(
657
32
            Sym.get()));
658
32
        PCHSignature = ObjName.Signature;
659
32
      }
660
161
      Offset += Sym->length();
661
161
    }
662
97
  }
663
48
}
664
665
// Depending on the compilation flags, OBJs can refer to external files,
666
// necessary to merge this OBJ into the final PDB. We currently support two
667
// types of external files: Precomp/PCH OBJs, when compiling with /Yc and /Yu.
668
// And PDB type servers, when compiling with /Zi. This function extracts these
669
// dependencies and makes them available as a TpiSource interface (see
670
// DebugTypes.h).
671
383
void ObjFile::initializeDependencies() {
672
383
  if (!Config->Debug)
673
319
    return;
674
64
675
64
  bool IsPCH = false;
676
64
677
64
  ArrayRef<uint8_t> Data = getDebugSection(".debug$P");
678
64
  if (!Data.empty())
679
2
    IsPCH = true;
680
62
  else
681
62
    Data = getDebugSection(".debug$T");
682
64
683
64
  if (Data.empty())
684
36
    return;
685
28
686
28
  CVTypeArray Types;
687
28
  BinaryStreamReader Reader(Data, support::little);
688
28
  cantFail(Reader.readArray(Types, Reader.getLength()));
689
28
690
28
  CVTypeArray::Iterator FirstType = Types.begin();
691
28
  if (FirstType == Types.end())
692
0
    return;
693
28
694
28
  DebugTypes.emplace(Types);
695
28
696
28
  if (IsPCH) {
697
2
    DebugTypesObj = makePrecompSource(this);
698
2
    return;
699
2
  }
700
26
701
26
  if (FirstType->kind() == LF_TYPESERVER2) {
702
2
    TypeServer2Record TS = cantFail(
703
2
        TypeDeserializer::deserializeAs<TypeServer2Record>(FirstType->data()));
704
2
    DebugTypesObj = makeUseTypeServerSource(this, &TS);
705
2
    return;
706
2
  }
707
24
708
24
  if (FirstType->kind() == LF_PRECOMP) {
709
4
    PrecompRecord Precomp = cantFail(
710
4
        TypeDeserializer::deserializeAs<PrecompRecord>(FirstType->data()));
711
4
    DebugTypesObj = makeUsePrecompSource(this, &Precomp);
712
4
    return;
713
4
  }
714
20
715
20
  DebugTypesObj = makeTpiSource(this);
716
20
}
717
718
17
StringRef ltrim1(StringRef S, const char *Chars) {
719
17
  if (!S.empty() && strchr(Chars, S[0]))
720
17
    return S.substr(1);
721
0
  return S;
722
0
}
723
724
57
void ImportFile::parse() {
725
57
  const char *Buf = MB.getBufferStart();
726
57
  const char *End = MB.getBufferEnd();
727
57
  const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
728
57
729
57
  // Check if the total size is valid.
730
57
  if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData))
731
0
    fatal("broken import library");
732
57
733
57
  // Read names and create an __imp_ symbol.
734
57
  StringRef Name = Saver.save(StringRef(Buf + sizeof(*Hdr)));
735
57
  StringRef ImpName = Saver.save("__imp_" + Name);
736
57
  const char *NameStart = Buf + sizeof(coff_import_header) + Name.size() + 1;
737
57
  DLLName = StringRef(NameStart);
738
57
  StringRef ExtName;
739
57
  switch (Hdr->getNameType()) {
740
57
  case IMPORT_ORDINAL:
741
6
    ExtName = "";
742
6
    break;
743
57
  case IMPORT_NAME:
744
34
    ExtName = Name;
745
34
    break;
746
57
  case IMPORT_NAME_NOPREFIX:
747
1
    ExtName = ltrim1(Name, "?@_");
748
1
    break;
749
57
  case IMPORT_NAME_UNDECORATE:
750
16
    ExtName = ltrim1(Name, "?@_");
751
16
    ExtName = ExtName.substr(0, ExtName.find('@'));
752
16
    break;
753
57
  }
754
57
755
57
  this->Hdr = Hdr;
756
57
  ExternalName = ExtName;
757
57
758
57
  ImpSym = Symtab->addImportData(ImpName, this);
759
57
  // If this was a duplicate, we logged an error but may continue;
760
57
  // in this case, ImpSym is nullptr.
761
57
  if (!ImpSym)
762
1
    return;
763
56
764
56
  if (Hdr->getType() == llvm::COFF::IMPORT_CONST)
765
1
    static_cast<void>(Symtab->addImportData(Name, this));
766
56
767
56
  // If type is function, we need to create a thunk which jump to an
768
56
  // address pointed by the __imp_ symbol. (This allows you to call
769
56
  // DLL functions just like regular non-DLL functions.)
770
56
  if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
771
51
    ThunkSym = Symtab->addImportThunk(
772
51
        Name, cast_or_null<DefinedImportData>(ImpSym), Hdr->Machine);
773
56
}
774
775
BitcodeFile::BitcodeFile(MemoryBufferRef MB, StringRef ArchiveName,
776
                         uint64_t OffsetInArchive)
777
34
    : InputFile(BitcodeKind, MB) {
778
34
  std::string Path = MB.getBufferIdentifier().str();
779
34
780
34
  // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
781
34
  // name. If two archives define two members with the same name, this
782
34
  // causes a collision which result in only one of the objects being taken
783
34
  // into consideration at LTO time (which very likely causes undefined
784
34
  // symbols later in the link stage). So we append file offset to make
785
34
  // filename unique.
786
34
  MemoryBufferRef MBRef(
787
34
      MB.getBuffer(),
788
34
      Saver.save(ArchiveName + Path +
789
34
                 (ArchiveName.empty() ? 
""27
:
utostr(OffsetInArchive)7
)));
790
34
791
34
  Obj = check(lto::InputFile::create(MBRef));
792
34
}
793
794
34
void BitcodeFile::parse() {
795
34
  std::vector<std::pair<Symbol *, bool>> Comdat(Obj->getComdatTable().size());
796
44
  for (size_t I = 0; I != Obj->getComdatTable().size(); 
++I10
)
797
10
    // FIXME: lto::InputFile doesn't keep enough data to do correct comdat
798
10
    // selection handling.
799
10
    Comdat[I] = Symtab->addComdat(this, Saver.save(Obj->getComdatTable()[I]));
800
59
  for (const lto::InputFile::Symbol &ObjSym : Obj->symbols()) {
801
59
    StringRef SymName = Saver.save(ObjSym.getName());
802
59
    int ComdatIndex = ObjSym.getComdatIndex();
803
59
    Symbol *Sym;
804
59
    if (ObjSym.isUndefined()) {
805
9
      Sym = Symtab->addUndefined(SymName, this, false);
806
50
    } else if (ObjSym.isCommon()) {
807
0
      Sym = Symtab->addCommon(this, SymName, ObjSym.getCommonSize());
808
50
    } else if (ObjSym.isWeak() && 
ObjSym.isIndirect()9
) {
809
1
      // Weak external.
810
1
      Sym = Symtab->addUndefined(SymName, this, true);
811
1
      std::string Fallback = ObjSym.getCOFFWeakExternalFallback();
812
1
      Symbol *Alias = Symtab->addUndefined(Saver.save(Fallback));
813
1
      checkAndSetWeakAlias(Symtab, this, Sym, Alias);
814
49
    } else if (ComdatIndex != -1) {
815
10
      if (SymName == Obj->getComdatTable()[ComdatIndex])
816
10
        Sym = Comdat[ComdatIndex].first;
817
0
      else if (Comdat[ComdatIndex].second)
818
0
        Sym = Symtab->addRegular(this, SymName);
819
0
      else
820
0
        Sym = Symtab->addUndefined(SymName, this, false);
821
39
    } else {
822
39
      Sym = Symtab->addRegular(this, SymName);
823
39
    }
824
59
    Symbols.push_back(Sym);
825
59
    if (ObjSym.isUsed())
826
1
      Config->GCRoot.push_back(Sym);
827
59
  }
828
34
  Directives = Obj->getCOFFLinkerOpts();
829
34
}
830
831
34
MachineTypes BitcodeFile::getMachineType() {
832
34
  switch (Triple(Obj->getTargetTriple()).getArch()) {
833
34
  case Triple::x86_64:
834
33
    return AMD64;
835
34
  case Triple::x86:
836
1
    return I386;
837
34
  case Triple::arm:
838
0
    return ARMNT;
839
34
  case Triple::aarch64:
840
0
    return ARM64;
841
34
  default:
842
0
    return IMAGE_FILE_MACHINE_UNKNOWN;
843
34
  }
844
34
}
845
} // namespace coff
846
} // namespace lld
847
848
// Returns the last element of a path, which is supposed to be a filename.
849
82
static StringRef getBasename(StringRef Path) {
850
82
  return sys::path::filename(Path, sys::path::Style::windows);
851
82
}
852
853
// Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
854
647
std::string lld::toString(const coff::InputFile *File) {
855
647
  if (!File)
856
0
    return "<internal>";
857
647
  if (File->ParentName.empty() || 
File->kind() == coff::InputFile::ImportKind99
)
858
606
    return File->getName();
859
41
860
41
  return (getBasename(File->ParentName) + "(" + getBasename(File->getName()) +
861
41
          ")")
862
41
      .str();
863
41
}