Coverage Report

Created: 2017-10-03 07:32

/Users/buildslave/jenkins/sharedspace/clang-stage2-coverage-R@2/llvm/tools/lld/COFF/InputFiles.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- InputFiles.cpp -----------------------------------------------------===//
2
//
3
//                             The LLVM Linker
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
10
#include "InputFiles.h"
11
#include "Chunks.h"
12
#include "Config.h"
13
#include "Driver.h"
14
#include "Error.h"
15
#include "Memory.h"
16
#include "SymbolTable.h"
17
#include "Symbols.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/Object/Binary.h"
24
#include "llvm/Object/COFF.h"
25
#include "llvm/Support/Casting.h"
26
#include "llvm/Support/Endian.h"
27
#include "llvm/Support/Error.h"
28
#include "llvm/Support/ErrorOr.h"
29
#include "llvm/Support/FileSystem.h"
30
#include "llvm/Target/TargetOptions.h"
31
#include <cstring>
32
#include <system_error>
33
#include <utility>
34
35
using namespace llvm;
36
using namespace llvm::COFF;
37
using namespace llvm::object;
38
using namespace llvm::support::endian;
39
40
using llvm::Triple;
41
using llvm::support::ulittle32_t;
42
43
namespace lld {
44
namespace coff {
45
46
std::vector<ObjFile *> ObjFile::Instances;
47
std::vector<ImportFile *> ImportFile::Instances;
48
std::vector<BitcodeFile *> BitcodeFile::Instances;
49
50
/// Checks that Source is compatible with being a weak alias to Target.
51
/// If Source is Undefined and has no weak alias set, makes it a weak
52
/// alias to Target.
53
static void checkAndSetWeakAlias(SymbolTable *Symtab, InputFile *F,
54
7
                                 SymbolBody *Source, SymbolBody *Target) {
55
7
  if (auto *
U7
= dyn_cast<Undefined>(Source)) {
56
6
    if (
U->WeakAlias && 6
U->WeakAlias != Target0
)
57
0
      Symtab->reportDuplicate(Source->symbol(), F);
58
6
    U->WeakAlias = Target;
59
6
  }
60
7
}
61
62
55
ArchiveFile::ArchiveFile(MemoryBufferRef M) : InputFile(ArchiveKind, M) {}
63
64
55
void ArchiveFile::parse() {
65
55
  // Parse a MemoryBufferRef as an archive file.
66
55
  File = check(Archive::create(MB), toString(this));
67
55
68
55
  // Read the symbol table to construct Lazy objects.
69
55
  for (const Archive::Symbol &Sym : File->symbols())
70
295
    Symtab->addLazy(this, Sym);
71
55
}
72
73
// Returns a buffer pointing to a member file containing a given symbol.
74
87
void ArchiveFile::addMember(const Archive::Symbol *Sym) {
75
87
  const Archive::Child &C =
76
87
      check(Sym->getMember(),
77
87
            "could not get the member for symbol " + Sym->getName());
78
87
79
87
  // Return an empty buffer if we have already returned the same buffer.
80
87
  if (!Seen.insert(C.getChildOffset()).second)
81
0
    return;
82
87
83
87
  Driver->enqueueArchiveMember(C, Sym->getName(), getName());
84
87
}
85
86
2
std::vector<MemoryBufferRef> getArchiveMembers(Archive *File) {
87
2
  std::vector<MemoryBufferRef> V;
88
2
  Error Err = Error::success();
89
2
  for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
90
2
    Archive::Child C =
91
2
        check(COrErr,
92
2
              File->getFileName() + ": could not get the child of the archive");
93
2
    MemoryBufferRef MBRef =
94
2
        check(C.getMemoryBufferRef(),
95
2
              File->getFileName() +
96
2
                  ": could not get the buffer for a child of the archive");
97
2
    V.push_back(MBRef);
98
2
  }
99
2
  if (Err)
100
0
    fatal(File->getFileName() +
101
0
          ": Archive::children failed: " + toString(std::move(Err)));
102
2
  return V;
103
2
}
104
105
318
void ObjFile::parse() {
106
318
  // Parse a memory buffer as a COFF file.
107
318
  std::unique_ptr<Binary> Bin = check(createBinary(MB), toString(this));
108
318
109
318
  if (auto *
Obj318
= dyn_cast<COFFObjectFile>(Bin.get())) {
110
318
    Bin.release();
111
318
    COFFObj.reset(Obj);
112
318
  } else {
113
0
    fatal(toString(this) + " is not a COFF file");
114
0
  }
115
318
116
318
  // Read section and symbol tables.
117
318
  initializeChunks();
118
318
  initializeSymbols();
119
318
  initializeSEH();
120
318
}
121
122
318
void ObjFile::initializeChunks() {
123
318
  uint32_t NumSections = COFFObj->getNumberOfSections();
124
318
  Chunks.reserve(NumSections);
125
318
  SparseChunks.resize(NumSections + 1);
126
1.24k
  for (uint32_t I = 1; 
I < NumSections + 11.24k
;
++I922
) {
127
922
    const coff_section *Sec;
128
922
    StringRef Name;
129
922
    if (auto EC = COFFObj->getSection(I, Sec))
130
0
      fatal(EC, "getSection failed: #" + Twine(I));
131
922
    
if (auto 922
EC922
= COFFObj->getSectionName(Sec, Name))
132
0
      fatal(EC, "getSectionName failed: #" + Twine(I));
133
922
    
if (922
Name == ".sxdata"922
) {
134
3
      SXData = Sec;
135
3
      continue;
136
3
    }
137
919
    
if (919
Name == ".drectve"919
) {
138
79
      ArrayRef<uint8_t> Data;
139
79
      COFFObj->getSectionContents(Sec, Data);
140
79
      Directives = std::string((const char *)Data.data(), Data.size());
141
79
      continue;
142
79
    }
143
840
144
840
    // Object files may have DWARF debug info or MS CodeView debug info
145
840
    // (or both).
146
840
    //
147
840
    // DWARF sections don't need any special handling from the perspective
148
840
    // of the linker; they are just a data section containing relocations.
149
840
    // We can just link them to complete debug info.
150
840
    //
151
840
    // CodeView needs a linker support. We need to interpret and debug
152
840
    // info, and then write it to a separate .pdb file.
153
840
154
840
    // Ignore debug info unless /debug is given.
155
840
    
if (840
!Config->Debug && 840
Name.startswith(".debug")607
)
156
19
      continue;
157
821
158
821
    
if (821
Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE821
)
159
0
      continue;
160
821
    auto *C = make<SectionChunk>(this, Sec);
161
821
162
821
    // CodeView sections are stored to a different vector because they are not
163
821
    // linked in the regular manner.
164
821
    if (C->isCodeView())
165
72
      DebugChunks.push_back(C);
166
821
    else
167
749
      Chunks.push_back(C);
168
922
169
922
    SparseChunks[I] = C;
170
922
  }
171
318
}
172
173
318
void ObjFile::initializeSymbols() {
174
318
  uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
175
318
  SymbolBodies.reserve(NumSymbols);
176
318
  SparseSymbolBodies.resize(NumSymbols);
177
318
178
318
  SmallVector<std::pair<SymbolBody *, uint32_t>, 8> WeakAliases;
179
318
  int32_t LastSectionNumber = 0;
180
318
181
2.07k
  for (uint32_t I = 0; 
I < NumSymbols2.07k
;
++I1.75k
) {
182
1.75k
    // Get a COFFSymbolRef object.
183
1.75k
    ErrorOr<COFFSymbolRef> SymOrErr = COFFObj->getSymbol(I);
184
1.75k
    if (!SymOrErr)
185
0
      fatal(SymOrErr.getError(), "broken object file: " + toString(this));
186
1.75k
    COFFSymbolRef Sym = *SymOrErr;
187
1.75k
188
1.75k
    const void *AuxP = nullptr;
189
1.75k
    if (Sym.getNumberOfAuxSymbols())
190
882
      AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
191
1.75k
    bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
192
1.75k
193
1.75k
    SymbolBody *Body = nullptr;
194
1.75k
    if (
Sym.isUndefined()1.75k
) {
195
130
      Body = createUndefined(Sym);
196
1.75k
    } else 
if (1.62k
Sym.isWeakExternal()1.62k
) {
197
5
      Body = createUndefined(Sym);
198
5
      uint32_t TagIndex =
199
5
          static_cast<const coff_aux_weak_external *>(AuxP)->TagIndex;
200
5
      WeakAliases.emplace_back(Body, TagIndex);
201
1.62k
    } else {
202
1.62k
      Body = createDefined(Sym, AuxP, IsFirst);
203
1.62k
    }
204
1.75k
    if (
Body1.75k
) {
205
1.59k
      SymbolBodies.push_back(Body);
206
1.59k
      SparseSymbolBodies[I] = Body;
207
1.59k
    }
208
1.75k
    I += Sym.getNumberOfAuxSymbols();
209
1.75k
    LastSectionNumber = Sym.getSectionNumber();
210
1.75k
  }
211
318
212
318
  
for (auto &KV : WeakAliases) 318
{
213
5
    SymbolBody *Sym = KV.first;
214
5
    uint32_t Idx = KV.second;
215
5
    checkAndSetWeakAlias(Symtab, this, Sym, SparseSymbolBodies[Idx]);
216
5
  }
217
318
}
218
219
135
SymbolBody *ObjFile::createUndefined(COFFSymbolRef Sym) {
220
135
  StringRef Name;
221
135
  COFFObj->getSymbolName(Sym, Name);
222
135
  return Symtab->addUndefined(Name, this, Sym.isWeakExternal())->body();
223
135
}
224
225
SymbolBody *ObjFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
226
1.62k
                                   bool IsFirst) {
227
1.62k
  StringRef Name;
228
1.62k
  if (
Sym.isCommon()1.62k
) {
229
10
    auto *C = make<CommonChunk>(Sym);
230
10
    Chunks.push_back(C);
231
10
    COFFObj->getSymbolName(Sym, Name);
232
10
    Symbol *S =
233
10
        Symtab->addCommon(this, Name, Sym.getValue(), Sym.getGeneric(), C);
234
10
    return S->body();
235
10
  }
236
1.61k
  
if (1.61k
Sym.isAbsolute()1.61k
) {
237
109
    COFFObj->getSymbolName(Sym, Name);
238
109
    // Skip special symbols.
239
109
    if (Name == "@comp.id")
240
47
      return nullptr;
241
62
    // COFF spec 5.10.1. The .sxdata section.
242
62
    
if (62
Name == "@feat.00"62
) {
243
54
      if (Sym.getValue() & 1)
244
18
        SEHCompat = true;
245
54
      return nullptr;
246
54
    }
247
8
    
if (8
Sym.isExternal()8
)
248
6
      return Symtab->addAbsolute(Name, Sym)->body();
249
8
    else
250
2
      return make<DefinedAbsolute>(Name, Sym);
251
1.50k
  }
252
1.50k
  int32_t SectionNumber = Sym.getSectionNumber();
253
1.50k
  if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
254
1
    return nullptr;
255
1.50k
256
1.50k
  // Reserved sections numbers don't have contents.
257
1.50k
  
if (1.50k
llvm::COFF::isReservedSectionNumber(SectionNumber)1.50k
)
258
0
    fatal("broken object file: " + toString(this));
259
1.50k
260
1.50k
  // This symbol references a section which is not present in the section
261
1.50k
  // header.
262
1.50k
  
if (1.50k
(uint32_t)SectionNumber >= SparseChunks.size()1.50k
)
263
0
    fatal("broken object file: " + toString(this));
264
1.50k
265
1.50k
  // Nothing else to do without a section chunk.
266
1.50k
  auto *SC = cast_or_null<SectionChunk>(SparseChunks[SectionNumber]);
267
1.50k
  if (!SC)
268
66
    return nullptr;
269
1.43k
270
1.43k
  // Handle section definitions
271
1.43k
  
if (1.43k
IsFirst && 1.43k
AuxP1.08k
) {
272
805
    auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
273
805
    if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
274
14
      
if (auto *14
ParentSC14
= cast_or_null<SectionChunk>(
275
14
              SparseChunks[Aux->getNumber(Sym.isBigObj())])) {
276
14
        ParentSC->addAssociative(SC);
277
14
        // If we already discarded the parent, discard the child.
278
14
        if (ParentSC->isDiscarded())
279
0
          SC->markDiscarded();
280
14
      }
281
805
    SC->Checksum = Aux->CheckSum;
282
805
  }
283
1.43k
284
1.43k
  DefinedRegular *B;
285
1.43k
  if (
Sym.isExternal()1.43k
) {
286
500
    COFFObj->getSymbolName(Sym, Name);
287
500
    Symbol *S =
288
500
        Symtab->addRegular(this, Name, SC->isCOMDAT(), Sym.getGeneric(), SC);
289
500
    B = cast<DefinedRegular>(S->body());
290
500
  } else
291
938
    B = make<DefinedRegular>(this, /*Name*/ "", SC->isCOMDAT(),
292
938
                             /*IsExternal*/ false, Sym.getGeneric(), SC);
293
1.43k
  if (
SC->isCOMDAT() && 1.43k
Sym.getValue() == 0148
&&
!AuxP148
)
294
70
    SC->setSymbol(B);
295
1.62k
296
1.62k
  return B;
297
1.62k
}
298
299
318
void ObjFile::initializeSEH() {
300
318
  if (
!SEHCompat || 318
!SXData18
)
301
315
    return;
302
3
  ArrayRef<uint8_t> A;
303
3
  COFFObj->getSectionContents(SXData, A);
304
3
  if (A.size() % 4 != 0)
305
0
    fatal(".sxdata must be an array of symbol table indices");
306
3
  auto *I = reinterpret_cast<const ulittle32_t *>(A.data());
307
3
  auto *E = reinterpret_cast<const ulittle32_t *>(A.data() + A.size());
308
7
  for (; 
I != E7
;
++I4
)
309
4
    SEHandlers.insert(SparseSymbolBodies[*I]);
310
318
}
311
312
275
MachineTypes ObjFile::getMachineType() {
313
275
  if (COFFObj)
314
275
    return static_cast<MachineTypes>(COFFObj->getMachine());
315
0
  return IMAGE_FILE_MACHINE_UNKNOWN;
316
0
}
317
318
15
StringRef ltrim1(StringRef S, const char *Chars) {
319
15
  if (
!S.empty() && 15
strchr(Chars, S[0])15
)
320
15
    return S.substr(1);
321
0
  return S;
322
0
}
323
324
66
void ImportFile::parse() {
325
66
  const char *Buf = MB.getBufferStart();
326
66
  const char *End = MB.getBufferEnd();
327
66
  const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
328
66
329
66
  // Check if the total size is valid.
330
66
  if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData))
