Coverage Report

Created: 2018-01-17 17:22

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/COFF/Writer.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- Writer.cpp ---------------------------------------------------------===//
2
//
3
//                             The LLVM Linker
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
10
#include "Writer.h"
11
#include "Config.h"
12
#include "DLL.h"
13
#include "InputFiles.h"
14
#include "MapFile.h"
15
#include "PDB.h"
16
#include "SymbolTable.h"
17
#include "Symbols.h"
18
#include "lld/Common/ErrorHandler.h"
19
#include "lld/Common/Memory.h"
20
#include "lld/Common/Timer.h"
21
#include "llvm/ADT/DenseMap.h"
22
#include "llvm/ADT/STLExtras.h"
23
#include "llvm/ADT/StringSwitch.h"
24
#include "llvm/Support/BinaryStreamReader.h"
25
#include "llvm/Support/Debug.h"
26
#include "llvm/Support/Endian.h"
27
#include "llvm/Support/FileOutputBuffer.h"
28
#include "llvm/Support/Parallel.h"
29
#include "llvm/Support/RandomNumberGenerator.h"
30
#include <algorithm>
31
#include <cstdio>
32
#include <map>
33
#include <memory>
34
#include <utility>
35
36
using namespace llvm;
37
using namespace llvm::COFF;
38
using namespace llvm::object;
39
using namespace llvm::support;
40
using namespace llvm::support::endian;
41
using namespace lld;
42
using namespace lld::coff;
43
44
static const int SectorSize = 512;
45
static const int DOSStubSize = 64;
46
static const int NumberfOfDataDirectory = 16;
47
48
namespace {
49
50
class DebugDirectoryChunk : public Chunk {
51
public:
52
0
  DebugDirectoryChunk(const std::vector<Chunk *> &R) : Records(R) {}
53
54
0
  size_t getSize() const override {
55
0
    return Records.size() * sizeof(debug_directory);
56
0
  }
57
58
0
  void writeTo(uint8_t *B) const override {
59
0
    auto *D = reinterpret_cast<debug_directory *>(B + OutputSectionOff);
60
0
61
0
    for (const Chunk *Record : Records) {
62
0
      D->Characteristics = 0;
63
0
      D->TimeDateStamp = 0;
64
0
      D->MajorVersion = 0;
65
0
      D->MinorVersion = 0;
66
0
      D->Type = COFF::IMAGE_DEBUG_TYPE_CODEVIEW;
67
0
      D->SizeOfData = Record->getSize();
68
0
      D->AddressOfRawData = Record->getRVA();
69
0
      OutputSection *OS = Record->getOutputSection();
70
0
      uint64_t Offs = OS->getFileOff() + (Record->getRVA() - OS->getRVA());
71
0
      D->PointerToRawData = Offs;
72
0
73
0
      ++D;
74
0
    }
75
0
  }
76
77
private:
78
  const std::vector<Chunk *> &Records;
79
};
80
81
class CVDebugRecordChunk : public Chunk {
82
public:
83
0
  CVDebugRecordChunk() {
84
0
    PDBAbsPath = Config->PDBPath;
85
0
    if (!PDBAbsPath.empty())
86
0
      llvm::sys::fs::make_absolute(PDBAbsPath);
87
0
  }
88
89
0
  size_t getSize() const override {
90
0
    return sizeof(codeview::DebugInfo) + PDBAbsPath.size() + 1;
91
0
  }
92
93
0
  void writeTo(uint8_t *B) const override {
94
0
    // Save off the DebugInfo entry to backfill the file signature (build id)
95
0
    // in Writer::writeBuildId
96
0
    BuildId = reinterpret_cast<codeview::DebugInfo *>(B + OutputSectionOff);
97
0
98
0
    // variable sized field (PDB Path)
99
0
    char *P = reinterpret_cast<char *>(B + OutputSectionOff + sizeof(*BuildId));
100
0
    if (!PDBAbsPath.empty())
101
0
      memcpy(P, PDBAbsPath.data(), PDBAbsPath.size());
102
0
    P[PDBAbsPath.size()] = '\0';
103
0
  }
104
105
  SmallString<128> PDBAbsPath;
106
  mutable codeview::DebugInfo *BuildId = nullptr;
107
};
108
109
// The writer writes a SymbolTable result to a file.
110
class Writer {
111
public:
112
0
  Writer() : Buffer(errorHandler().OutputBuffer) {}
113
  void run();
114
115
private:
116
  void createSections();
117
  void createMiscChunks();
118
  void createImportTables();
119
  void createExportTable();
120
  void assignAddresses();
121
  void removeEmptySections();
122
  void createSymbolAndStringTable();
123
  void openFile(StringRef OutputPath);
124
  template <typename PEHeaderTy> void writeHeader();
125
  void createSEHTable(OutputSection *RData);
126
  void setSectionPermissions();
127
  void writeSections();
128
  void writeBuildId();
129
  void sortExceptionTable();
130
131
  llvm::Optional<coff_symbol16> createSymbol(Defined *D);
132
  size_t addEntryToStringTable(StringRef Str);
133
134
  OutputSection *findSection(StringRef Name);
135
  OutputSection *createSection(StringRef Name);
136
  void addBaserels(OutputSection *Dest);
137
  void addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V);
138
139
  uint32_t getSizeOfInitializedData();
140
  std::map<StringRef, std::vector<DefinedImportData *>> binImports();
141
142
  std::unique_ptr<FileOutputBuffer> &Buffer;
143
  std::vector<OutputSection *> OutputSections;
144
  std::vector<char> Strtab;
145
  std::vector<llvm::object::coff_symbol16> OutputSymtab;
146
  IdataContents Idata;
147
  DelayLoadContents DelayIdata;
148
  EdataContents Edata;
149
  SEHTableChunk *SEHTable = nullptr;
150
151
  Chunk *DebugDirectory = nullptr;
152
  std::vector<Chunk *> DebugRecords;
153
  CVDebugRecordChunk *BuildId = nullptr;
154
  Optional<codeview::DebugInfo> PreviousBuildId;
155
  ArrayRef<uint8_t> SectionTable;
156
157
  uint64_t FileSize;
158
  uint32_t PointerToSymbolTable = 0;
159
  uint64_t SizeOfImage;
160
  uint64_t SizeOfHeaders;
161
};
162
} // anonymous namespace
163
164
namespace lld {
165
namespace coff {
166
167
static Timer CodeLayoutTimer("Code Layout", Timer::root());
168
static Timer DiskCommitTimer("Commit Output File", Timer::root());
169
170
0
void writeResult() { Writer().run(); }
171
172
0
void OutputSection::setRVA(uint64_t RVA) {
173
0
  Header.VirtualAddress = RVA;
174
0
  for (Chunk *C : Chunks)
175
0
    C->setRVA(C->getRVA() + RVA);
176
0
}
177
178
0
void OutputSection::setFileOffset(uint64_t Off) {
179
0
  // If a section has no actual data (i.e. BSS section), we want to
180
0
  // set 0 to its PointerToRawData. Otherwise the output is rejected
181
0
  // by the loader.
182
0
  if (Header.SizeOfRawData == 0)
183
0
    return;
184
0
185
0
  // It is possible that this assignment could cause an overflow of the u32,
186
0
  // but that should be caught by the FileSize check in OutputSection::run().
187
0
  Header.PointerToRawData = Off;
188
0
}
189
190
0
void OutputSection::addChunk(Chunk *C) {
191
0
  Chunks.push_back(C);
192
0
  C->setOutputSection(this);
193
0
  uint64_t Off = Header.VirtualSize;
194
0
  Off = alignTo(Off, C->Alignment);
195
0
  C->setRVA(Off);
196
0
  C->OutputSectionOff = Off;
197
0
  Off += C->getSize();
198
0
  if (Off > UINT32_MAX)
199
0
    error("section larger than 4 GiB: " + Name);
200
0
  Header.VirtualSize = Off;
201
0
  if (C->hasData())
202
0
    Header.SizeOfRawData = alignTo(Off, SectorSize);
203
0
}
204
205
0
void OutputSection::addPermissions(uint32_t C) {
206
0
  Header.Characteristics |= C & PermMask;
207
0
}
208
209
0
void OutputSection::setPermissions(uint32_t C) {
210
0
  Header.Characteristics = C & PermMask;
211
0
}
212
213
// Write the section header to a given buffer.
214
0
void OutputSection::writeHeaderTo(uint8_t *Buf) {
215
0
  auto *Hdr = reinterpret_cast<coff_section *>(Buf);
216
0
  *Hdr = Header;
217
0
  if (StringTableOff) {
218
0
    // If name is too long, write offset into the string table as a name.
219
0
    sprintf(Hdr->Name, "/%d", StringTableOff);
220
0
  } else {
221
0
    assert(!Config->Debug || Name.size() <= COFF::NameSize ||
222
0
           (Hdr->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) == 0);
223
0
    strncpy(Hdr->Name, Name.data(),
224
0
            std::min(Name.size(), (size_t)COFF::NameSize));
225
0
  }
226
0
}
227
228
} // namespace coff
229
} // namespace lld
230
231
// PDBs are matched against executables using a build id which consists of three
232
// components:
233
//   1. A 16-bit GUID
234
//   2. An age
235
//   3. A time stamp.
236
//
237
// Debuggers and symbol servers match executables against debug info by checking
238
// each of these components of the EXE/DLL against the corresponding value in
239
// the PDB and failing a match if any of the components differ.  In the case of
240
// symbol servers, symbols are cached in a folder that is a function of the
241
// GUID.  As a result, in order to avoid symbol cache pollution where every
242
// incremental build copies a new PDB to the symbol cache, we must try to re-use
243
// the existing GUID if one exists, but bump the age.  This way the match will
244
// fail, so the symbol cache knows to use the new PDB, but the GUID matches, so
245
// it overwrites the existing item in the symbol cache rather than making a new
246
// one.
247
0
static Optional<codeview::DebugInfo> loadExistingBuildId(StringRef Path) {
248
0
  // We don't need to incrementally update a previous build id if we're not
249
0
  // writing codeview debug info.
250
0
  if (!Config->Debug)
251
0
    return None;
252
0
253
0
  auto ExpectedBinary = llvm::object::createBinary(Path);
254
0
  if (!ExpectedBinary) {
255
0
    consumeError(ExpectedBinary.takeError());
256
0
    return None;
257
0
  }
258
0
259
0
  auto Binary = std::move(*ExpectedBinary);
260
0
  if (!Binary.getBinary()->isCOFF())
261
0
    return None;
262
0
263
0
  std::error_code EC;
264
0
  COFFObjectFile File(Binary.getBinary()->getMemoryBufferRef(), EC);
265
0
  if (EC)
266
0
    return None;
267
0
268
0
  // If the machine of the binary we're outputting doesn't match the machine
269
0
  // of the existing binary, don't try to re-use the build id.
270
0
  if (File.is64() != Config->is64() || File.getMachine() != Config->Machine)
271
0
    return None;
272
0
273
0
  for (const auto &DebugDir : File.debug_directories()) {
274
0
    if (DebugDir.Type != IMAGE_DEBUG_TYPE_CODEVIEW)
275
0
      continue;
276
0
277
0
    const codeview::DebugInfo *ExistingDI = nullptr;
278
0
    StringRef PDBFileName;
279
0
    if (auto EC = File.getDebugPDBInfo(ExistingDI, PDBFileName)) {
280
0
      (void)EC;
281
0
      return None;
282
0
    }
283
0
    // We only support writing PDBs in v70 format.  So if this is not a build
284
0
    // id that we recognize / support, ignore it.
285
0
    if (ExistingDI->Signature.CVSignature != OMF::Signature::PDB70)
286
0
      return None;
287
0
    return *ExistingDI;
288
0
  }
289
0
  return None;
290
0
}
291
292
// The main function of the writer.
293
0
void Writer::run() {
294
0
  ScopedTimer T1(CodeLayoutTimer);
295
0
296
0
  createSections();
297
0
  createMiscChunks();
298
0
  createImportTables();
299
0
  createExportTable();
300
0
  if (Config->Relocatable)
301
0
    createSection(".reloc");
302
0
  assignAddresses();
303
0
  removeEmptySections();
304
0
  setSectionPermissions();
305
0
  createSymbolAndStringTable();
306
0
307
0
  if (FileSize > UINT32_MAX)
308
0
    fatal("image size (" + Twine(FileSize) + ") " +
309
0
        "exceeds maximum allowable size (" + Twine(UINT32_MAX) + ")");
310
0
311
0
  // We must do this before opening the output file, as it depends on being able
312
0
  // to read the contents of the existing output file.
313
0
  PreviousBuildId = loadExistingBuildId(Config->OutputFile);
314
0
  openFile(Config->OutputFile);
315
0
  if (Config->is64()) {
316
0
    writeHeader<pe32plus_header>();
317
0
  } else {
318
0
    writeHeader<pe32_header>();
319
0
  }
320
0
  writeSections();
321
0
  sortExceptionTable();
322
0
  writeBuildId();
323
0
324
0
  T1.stop();
325
0
326
0
  if (!Config->PDBPath.empty() && Config->Debug) {
327
0
    assert(BuildId);
328
0
    createPDB(Symtab, OutputSections, SectionTable, *BuildId->BuildId);
329
0
  }
330
0
331
0
  writeMapFile(OutputSections);
332
0
333
0
  ScopedTimer T2(DiskCommitTimer);
334
0
  if (auto E = Buffer->commit())
335
0
    fatal("failed to write the output file: " + toString(std::move(E)));
336
0
}
337
338
0
static StringRef getOutputSection(StringRef Name) {
339
0
  StringRef S = Name.split('$').first;
340
0
341
0
  // Treat a later period as a separator for MinGW, for sections like
342
0
  // ".ctors.01234".
343
0
  S = S.substr(0, S.find('.', 1));
344
0
345
0
  auto It = Config->Merge.find(S);
346
0
  if (It == Config->Merge.end())
347
0
    return S;
348
0
  return It->second;
349
0
}
350
351
// Create output section objects and add them to OutputSections.
352
0
void Writer::createSections() {
353
0
  // First, bin chunks by name.
354
0
  std::map<StringRef, std::vector<Chunk *>> Map;
355
0
  for (Chunk *C : Symtab->getChunks()) {
356
0
    auto *SC = dyn_cast<SectionChunk>(C);
357
0
    if (SC && !SC->isLive()) {
358
0
      if (Config->Verbose)
359
0
        SC->printDiscardedMessage();
360
0
      continue;
361
0
    }
362
0
    Map[C->getSectionName()].push_back(C);
363
0
  }
364
0
365
0
  // Then create an OutputSection for each section.
366
0
  // '$' and all following characters in input section names are
367
0
  // discarded when determining output section. So, .text$foo
368
0
  // contributes to .text, for example. See PE/COFF spec 3.2.
369
0
  SmallDenseMap<StringRef, OutputSection *> Sections;
370
0
  for (auto Pair : Map) {
371
0
    StringRef Name = getOutputSection(Pair.first);
372
0
    OutputSection *&Sec = Sections[Name];
373
0
    if (!Sec) {
374
0
      Sec = make<OutputSection>(Name);
375
0
      OutputSections.push_back(Sec);
376
0
    }
377
0
    std::vector<Chunk *> &Chunks = Pair.second;
378
0
    for (Chunk *C : Chunks) {
379
0
      Sec->addChunk(C);
380
0
      Sec->addPermissions(C->getPermissions());
381
0
    }
382
0
  }
383
0
}
384
385
0
void Writer::createMiscChunks() {
386
0
  OutputSection *RData = createSection(".rdata");
387
0
388
0
  // Create thunks for locally-dllimported symbols.
389
0
  if (!Symtab->LocalImportChunks.empty()) {
390
0
    for (Chunk *C : Symtab->LocalImportChunks)
391
0
      RData->addChunk(C);
392
0
  }
393
0
394
0
  // Create Debug Information Chunks
395
0
  if (Config->Debug) {
396
0
    DebugDirectory = make<DebugDirectoryChunk>(DebugRecords);
397
0
398
0
    // Make a CVDebugRecordChunk even when /DEBUG:CV is not specified.  We
399
0
    // output a PDB no matter what, and this chunk provides the only means of
400
0
    // allowing a debugger to match a PDB and an executable.  So we need it even
401
0
    // if we're ultimately not going to write CodeView data to the PDB.
402
0
    auto *CVChunk = make<CVDebugRecordChunk>();
403
0
    BuildId = CVChunk;
404
0
    DebugRecords.push_back(CVChunk);
405
0
406
0
    RData->addChunk(DebugDirectory);
407
0
    for (Chunk *C : DebugRecords)
408
0
      RData->addChunk(C);
409
0
  }
410
0
411
0
  createSEHTable(RData);
412
0
}
413
414
// Create .idata section for the DLL-imported symbol table.
415
// The format of this section is inherently Windows-specific.
416
// IdataContents class abstracted away the details for us,
417
// so we just let it create chunks and add them to the section.
418
0
void Writer::createImportTables() {
419
0
  if (ImportFile::Instances.empty())
420
0
    return;
421
0
422
0
  // Initialize DLLOrder so that import entries are ordered in
423
0
  // the same order as in the command line. (That affects DLL
424
0
  // initialization order, and this ordering is MSVC-compatible.)
425
0
  for (ImportFile *File : ImportFile::Instances) {
426
0
    if (!File->Live)
427
0
      continue;
428
0
429
0
    std::string DLL = StringRef(File->DLLName).lower();
430
0
    if (Config->DLLOrder.count(DLL) == 0)
431
0
      Config->DLLOrder[DLL] = Config->DLLOrder.size();
432
0
  }
433
0
434
0
  OutputSection *Text = createSection(".text");
435
0
  for (ImportFile *File : ImportFile::Instances) {
436
0
    if (!File->Live)
437
0
      continue;
438
0
439
0
    if (DefinedImportThunk *Thunk = File->ThunkSym)
440
0
      Text->addChunk(Thunk->getChunk());
441
0
442
0
    if (Config->DelayLoads.count(StringRef(File->DLLName).lower())) {
443
0
      if (!File->ThunkSym)
444
0
        fatal("cannot delay-load " + toString(File) +
445
0
              " due to import of data: " + toString(*File->ImpSym));
446
0
      DelayIdata.add(File->ImpSym);
447
0
    } else {
448
0
      Idata.add(File->ImpSym);
449
0
    }
450
0
  }
451
0
452
0
  if (!Idata.empty()) {
453
0
    OutputSection *Sec = createSection(".idata");
454
0
    for (Chunk *C : Idata.getChunks())
455
0
      Sec->addChunk(C);
456
0
  }
457
0
458
0
  if (!DelayIdata.empty()) {
459
0
    Defined *Helper = cast<Defined>(Config->DelayLoadHelper);
460
0
    DelayIdata.create(Helper);
461
0
    OutputSection *Sec = createSection(".didat");
462
0
    for (Chunk *C : DelayIdata.getChunks())
463
0
      Sec->addChunk(C);
464
0
    Sec = createSection(".data");
465
0
    for (Chunk *C : DelayIdata.getDataChunks())
466
0
      Sec->addChunk(C);
467
0
    Sec = createSection(".text");
468
0
    for (Chunk *C : DelayIdata.getCodeChunks())
469
0
      Sec->addChunk(C);
470
0
  }
471
0
}
472
473
0
void Writer::createExportTable() {
474
0
  if (Config->Exports.empty())
475
0
    return;
476
0
  OutputSection *Sec = createSection(".edata");
477
0
  for (Chunk *C : Edata.Chunks)
478
0
    Sec->addChunk(C);
479
0
}
480
481
// The Windows loader doesn't seem to like empty sections,
482
// so we remove them if any.
483
0
void Writer::removeEmptySections() {
484
0
  auto IsEmpty = [](OutputSection *S) { return S->getVirtualSize() == 0; };
485
0
  OutputSections.erase(
486
0
      std::remove_if(OutputSections.begin(), OutputSections.end(), IsEmpty),
487
0
      OutputSections.end());
488
0
  uint32_t Idx = 1;
489
0
  for (OutputSection *Sec : OutputSections)
490
0
    Sec->SectionIndex = Idx++;
491
0
}
492
493
0
size_t Writer::addEntryToStringTable(StringRef Str) {
494
0
  assert(Str.size() > COFF::NameSize);
495
0
  size_t OffsetOfEntry = Strtab.size() + 4; // +4 for the size field
496
0
  Strtab.insert(Strtab.end(), Str.begin(), Str.end());
497
0
  Strtab.push_back('\0');
498
0
  return OffsetOfEntry;
499
0
}
500
501
0
Optional<coff_symbol16> Writer::createSymbol(Defined *Def) {
502
0
  // Relative symbols are unrepresentable in a COFF symbol table.
503
0
  if (isa<DefinedSynthetic>(Def))
504
0
    return None;
505
0
506
0
  // Don't write dead symbols or symbols in codeview sections to the symbol
507
0
  // table.
508
0
  if (!Def->isLive())
509
0
    return None;
510
0
  if (auto *D = dyn_cast<DefinedRegular>(Def))
511
0
    if (D->getChunk()->isCodeView())
512
0
      return None;
513
0
514
0
  coff_symbol16 Sym;
515
0
  StringRef Name = Def->getName();
516
0
  if (Name.size() > COFF::NameSize) {
517
0
    Sym.Name.Offset.Zeroes = 0;
518
0
    Sym.Name.Offset.Offset = addEntryToStringTable(Name);
519
0
  } else {
520
0
    memset(Sym.Name.ShortName, 0, COFF::NameSize);
521
0
    memcpy(Sym.Name.ShortName, Name.data(), Name.size());
522
0
  }
523
0
524
0
  if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
525
0
    COFFSymbolRef Ref = D->getCOFFSymbol();
526
0
    Sym.Type = Ref.getType();
527
0
    Sym.StorageClass = Ref.getStorageClass();
528
0
  } else {
529
0
    Sym.Type = IMAGE_SYM_TYPE_NULL;
530
0
    Sym.StorageClass = IMAGE_SYM_CLASS_EXTERNAL;
531
0
  }
