Coverage Report

Created: 2017-10-03 07:32

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