331
0
    fatal("broken import library");
332
66
333
66
  // Read names and create an __imp_ symbol.
334
66
  StringRef Name = Saver.save(StringRef(Buf + sizeof(*Hdr)));
335
66
  StringRef ImpName = Saver.save("__imp_" + Name);
336
66
  const char *NameStart = Buf + sizeof(coff_import_header) + Name.size() + 1;
337
66
  DLLName = StringRef(NameStart);
338
66
  StringRef ExtName;
339
66
  switch (Hdr->getNameType()) {
340
8
  case IMPORT_ORDINAL:
341
8
    ExtName = "";
342
8
    break;
343
43
  case IMPORT_NAME:
344
43
    ExtName = Name;
345
43
    break;
346
2
  case IMPORT_NAME_NOPREFIX:
347
2
    ExtName = ltrim1(Name, "?@_");
348
2
    break;
349
13
  case IMPORT_NAME_UNDECORATE:
350
13
    ExtName = ltrim1(Name, "?@_");
351
13
    ExtName = ExtName.substr(0, ExtName.find('@'));
352
13
    break;
353
66
  }
354
66
355
66
  this->Hdr = Hdr;
356
66
  ExternalName = ExtName;
357
66
358
66
  ImpSym = Symtab->addImportData(ImpName, this);