532
0
  Sym.NumberOfAuxSymbols = 0;
533
0
534
0
  switch (Def->kind()) {
535
0
  case Symbol::DefinedAbsoluteKind:
536
0
    Sym.Value = Def->getRVA();
537
0
    Sym.SectionNumber = IMAGE_SYM_ABSOLUTE;
538
0
    break;
539
0
  default: {
540
0
    uint64_t RVA = Def->getRVA();
541
0
    OutputSection *Sec = nullptr;
542
0
    for (OutputSection *S : OutputSections) {
543
0
      if (S->getRVA() > RVA)
544
0
        break;
545
0
      Sec = S;
546
0
    }
547
0
    Sym.Value = RVA - Sec->getRVA();
548
0
    Sym.SectionNumber = Sec->SectionIndex;
549
0
    break;
550
0
  }
551
0
  }
552
0
  return Sym;
553
0
}
554
555
0
void Writer::createSymbolAndStringTable() {
556
0
  // Name field in the section table is 8 byte long. Longer names need
557
0
  // to be written to the string table. First, construct string table.
558
0
  for (OutputSection *Sec : OutputSections) {
559
0
    StringRef Name = Sec->getName();
560
0
    if (Name.size() <= COFF::NameSize)
561
0
      continue;
562
0
    // If a section isn't discardable (i.e. will be mapped at runtime),
563
0
    // prefer a truncated section name over a long section name in
564
0
    // the string table that is unavailable at runtime. This is different from
565
0
    // what link.exe does, but finding ".eh_fram" instead of "/4" is useful
566
0
    // to libunwind.
567
0
    if ((Sec->getPermissions() & IMAGE_SCN_MEM_DISCARDABLE) == 0)
568
0
      continue;
569
0
    Sec->setStringTableOff(addEntryToStringTable(Name));
570
0
  }
571
0
572
0
  if (Config->DebugDwarf) {
573
0
    for (ObjFile *File : ObjFile::Instances) {
574
0
      for (Symbol *B : File->getSymbols()) {
575
0
        auto *D = dyn_cast_or_null<Defined>(B);
576
0
        if (!D || D->WrittenToSymtab)
577
0
          continue;
578
0
        D->WrittenToSymtab = true;
579
0
580
0
        if (Optional<coff_symbol16> Sym = createSymbol(D))
581
0
          OutputSymtab.push_back(*Sym);
582
0
      }
583
0
    }
584
0
  }
585
0
586
0
  if (OutputSymtab.empty() && Strtab.empty())
587
0
    return;
588
0
589
0
  // We position the symbol table to be adjacent to the end of the last section.
590
0
  uint64_t FileOff = FileSize;
591
0
  PointerToSymbolTable = FileOff;
592
0
  FileOff += OutputSymtab.size() * sizeof(coff_symbol16);
593
0
  FileOff += 4 + Strtab.size();
594
0
  FileSize = alignTo(FileOff, SectorSize);
595
0
}
596
597
// Visits all sections to assign incremental, non-overlapping RVAs and
598
// file offsets.
599
0
void Writer::assignAddresses() {
600
0
  SizeOfHeaders = DOSStubSize + sizeof(PEMagic) + sizeof(coff_file_header) +
601
0
                  sizeof(data_directory) * NumberfOfDataDirectory +
602
0
                  sizeof(coff_section) * OutputSections.size();
603
0
  SizeOfHeaders +=
604
0
      Config->is64() ? sizeof(pe32plus_header) : sizeof(pe32_header);
605
0
  SizeOfHeaders = alignTo(SizeOfHeaders, SectorSize);
606
0
  uint64_t RVA = PageSize; // The first page is kept unmapped.
607
0
  FileSize = SizeOfHeaders;
608
0
  // Move DISCARDABLE (or non-memory-mapped) sections to the end of file because
609
0
  // the loader cannot handle holes.
610
0
  std::stable_partition(
611
0
      OutputSections.begin(), OutputSections.end(), [](OutputSection *S) {
612
0
        return (S->getPermissions() & IMAGE_SCN_MEM_DISCARDABLE) == 0;
613
0
      });
614
0
  for (OutputSection *Sec : OutputSections) {
615
0
    if (Sec->getName() == ".reloc")
616
0
      addBaserels(Sec);
617
0
    Sec->setRVA(RVA);
618
0
    Sec->setFileOffset(FileSize);
619
0
    RVA += alignTo(Sec->getVirtualSize(), PageSize);
620
0
    FileSize += alignTo(Sec->getRawSize(), SectorSize);
621
0
  }
622
0
  SizeOfImage = alignTo(RVA, PageSize);
623
0
}
624
625
0
template <typename PEHeaderTy> void Writer::writeHeader() {
626
0
  // Write DOS stub
627
0
  uint8_t *Buf = Buffer->getBufferStart();
628
0
  auto *DOS = reinterpret_cast<dos_header *>(Buf);
629
0
  Buf += DOSStubSize;
630
0
  DOS->Magic[0] = 'M';
631
0
  DOS->Magic[1] = 'Z';
632
0
  DOS->AddressOfRelocationTable = sizeof(dos_header);
633
0
  DOS->AddressOfNewExeHeader = DOSStubSize;
634
0
635
0
  // Write PE magic
636
0
  memcpy(Buf, PEMagic, sizeof(PEMagic));
637
0
  Buf += sizeof(PEMagic);
638
0
639
0
  // Write COFF header
640
0
  auto *COFF = reinterpret_cast<coff_file_header *>(Buf);
641
0
  Buf += sizeof(*COFF);
642
0
  COFF->Machine = Config->Machine;
643
0
  COFF->NumberOfSections = OutputSections.size();
644
0
  COFF->Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
645
0
  if (Config->LargeAddressAware)
646
0
    COFF->Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
647
0
  if (!Config->is64())
648
0
    COFF->Characteristics |= IMAGE_FILE_32BIT_MACHINE;
649
0
  if (Config->DLL)
650
0
    COFF->Characteristics |= IMAGE_FILE_DLL;
651
0
  if (!Config->Relocatable)
652
0
    COFF->Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
653
0
  COFF->SizeOfOptionalHeader =
654
0
      sizeof(PEHeaderTy) + sizeof(data_directory) * NumberfOfDataDirectory;
655
0
656
0
  // Write PE header
657
0
  auto *PE = reinterpret_cast<PEHeaderTy *>(Buf);
658
0
  Buf += sizeof(*PE);
659
0
  PE->Magic = Config->is64() ? PE32Header::PE32_PLUS : PE32Header::PE32;
660
0
661
0
  // If {Major,Minor}LinkerVersion is left at 0.0, then for some
662
0
  // reason signing the resulting PE file with Authenticode produces a
663
0
  // signature that fails to validate on Windows 7 (but is OK on 10).
664
0
  // Set it to 14.0, which is what VS2015 outputs, and which avoids
665
0
  // that problem.
666
0
  PE->MajorLinkerVersion = 14;
667
0
  PE->MinorLinkerVersion = 0;
668
0
669
0
  PE->ImageBase = Config->ImageBase;
670
0
  PE->SectionAlignment = PageSize;
671
0
  PE->FileAlignment = SectorSize;
672
0
  PE->MajorImageVersion = Config->MajorImageVersion;
673
0
  PE->MinorImageVersion = Config->MinorImageVersion;
674
0
  PE->MajorOperatingSystemVersion = Config->MajorOSVersion;
675
0
  PE->MinorOperatingSystemVersion = Config->MinorOSVersion;
676
0
  PE->MajorSubsystemVersion = Config->MajorOSVersion;
677
0
  PE->MinorSubsystemVersion = Config->MinorOSVersion;
678
0
  PE->Subsystem = Config->Subsystem;
679
0
  PE->SizeOfImage = SizeOfImage;
680
0
  PE->SizeOfHeaders = SizeOfHeaders;
681
0
  if (!Config->NoEntry) {
682
0
    Defined *Entry = cast<Defined>(Config->Entry);
683
0
    PE->AddressOfEntryPoint = Entry->getRVA();
684
0
    // Pointer to thumb code must have the LSB set, so adjust it.
685
0
    if (Config->Machine == ARMNT)
686
0
      PE->AddressOfEntryPoint |= 1;
687
0
  }
688
0
  PE->SizeOfStackReserve = Config->StackReserve;
689
0
  PE->SizeOfStackCommit = Config->StackCommit;
690
0
  PE->SizeOfHeapReserve = Config->HeapReserve;
691
0
  PE->SizeOfHeapCommit = Config->HeapCommit;
692
0
  if (Config->AppContainer)
693
0
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_APPCONTAINER;
694
0
  if (Config->DynamicBase)
695
0
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
696
0
  if (Config->HighEntropyVA)
697
0
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
698
0
  if (!Config->AllowBind)
699
0
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_BIND;
700
0
  if (Config->NxCompat)
701
0
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
702
0
  if (!Config->AllowIsolation)
703
0
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION;
704
0
  if (Config->Machine == I386 && !SEHTable &&
705
0
      !Symtab->findUnderscore("_load_config_used"))
706
0
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_SEH;
707
0
  if (Config->TerminalServerAware)
708
0
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE;
709
0
  PE->NumberOfRvaAndSize = NumberfOfDataDirectory;
710
0
  if (OutputSection *Text = findSection(".text")) {
711
0
    PE->BaseOfCode = Text->getRVA();
712
0
    PE->SizeOfCode = Text->getRawSize();
713
0
  }
714
0
  PE->SizeOfInitializedData = getSizeOfInitializedData();
715
0
716
0
  // Write data directory
717
0
  auto *Dir = reinterpret_cast<data_directory *>(Buf);
718
0
  Buf += sizeof(*Dir) * NumberfOfDataDirectory;
719
0
  if (OutputSection *Sec = findSection(".edata")) {
720
0
    Dir[EXPORT_TABLE].RelativeVirtualAddress = Sec->getRVA();
721
0
    Dir[EXPORT_TABLE].Size = Sec->getVirtualSize();
722
0
  }
723
0
  if (!Idata.empty()) {
724
0
    Dir[IMPORT_TABLE].RelativeVirtualAddress = Idata.getDirRVA();
725
0
    Dir[IMPORT_TABLE].Size = Idata.getDirSize();
726
0
    Dir[IAT].RelativeVirtualAddress = Idata.getIATRVA();
727
0
    Dir[IAT].Size = Idata.getIATSize();
728
0
  }
729
0
  if (OutputSection *Sec = findSection(".rsrc")) {
730
0
    Dir[RESOURCE_TABLE].RelativeVirtualAddress = Sec->getRVA();
731
0
    Dir[RESOURCE_TABLE].Size = Sec->getVirtualSize();
732
0
  }
733
0
  if (OutputSection *Sec = findSection(".pdata")) {
734
0
    Dir[EXCEPTION_TABLE].RelativeVirtualAddress = Sec->getRVA();
735
0
    Dir[EXCEPTION_TABLE].Size = Sec->getVirtualSize();
736
0
  }
737
0
  if (OutputSection *Sec = findSection(".reloc")) {
738
0
    Dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = Sec->getRVA();
739
0
    Dir[BASE_RELOCATION_TABLE].Size = Sec->getVirtualSize();
740
0
  }
741
0
  if (Symbol *Sym = Symtab->findUnderscore("_tls_used")) {
742
0
    if (Defined *B = dyn_cast<Defined>(Sym)) {
743
0
      Dir[TLS_TABLE].RelativeVirtualAddress = B->getRVA();
744
0
      Dir[TLS_TABLE].Size = Config->is64()
745
0
                                ? sizeof(object::coff_tls_directory64)
746
0
                                : sizeof(object::coff_tls_directory32);
747
0
    }
748
0
  }
749
0
  if (Config->Debug) {
750
0
    Dir[DEBUG_DIRECTORY].RelativeVirtualAddress = DebugDirectory->getRVA();
751
0
    Dir[DEBUG_DIRECTORY].Size = DebugDirectory->getSize();
752
0
  }
753
0
  if (Symbol *Sym = Symtab->findUnderscore("_load_config_used")) {
754
0
    if (auto *B = dyn_cast<DefinedRegular>(Sym)) {
755
0
      SectionChunk *SC = B->getChunk();
756
0
      assert(B->getRVA() >= SC->getRVA());
757
0
      uint64_t OffsetInChunk = B->getRVA() - SC->getRVA();
758
0
      if (!SC->hasData() || OffsetInChunk + 4 > SC->getSize())
759
0
        fatal("_load_config_used is malformed");
760
0
761
0
      ArrayRef<uint8_t> SecContents = SC->getContents();
762
0
      uint32_t LoadConfigSize =
763
0
          *reinterpret_cast<const ulittle32_t *>(&SecContents[OffsetInChunk]);
764
0
      if (OffsetInChunk + LoadConfigSize > SC->getSize())
765
0
        fatal("_load_config_used is too large");
766
0
      Dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = B->getRVA();
767
0
      Dir[LOAD_CONFIG_TABLE].Size = LoadConfigSize;
768
0
    }
769
0
  }
770
0
  if (!DelayIdata.empty()) {
771
0
    Dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
772
0
        DelayIdata.getDirRVA();
773
0
    Dir[DELAY_IMPORT_DESCRIPTOR].Size = DelayIdata.getDirSize();
774
0
  }
775
0
776
0
  // Write section table
777
0
  for (OutputSection *Sec : OutputSections) {
778
0
    Sec->writeHeaderTo(Buf);
779
0
    Buf += sizeof(coff_section);
780
0
  }
781
0
  SectionTable = ArrayRef<uint8_t>(
782
0
      Buf - OutputSections.size() * sizeof(coff_section), Buf);
783
0
784
0
  if (OutputSymtab.empty() && Strtab.empty())
785
0
    return;
786
0
787
0
  COFF->PointerToSymbolTable = PointerToSymbolTable;
788
0
  uint32_t NumberOfSymbols = OutputSymtab.size();
789
0
  COFF->NumberOfSymbols = NumberOfSymbols;
790
0
  auto *SymbolTable = reinterpret_cast<coff_symbol16 *>(
791
0
      Buffer->getBufferStart() + COFF->PointerToSymbolTable);
792
0
  for (size_t I = 0; I != NumberOfSymbols; ++I)
793
0
    SymbolTable[I] = OutputSymtab[I];
794
0
  // Create the string table, it follows immediately after the symbol table.
795
0
  // The first 4 bytes is length including itself.
796
0
  Buf = reinterpret_cast<uint8_t *>(&SymbolTable[NumberOfSymbols]);
797
0
  write32le(Buf, Strtab.size() + 4);
798
0
  if (!Strtab.empty())
799
0
    memcpy(Buf + 4, Strtab.data(), Strtab.size());
800
0
}
Unexecuted instantiation: Writer.cpp:void (anonymous namespace)::Writer::writeHeader<llvm::object::pe32plus_header>()
Unexecuted instantiation: Writer.cpp:void (anonymous namespace)::Writer::writeHeader<llvm::object::pe32_header>()
801
802
0
void Writer::openFile(StringRef Path) {
803
0
  Buffer = CHECK(
804
0
      FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable),
805
0
      "failed to open " + Path);
