Coverage Report

Created: 2017-09-19 22:28

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