359
66
360
66
  if (Hdr->getType() == llvm::COFF::IMPORT_CONST)
361
1
    static_cast<void>(Symtab->addImportData(Name, this));
362
66
363
66
  // If type is function, we need to create a thunk which jump to an
364
66
  // address pointed by the __imp_ symbol. (This allows you to call
365
66
  // DLL functions just like regular non-DLL functions.)
366
66
  if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
367
64
    ThunkSym = Symtab->addImportThunk(Name, ImpSym, Hdr->Machine);
368
66
}
369
370
49
void BitcodeFile::parse() {
371
49
  Obj = check(lto::InputFile::create(MemoryBufferRef(
372
49
      MB.getBuffer(), Saver.save(ParentName + MB.getBufferIdentifier()))));
373
101
  for (const lto::InputFile::Symbol &ObjSym : Obj->symbols()) {
374
101
    StringRef SymName = Saver.save(ObjSym.getName());
375
101
    Symbol *Sym;
376
101
    if (
ObjSym.isUndefined()101
) {
377
21
      Sym = Symtab->addUndefined(SymName, this, false);
378
101
    } else 
if (80
ObjSym.isCommon()80
) {
379
0
      Sym = Symtab->addCommon(this, SymName, ObjSym.getCommonSize());
380
80
    } else 
if (80
ObjSym.isWeak() && 80
ObjSym.isIndirect()17
) {
381
2
      // Weak external.
382
2
      Sym = Symtab->addUndefined(SymName, this, true);
383
2
      std::string Fallback = ObjSym.getCOFFWeakExternalFallback();
384
2
      SymbolBody *Alias = Symtab->addUndefined(Saver.save(Fallback));
385
2
      checkAndSetWeakAlias(Symtab, this, Sym->body(), Alias);
386
80
    } else {
387
78
      bool IsCOMDAT = ObjSym.getComdatIndex() != -1;
388
78
      Sym = Symtab->addRegular(this, SymName, IsCOMDAT);
389
78
    }
390
101
    SymbolBodies.push_back(Sym->body());
391
101
  }
392
49
  Directives = Obj->getCOFFLinkerOpts();
393
49
}
394
395
49
MachineTypes BitcodeFile::getMachineType() {
396
49
  switch (Triple(Obj->getTargetTriple()).getArch()) {
397
48
  case Triple::x86_64:
398
48
    return AMD64;
399
1
  case Triple::x86:
400
1
    return I386;
401
0
  case Triple::arm:
402
0
    return ARMNT;
403
0
  case Triple::aarch64:
404
0
    return ARM64;
405
0
  default:
406
0
    return IMAGE_FILE_MACHINE_UNKNOWN;
407
0
  }
408
0
}
409
} // namespace coff
410
} // namespace lld
411
412
// Returns the last element of a path, which is supposed to be a filename.
413
132
static StringRef getBasename(StringRef Path) {
414
132
  size_t Pos = Path.find_last_of("\\/");
415
132
  if (Pos == StringRef::npos)
416
69
    return Path;
417
63
  return Path.substr(Pos + 1);
418
63
}
419
420
// Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
421
923
std::string lld::toString(coff::InputFile *File) {
422
923
  if (!File)
423
0
    return "(internal)";
424
923
  
if (923
File->ParentName.empty()923
)
425
857
    return File->getName().lower();
426
66
427
66
  std::string Res =
428
66
      (getBasename(File->ParentName) + "(" + getBasename(File->getName()) + ")")
429
66
          .str();
430
66
  return StringRef(Res).lower();
431
66
}