806
0
}
807
808
0
void Writer::createSEHTable(OutputSection *RData) {
809
0
  // Create SEH table. x86-only.
810
0
  if (Config->Machine != I386)
811
0
    return;
812
0
813
0
  std::set<Defined *> Handlers;
814
0
815
0
  for (ObjFile *File : ObjFile::Instances) {
816
0
    if (!File->SEHCompat)
817
0
      return;
818
0
    for (uint32_t I : File->SXData)
819
0
      if (Symbol *B = File->getSymbol(I))
820
0
        if (B->isLive())
821
0
          Handlers.insert(cast<Defined>(B));
822
0
  }
823
0
824
0
  if (Handlers.empty())
825
0
    return;
826
0
827
0
  SEHTable = make<SEHTableChunk>(Handlers);
828
0
  RData->addChunk(SEHTable);
829
0
830
0
  // Replace the absolute table symbol with a synthetic symbol pointing to the
831
0
  // SEHTable chunk so that we can emit base relocations for it and resolve
832
0
  // section relative relocations.
833
0
  Symbol *T = Symtab->find("___safe_se_handler_table");
834
0
  Symbol *C = Symtab->find("___safe_se_handler_count");
835
0
  replaceSymbol<DefinedSynthetic>(T, T->getName(), SEHTable);
836
0
  cast<DefinedAbsolute>(C)->setVA(SEHTable->getSize() / 4);
837
0
}
838
839
// Handles /section options to allow users to overwrite
840
// section attributes.
841
0
void Writer::setSectionPermissions() {
842
0
  for (auto &P : Config->Section) {
843
0
    StringRef Name = P.first;
844
0
    uint32_t Perm = P.second;
845
0
    if (auto *Sec = findSection(Name))
846
0
      Sec->setPermissions(Perm);
847
0
  }
848
0
}
849
850
// Write section contents to a mmap'ed file.
851
0
void Writer::writeSections() {
852
0
  // Record the section index that should be used when resolving a section
853
0
  // relocation against an absolute symbol.
854
0
  DefinedAbsolute::OutputSectionIndex = OutputSections.size() + 1;
855
0
856
0
  uint8_t *Buf = Buffer->getBufferStart();
857
0
  for (OutputSection *Sec : OutputSections) {
858
0
    uint8_t *SecBuf = Buf + Sec->getFileOff();
859
0
    // Fill gaps between functions in .text with INT3 instructions
860
0
    // instead of leaving as NUL bytes (which can be interpreted as
861
0
    // ADD instructions).
862
0
    if (Sec->getPermissions() & IMAGE_SCN_CNT_CODE)
863
0
      memset(SecBuf, 0xCC, Sec->getRawSize());
864
0
    for_each(parallel::par, Sec->getChunks().begin(), Sec->getChunks().end(),
865
0
             [&](Chunk *C) { C->writeTo(SecBuf); });
866
0
  }
867
0
}
868
869
0
void Writer::writeBuildId() {
870
0
  // If we're not writing a build id (e.g. because /debug is not specified),
871
0
  // then just return;
872
0
  if (!Config->Debug)
873
0
    return;
874
0
875
0
  assert(BuildId && "BuildId is not set!");
876
0
877
0
  if (PreviousBuildId.hasValue()) {
878
0
    *BuildId->BuildId = *PreviousBuildId;
879
0
    BuildId->BuildId->PDB70.Age = BuildId->BuildId->PDB70.Age + 1;
880
0
    return;
881
0
  }
882
0
883
0
  BuildId->BuildId->Signature.CVSignature = OMF::Signature::PDB70;
884
0
  BuildId->BuildId->PDB70.Age = 1;
885
0
  llvm::getRandomBytes(BuildId->BuildId->PDB70.Signature, 16);
886
0
}
887
888
// Sort .pdata section contents according to PE/COFF spec 5.5.
889
0
void Writer::sortExceptionTable() {
890
0
  OutputSection *Sec = findSection(".pdata");
891
0
  if (!Sec)
892
0
    return;
893
0
  // We assume .pdata contains function table entries only.
894
0
  uint8_t *Begin = Buffer->getBufferStart() + Sec->getFileOff();
895
0
  uint8_t *End = Begin + Sec->getVirtualSize();
896
0
  if (Config->Machine == AMD64) {
897
0
    struct Entry { ulittle32_t Begin, End, Unwind; };
898
0
    sort(parallel::par, (Entry *)Begin, (Entry *)End,
899
0
         [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
900
0
    return;
901
0
  }
902
0
  if (Config->Machine == ARMNT || Config->Machine == ARM64) {
903
0
    struct Entry { ulittle32_t Begin, Unwind; };
904
0
    sort(parallel::par, (Entry *)Begin, (Entry *)End,
905
0
         [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
906
0
    return;
907
0
  }
908
0
  errs() << "warning: don't know how to handle .pdata.\n";
909
0
}
910
911
0
OutputSection *Writer::findSection(StringRef Name) {
912
0
  for (OutputSection *Sec : OutputSections)
913
0
    if (Sec->getName() == Name)
914
0
      return Sec;
915
0
  return nullptr;
916
0
}
917
918
0
uint32_t Writer::getSizeOfInitializedData() {
919
0
  uint32_t Res = 0;
920
0
  for (OutputSection *S : OutputSections)
921
0
    if (S->getPermissions() & IMAGE_SCN_CNT_INITIALIZED_DATA)
922
0
      Res += S->getRawSize();
923
0
  return Res;
924
0
}
925
926
// Returns an existing section or create a new one if not found.
927
0
OutputSection *Writer::createSection(StringRef Name) {
928
0
  if (auto *Sec = findSection(Name))
929
0
    return Sec;
930
0
  const auto DATA = IMAGE_SCN_CNT_INITIALIZED_DATA;
931
0
  const auto BSS = IMAGE_SCN_CNT_UNINITIALIZED_DATA;
932
0
  const auto CODE = IMAGE_SCN_CNT_CODE;
933
0
  const auto DISCARDABLE = IMAGE_SCN_MEM_DISCARDABLE;
934
0
  const auto R = IMAGE_SCN_MEM_READ;
935
0
  const auto W = IMAGE_SCN_MEM_WRITE;
936
0
  const auto X = IMAGE_SCN_MEM_EXECUTE;
937
0
  uint32_t Perms = StringSwitch<uint32_t>(Name)
938
0
                       .Case(".bss", BSS | R | W)
939
0
                       .Case(".data", DATA | R | W)
940
0
                       .Cases(".didat", ".edata", ".idata", ".rdata", DATA | R)
941
0
                       .Case(".reloc", DATA | DISCARDABLE | R)
942
0
                       .Case(".text", CODE | R | X)
943
0
                       .Default(0);
944
0
  if (!Perms)
945
0
    llvm_unreachable("unknown section name");
946
0
  auto Sec = make<OutputSection>(Name);
947
0
  Sec->addPermissions(Perms);
948
0
  OutputSections.push_back(Sec);
949
0
  return Sec;
950
0
}
951
952
// Dest is .reloc section. Add contents to that section.
953
0
void Writer::addBaserels(OutputSection *Dest) {
954
0
  std::vector<Baserel> V;
955
0
  for (OutputSection *Sec : OutputSections) {
956
0
    if (Sec == Dest)
957
0
      continue;
958
0
    // Collect all locations for base relocations.
959
0
    for (Chunk *C : Sec->getChunks())
960
0
      C->getBaserels(&V);
961
0
    // Add the addresses to .reloc section.
962
0
    if (!V.empty())
963
0
      addBaserelBlocks(Dest, V);
964
0
    V.clear();
965
0
  }
966
0
}
967
968
// Add addresses to .reloc section. Note that addresses are grouped by page.
969
0
void Writer::addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V) {
970
0
  const uint32_t Mask = ~uint32_t(PageSize - 1);
971
0
  uint32_t Page = V[0].RVA & Mask;
972
0
  size_t I = 0, J = 1;
973
0
  for (size_t E = V.size(); J < E; ++J) {
974
0
    uint32_t P = V[J].RVA & Mask;
975
0
    if (P == Page)
976
0
      continue;
977
0
    Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
978
0
    I = J;
979
0
    Page = P;
980
0
  }
981
0
  if (I == J)
982
0
    return;
983
0
  Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
984
0
}