Coverage Report

Created: 2018-08-19 21:11

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/COFF/Writer.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- Writer.cpp ---------------------------------------------------------===//
2
//
3
//                             The LLVM Linker
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
10
#include "Writer.h"
11
#include "Config.h"
12
#include "DLL.h"
13
#include "InputFiles.h"
14
#include "MapFile.h"
15
#include "PDB.h"
16
#include "SymbolTable.h"
17
#include "Symbols.h"
18
#include "lld/Common/ErrorHandler.h"
19
#include "lld/Common/Memory.h"
20
#include "lld/Common/Timer.h"
21
#include "llvm/ADT/DenseMap.h"
22
#include "llvm/ADT/STLExtras.h"
23
#include "llvm/ADT/StringSwitch.h"
24
#include "llvm/Support/BinaryStreamReader.h"
25
#include "llvm/Support/Debug.h"
26
#include "llvm/Support/Endian.h"
27
#include "llvm/Support/FileOutputBuffer.h"
28
#include "llvm/Support/Parallel.h"
29
#include "llvm/Support/Path.h"
30
#include "llvm/Support/RandomNumberGenerator.h"
31
#include "llvm/Support/xxhash.h"
32
#include <algorithm>
33
#include <cstdio>
34
#include <map>
35
#include <memory>
36
#include <utility>
37
38
using namespace llvm;
39
using namespace llvm::COFF;
40
using namespace llvm::object;
41
using namespace llvm::support;
42
using namespace llvm::support::endian;
43
using namespace lld;
44
using namespace lld::coff;
45
46
/* To re-generate DOSProgram:
47
$ cat > /tmp/DOSProgram.asm
48
org 0
49
        ; Copy cs to ds.
50
        push cs
51
        pop ds
52
        ; Point ds:dx at the $-terminated string.
53
        mov dx, str
54
        ; Int 21/AH=09h: Write string to standard output.
55
        mov ah, 0x9
56
        int 0x21
57
        ; Int 21/AH=4Ch: Exit with return code (in AL).
58
        mov ax, 0x4C01
59
        int 0x21
60
str:
61
        db 'This program cannot be run in DOS mode.$'
62
align 8, db 0
63
$ nasm -fbin /tmp/DOSProgram.asm -o /tmp/DOSProgram.bin
64
$ xxd -i /tmp/DOSProgram.bin
65
*/
66
static unsigned char DOSProgram[] = {
67
  0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8, 0x01, 0x4c,
68
  0xcd, 0x21, 0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72,
69
  0x61, 0x6d, 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x20, 0x62, 0x65,
70
  0x20, 0x72, 0x75, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20,
71
  0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x24, 0x00, 0x00
72
};
73
static_assert(sizeof(DOSProgram) % 8 == 0,
74
              "DOSProgram size must be multiple of 8");
75
76
static const int SectorSize = 512;
77
static const int DOSStubSize = sizeof(dos_header) + sizeof(DOSProgram);
78
static_assert(DOSStubSize % 8 == 0, "DOSStub size must be multiple of 8");
79
80
static const int NumberfOfDataDirectory = 16;
81
82
namespace {
83
84
class DebugDirectoryChunk : public Chunk {
85
public:
86
80
  DebugDirectoryChunk(const std::vector<Chunk *> &R) : Records(R) {}
87
88
230
  size_t getSize() const override {
89
230
    return Records.size() * sizeof(debug_directory);
90
230
  }
91
92
80
  void writeTo(uint8_t *B) const override {
93
80
    auto *D = reinterpret_cast<debug_directory *>(B + OutputSectionOff);
94
80
95
80
    for (const Chunk *Record : Records) {
96
80
      D->Characteristics = 0;
97
80
      D->TimeDateStamp = 0;
98
80
      D->MajorVersion = 0;
99
80
      D->MinorVersion = 0;
100
80
      D->Type = COFF::IMAGE_DEBUG_TYPE_CODEVIEW;
101
80
      D->SizeOfData = Record->getSize();
102
80
      D->AddressOfRawData = Record->getRVA();
103
80
      OutputSection *OS = Record->getOutputSection();
104
80
      uint64_t Offs = OS->getFileOff() + (Record->getRVA() - OS->getRVA());
105
80
      D->PointerToRawData = Offs;
106
80
107
80
      TimeDateStamps.push_back(&D->TimeDateStamp);
108
80
      ++D;
109
80
    }
110
80
  }
111
112
80
  void setTimeDateStamp(uint32_t TimeDateStamp) {
113
80
    for (support::ulittle32_t *TDS : TimeDateStamps)
114
80
      *TDS = TimeDateStamp;
115
80
  }
116
117
private:
118
  mutable std::vector<support::ulittle32_t *> TimeDateStamps;
119
  const std::vector<Chunk *> &Records;
120
};
121
122
class CVDebugRecordChunk : public Chunk {
123
public:
124
230
  size_t getSize() const override {
125
230
    return sizeof(codeview::DebugInfo) + Config->PDBAltPath.size() + 1;
126
230
  }
127
128
80
  void writeTo(uint8_t *B) const override {
129
80
    // Save off the DebugInfo entry to backfill the file signature (build id)
130
80
    // in Writer::writeBuildId
131
80
    BuildId = reinterpret_cast<codeview::DebugInfo *>(B + OutputSectionOff);
132
80
133
80
    // variable sized field (PDB Path)
134
80
    char *P = reinterpret_cast<char *>(B + OutputSectionOff + sizeof(*BuildId));
135
80
    if (!Config->PDBAltPath.empty())
136
70
      memcpy(P, Config->PDBAltPath.data(), Config->PDBAltPath.size());
137
80
    P[Config->PDBAltPath.size()] = '\0';
138
80
  }
139
140
  mutable codeview::DebugInfo *BuildId = nullptr;
141
};
142
143
// The writer writes a SymbolTable result to a file.
144
class Writer {
145
public:
146
405
  Writer() : Buffer(errorHandler().OutputBuffer) {}
147
  void run();
148
149
private:
150
  void createSections();
151
  void createMiscChunks();
152
  void createImportTables();
153
  void createExportTable();
154
  void mergeSections();
155
  void assignAddresses();
156
  void removeEmptySections();
157
  void createSymbolAndStringTable();
158
  void openFile(StringRef OutputPath);
159
  template <typename PEHeaderTy> void writeHeader();
160
  void createSEHTable();
161
  void createGuardCFTables();
162
  void markSymbolsForRVATable(ObjFile *File,
163
                              ArrayRef<SectionChunk *> SymIdxChunks,
164
                              SymbolRVASet &TableSymbols);
165
  void maybeAddRVATable(SymbolRVASet TableSymbols, StringRef TableSym,
166
                        StringRef CountSym);
167
  void setSectionPermissions();
168
  void writeSections();
169
  void writeBuildId();
170
  void sortExceptionTable();
171
172
  llvm::Optional<coff_symbol16> createSymbol(Defined *D);
173
  size_t addEntryToStringTable(StringRef Str);
174
175
  OutputSection *findSection(StringRef Name);
176
  void addBaserels();
177
  void addBaserelBlocks(std::vector<Baserel> &V);
178
179
  uint32_t getSizeOfInitializedData();
180
  std::map<StringRef, std::vector<DefinedImportData *>> binImports();
181
182
  std::unique_ptr<FileOutputBuffer> &Buffer;
183
  std::vector<OutputSection *> OutputSections;
184
  std::vector<char> Strtab;
185
  std::vector<llvm::object::coff_symbol16> OutputSymtab;
186
  IdataContents Idata;
187
  DelayLoadContents DelayIdata;
188
  EdataContents Edata;
189
  bool SetNoSEHCharacteristic = false;
190
191
  DebugDirectoryChunk *DebugDirectory = nullptr;
192
  std::vector<Chunk *> DebugRecords;
193
  CVDebugRecordChunk *BuildId = nullptr;
194
  Optional<codeview::DebugInfo> PreviousBuildId;
195
  ArrayRef<uint8_t> SectionTable;
196
197
  uint64_t FileSize;
198
  uint32_t PointerToSymbolTable = 0;
199
  uint64_t SizeOfImage;
200
  uint64_t SizeOfHeaders;
201
202
  OutputSection *TextSec;
203
  OutputSection *RdataSec;
204
  OutputSection *BuildidSec;
205
  OutputSection *DataSec;
206
  OutputSection *PdataSec;
207
  OutputSection *IdataSec;
208
  OutputSection *EdataSec;
209
  OutputSection *DidatSec;
210
  OutputSection *RsrcSec;
211
  OutputSection *RelocSec;
212
213
  // The first and last .pdata sections in the output file.
214
  //
215
  // We need to keep track of the location of .pdata in whichever section it
216
  // gets merged into so that we can sort its contents and emit a correct data
217
  // directory entry for the exception table. This is also the case for some
218
  // other sections (such as .edata) but because the contents of those sections
219
  // are entirely linker-generated we can keep track of their locations using
220
  // the chunks that the linker creates. All .pdata chunks come from input
221
  // files, so we need to keep track of them separately.
222
  Chunk *FirstPdata = nullptr;
223
  Chunk *LastPdata;
224
};
225
} // anonymous namespace
226
227
namespace lld {
228
namespace coff {
229
230
static Timer CodeLayoutTimer("Code Layout", Timer::root());
231
static Timer DiskCommitTimer("Commit Output File", Timer::root());
232
233
405
void writeResult() { Writer().run(); }
234
235
2.68k
void OutputSection::addChunk(Chunk *C) {
236
2.68k
  Chunks.push_back(C);
237
2.68k
  C->setOutputSection(this);
238
2.68k
}
239
240
7
void OutputSection::setPermissions(uint32_t C) {
241
7
  Header.Characteristics &= ~PermMask;
242
7
  Header.Characteristics |= C;
243
7
}
244
245
1.66k
void OutputSection::merge(OutputSection *Other) {
246
1.66k
  for (Chunk *C : Other->Chunks)
247
1.25k
    C->setOutputSection(this);
248
1.66k
  Chunks.insert(Chunks.end(), Other->Chunks.begin(), Other->Chunks.end());
249
1.66k
  Other->Chunks.clear();
250
1.66k
}
251
252
// Write the section header to a given buffer.
253
843
void OutputSection::writeHeaderTo(uint8_t *Buf) {
254
843
  auto *Hdr = reinterpret_cast<coff_section *>(Buf);
255
843
  *Hdr = Header;
256
843
  if (StringTableOff) {
257
18
    // If name is too long, write offset into the string table as a name.
258
18
    sprintf(Hdr->Name, "/%d", StringTableOff);
259
825
  } else {
260
825
    assert(!Config->Debug || Name.size() <= COFF::NameSize ||
261
825
           (Hdr->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) == 0);
262
825
    strncpy(Hdr->Name, Name.data(),
263
825
            std::min(Name.size(), (size_t)COFF::NameSize));
264
825
  }
265
843
}
266
267
} // namespace coff
268
} // namespace lld
269
270
// PDBs are matched against executables using a build id which consists of three
271
// components:
272
//   1. A 16-bit GUID
273
//   2. An age
274
//   3. A time stamp.
275
//
276
// Debuggers and symbol servers match executables against debug info by checking
277
// each of these components of the EXE/DLL against the corresponding value in
278
// the PDB and failing a match if any of the components differ.  In the case of
279
// symbol servers, symbols are cached in a folder that is a function of the
280
// GUID.  As a result, in order to avoid symbol cache pollution where every
281
// incremental build copies a new PDB to the symbol cache, we must try to re-use
282
// the existing GUID if one exists, but bump the age.  This way the match will
283
// fail, so the symbol cache knows to use the new PDB, but the GUID matches, so
284
// it overwrites the existing item in the symbol cache rather than making a new
285
// one.
286
405
static Optional<codeview::DebugInfo> loadExistingBuildId(StringRef Path) {
287
405
  // We don't need to incrementally update a previous build id if we're not
288
405
  // writing codeview debug info.
289
405
  if (!Config->Debug)
290
325
    return None;
291
80
292
80
  auto ExpectedBinary = llvm::object::createBinary(Path);
293
80
  if (!ExpectedBinary) {
294
49
    consumeError(ExpectedBinary.takeError());
295
49
    return None;
296
49
  }
297
31
298
31
  auto Binary = std::move(*ExpectedBinary);
299
31
  if (!Binary.getBinary()->isCOFF())
300
0
    return None;
301
31
302
31
  std::error_code EC;
303
31
  COFFObjectFile File(Binary.getBinary()->getMemoryBufferRef(), EC);
304
31
  if (EC)
305
0
    return None;
306
31
307
31
  // If the machine of the binary we're outputting doesn't match the machine
308
31
  // of the existing binary, don't try to re-use the build id.
309
31
  if (File.is64() != Config->is64() || File.getMachine() != Config->Machine)
310
0
    return None;
311
31
312
31
  for (const auto &DebugDir : File.debug_directories()) {
313
21
    if (DebugDir.Type != IMAGE_DEBUG_TYPE_CODEVIEW)
314
0
      continue;
315
21
316
21
    const codeview::DebugInfo *ExistingDI = nullptr;
317
21
    StringRef PDBFileName;
318
21
    if (auto EC = File.getDebugPDBInfo(ExistingDI, PDBFileName)) {
319
0
      (void)EC;
320
0
      return None;
321
0
    }
322
21
    // We only support writing PDBs in v70 format.  So if this is not a build
323
21
    // id that we recognize / support, ignore it.
324
21
    if (ExistingDI->Signature.CVSignature != OMF::Signature::PDB70)
325
0
      return None;
326
21
    return *ExistingDI;
327
21
  }
328
31
  
return None10
;
329
31
}
330
331
// The main function of the writer.
332
405
void Writer::run() {
333
405
  ScopedTimer T1(CodeLayoutTimer);
334
405
335
405
  createSections();
336
405
  createMiscChunks();
337
405
  createImportTables();
338
405
  createExportTable();
339
405
  mergeSections();
340
405
  assignAddresses();
341
405
  removeEmptySections();
342
405
  setSectionPermissions();
343
405
  createSymbolAndStringTable();
344
405
345
405
  if (FileSize > UINT32_MAX)
346
405
    fatal("image size (" + Twine(FileSize) + ") " +
347
0
        "exceeds maximum allowable size (" + Twine(UINT32_MAX) + ")");
348
405
349
405
  // We must do this before opening the output file, as it depends on being able
350
405
  // to read the contents of the existing output file.
351
405
  PreviousBuildId = loadExistingBuildId(Config->OutputFile);
352
405
  openFile(Config->OutputFile);
353
405
  if (Config->is64()) {
354
325
    writeHeader<pe32plus_header>();
355
325
  } else {
356
80
    writeHeader<pe32_header>();
357
80
  }
358
405
  writeSections();
359
405
  sortExceptionTable();
360
405
  writeBuildId();
361
405
362
405
  T1.stop();
363
405
364
405
  if (!Config->PDBPath.empty() && 
Config->Debug70
) {
365
70
    assert(BuildId);
366
70
    createPDB(Symtab, OutputSections, SectionTable, *BuildId->BuildId);
367
70
  }
368
405
369
405
  writeMapFile(OutputSections);
370
405
371
405
  ScopedTimer T2(DiskCommitTimer);
372
405
  if (auto E = Buffer->commit())
373
0
    fatal("failed to write the output file: " + toString(std::move(E)));
374
405
}
375
376
937
static StringRef getOutputSectionName(StringRef Name) {
377
937
  StringRef S = Name.split('$').first;
378
937
379
937
  // Treat a later period as a separator for MinGW, for sections like
380
937
  // ".ctors.01234".
381
937
  return S.substr(0, S.find('.', 1));
382
937
}
383
384
// For /order.
385
4
static void sortBySectionOrder(std::vector<Chunk *> &Chunks) {
386
68
  auto GetPriority = [](const Chunk *C) {
387
68
    if (auto *Sec = dyn_cast<SectionChunk>(C))
388
68
      if (Sec->Sym)
389
68
        return Config->Order.lookup(Sec->Sym->getName());
390
0
    return 0;
391
0
  };
392
4
393
4
  std::stable_sort(Chunks.begin(), Chunks.end(),
394
34
                   [=](const Chunk *A, const Chunk *B) {
395
34
                     return GetPriority(A) < GetPriority(B);
396
34
                   });
397
4
}
398
399
// Create output section objects and add them to OutputSections.
400
405
void Writer::createSections() {
401
405
  // First, create the builtin sections.
402
405
  const uint32_t DATA = IMAGE_SCN_CNT_INITIALIZED_DATA;
403
405
  const uint32_t BSS = IMAGE_SCN_CNT_UNINITIALIZED_DATA;
404
405
  const uint32_t CODE = IMAGE_SCN_CNT_CODE;
405
405
  const uint32_t DISCARDABLE = IMAGE_SCN_MEM_DISCARDABLE;
406
405
  const uint32_t R = IMAGE_SCN_MEM_READ;
407
405
  const uint32_t W = IMAGE_SCN_MEM_WRITE;
408
405
  const uint32_t X = IMAGE_SCN_MEM_EXECUTE;
409
405
410
405
  SmallDenseMap<std::pair<StringRef, uint32_t>, OutputSection *> Sections;
411
5.39k
  auto CreateSection = [&](StringRef Name, uint32_t OutChars) {
412
5.39k
    OutputSection *&Sec = Sections[{Name, OutChars}];
413
5.39k
    if (!Sec) {
414
4.56k
      Sec = make<OutputSection>(Name, OutChars);
415
4.56k
      OutputSections.push_back(Sec);
416
4.56k
    }
417
5.39k
    return Sec;
418
5.39k
  };
419
405
420
405
  // Try to match the section order used by link.exe.
421
405
  TextSec = CreateSection(".text", CODE | R | X);
422
405
  CreateSection(".bss", BSS | R | W);
423
405
  RdataSec = CreateSection(".rdata", DATA | R);
424
405
  BuildidSec = CreateSection(".buildid", DATA | R);
425
405
  DataSec = CreateSection(".data", DATA | R | W);
426
405
  PdataSec = CreateSection(".pdata", DATA | R);
427
405
  IdataSec = CreateSection(".idata", DATA | R);
428
405
  EdataSec = CreateSection(".edata", DATA | R);
429
405
  DidatSec = CreateSection(".didat", DATA | R);
430
405
  RsrcSec = CreateSection(".rsrc", DATA | R);
431
405
  RelocSec = CreateSection(".reloc", DATA | DISCARDABLE | R);
432
405
433
405
  // Then bin chunks by name and output characteristics.
434
405
  std::map<std::pair<StringRef, uint32_t>, std::vector<Chunk *>> Map;
435
1.35k
  for (Chunk *C : Symtab->getChunks()) {
436
1.35k
    auto *SC = dyn_cast<SectionChunk>(C);
437
1.35k
    if (SC && 
!SC->isLive()1.34k
) {
438
50
      if (Config->Verbose)
439
20
        SC->printDiscardedMessage();
440
50
      continue;
441
50
    }
442
1.30k
    Map[{C->getSectionName(), C->getOutputCharacteristics()}].push_back(C);
443
1.30k
  }
444
405
445
405
  // Process an /order option.
446
405
  if (!Config->Order.empty())
447
4
    for (auto &Pair : Map)
448
4
      sortBySectionOrder(Pair.second);
449
405
450
405
  // Then create an OutputSection for each section.
451
405
  // '$' and all following characters in input section names are
452
405
  // discarded when determining output section. So, .text$foo
453
405
  // contributes to .text, for example. See PE/COFF spec 3.2.
454
937
  for (auto Pair : Map) {
455
937
    StringRef Name = getOutputSectionName(Pair.first.first);
456
937
    uint32_t OutChars = Pair.first.second;
457
937
458
937
    // In link.exe, there is a special case for the I386 target where .CRT
459
937
    // sections are treated as if they have output characteristics DATA | R if
460
937
    // their characteristics are DATA | R | W. This implements the same special
461
937
    // case for all architectures.
462
937
    if (Name == ".CRT")
463
3
      OutChars = DATA | R;
464
937
465
937
    OutputSection *Sec = CreateSection(Name, OutChars);
466
937
    std::vector<Chunk *> &Chunks = Pair.second;
467
937
    for (Chunk *C : Chunks)
468
1.30k
      Sec->addChunk(C);
469
937
  }
470
405
471
405
  // Finally, move some output sections to the end.
472
8.66k
  auto SectionOrder = [&](OutputSection *S) {
473
8.66k
    // Move DISCARDABLE (or non-memory-mapped) sections to the end of file because
474
8.66k
    // the loader cannot handle holes. Stripping can remove other discardable ones
475
8.66k
    // than .reloc, which is first of them (created early).
476
8.66k
    if (S->Header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE)
477
546
      return 2;
478
8.11k
    // .rsrc should come at the end of the non-discardable sections because its
479
8.11k
    // size may change by the Win32 UpdateResources() function, causing
480
8.11k
    // subsequent sections to move (see https://crbug.com/827082).
481
8.11k
    if (S == RsrcSec)
482
894
      return 1;
483
7.22k
    return 0;
484
7.22k
  };
485
405
  std::stable_sort(OutputSections.begin(), OutputSections.end(),
486
4.33k
                   [&](OutputSection *S, OutputSection *T) {
487
4.33k
                     return SectionOrder(S) < SectionOrder(T);
488
4.33k
                   });
489
405
}
490
491
405
void Writer::createMiscChunks() {
492
405
  for (auto &P : MergeChunk::Instances)
493
4
    RdataSec->addChunk(P.second);
494
405
495
405
  // Create thunks for locally-dllimported symbols.
496
405
  if (!Symtab->LocalImportChunks.empty()) {
497
6
    for (Chunk *C : Symtab->LocalImportChunks)
498
6
      RdataSec->addChunk(C);
499
6
  }
500
405
501
405
  // Create Debug Information Chunks
502
405
  if (Config->Debug) {
503
80
    DebugDirectory = make<DebugDirectoryChunk>(DebugRecords);
504
80
505
80
    OutputSection *DebugInfoSec = Config->MinGW ? 
BuildidSec1
:
RdataSec79
;
506
80
507
80
    // Make a CVDebugRecordChunk even when /DEBUG:CV is not specified.  We
508
80
    // output a PDB no matter what, and this chunk provides the only means of
509
80
    // allowing a debugger to match a PDB and an executable.  So we need it even
510
80
    // if we're ultimately not going to write CodeView data to the PDB.
511
80
    auto *CVChunk = make<CVDebugRecordChunk>();
512
80
    BuildId = CVChunk;
513
80
    DebugRecords.push_back(CVChunk);
514
80
515
80
    DebugInfoSec->addChunk(DebugDirectory);
516
80
    for (Chunk *C : DebugRecords)
517
80
      DebugInfoSec->addChunk(C);
518
80
  }
519
405
520
405
  // Create SEH table. x86-only.
521
405
  if (Config->Machine == I386)
522
71
    createSEHTable();
523
405
524
405
  // Create /guard:cf tables if requested.
525
405
  if (Config->GuardCF != GuardCFLevel::Off)
526
11
    createGuardCFTables();
527
405
}
528
529
// Create .idata section for the DLL-imported symbol table.
530
// The format of this section is inherently Windows-specific.
531
// IdataContents class abstracted away the details for us,
532
// so we just let it create chunks and add them to the section.
533
405
void Writer::createImportTables() {
534
405
  if (ImportFile::Instances.empty())
535
366
    return;
536
39
537
39
  // Initialize DLLOrder so that import entries are ordered in
538
39
  // the same order as in the command line. (That affects DLL
539
39
  // initialization order, and this ordering is MSVC-compatible.)
540
78
  
for (ImportFile *File : ImportFile::Instances)39
{
541
78
    if (!File->Live)
542
3
      continue;
543
75
544
75
    std::string DLL = StringRef(File->DLLName).lower();
545
75
    if (Config->DLLOrder.count(DLL) == 0)
546
37
      Config->DLLOrder[DLL] = Config->DLLOrder.size();
547
75
548
75
    if (File->ThunkSym) {
549
74
      if (!isa<DefinedImportThunk>(File->ThunkSym))
550
0
        fatal(toString(*File->ThunkSym) + " was replaced");
551
74
      DefinedImportThunk *Thunk = cast<DefinedImportThunk>(File->ThunkSym);
552
74
      if (File->ThunkLive)
553
71
        TextSec->addChunk(Thunk->getChunk());
554
74
    }
555
75
556
75
    if (File->ImpSym && !isa<DefinedImportData>(File->ImpSym))
557
0
      fatal(toString(*File->ImpSym) + " was replaced");
558
75
    DefinedImportData *ImpSym = cast_or_null<DefinedImportData>(File->ImpSym);
559
75
    if (Config->DelayLoads.count(StringRef(File->DLLName).lower())) {
560
6
      if (!File->ThunkSym)
561
0
        fatal("cannot delay-load " + toString(File) +
562
0
              " due to import of data: " + toString(*ImpSym));
563
6
      DelayIdata.add(ImpSym);
564
69
    } else {
565
69
      Idata.add(ImpSym);
566
69
    }
567
75
  }
568
39
569
39
  if (!Idata.empty())
570
33
    for (Chunk *C : Idata.getChunks())
571
368
      IdataSec->addChunk(C);
572
39
573
39
  if (!DelayIdata.empty()) {
574
3
    Defined *Helper = cast<Defined>(Config->DelayLoadHelper);
575
3
    DelayIdata.create(Helper);
576
3
    for (Chunk *C : DelayIdata.getChunks())
577
23
      DidatSec->addChunk(C);
578
3
    for (Chunk *C : DelayIdata.getDataChunks())
579
12
      DataSec->addChunk(C);
580
3
    for (Chunk *C : DelayIdata.getCodeChunks())
581
6
      TextSec->addChunk(C);
582
3
  }
583
39
}
584
585
405
void Writer::createExportTable() {
586
405
  if (Config->Exports.empty())
587
312
    return;
588
93
  for (Chunk *C : Edata.Chunks)
589
635
    EdataSec->addChunk(C);
590
93
}
591
592
// The Windows loader doesn't seem to like empty sections,
593
// so we remove them if any.
594
405
void Writer::removeEmptySections() {
595
4.56k
  auto IsEmpty = [](OutputSection *S) { return S->getVirtualSize() == 0; };
596
405
  OutputSections.erase(
597
405
      std::remove_if(OutputSections.begin(), OutputSections.end(), IsEmpty),
598
405
      OutputSections.end());
599
405
  uint32_t Idx = 1;
600
405
  for (OutputSection *Sec : OutputSections)
601
843
    Sec->SectionIndex = Idx++;
602
405
}
603
604
42
size_t Writer::addEntryToStringTable(StringRef Str) {
605
42
  assert(Str.size() > COFF::NameSize);
606
42
  size_t OffsetOfEntry = Strtab.size() + 4; // +4 for the size field
607
42
  Strtab.insert(Strtab.end(), Str.begin(), Str.end());
608
42
  Strtab.push_back('\0');
609
42
  return OffsetOfEntry;
610
42
}
611
612
307
Optional<coff_symbol16> Writer::createSymbol(Defined *Def) {
613
307
  coff_symbol16 Sym;
614
307
  switch (Def->kind()) {
615
307
  case Symbol::DefinedAbsoluteKind:
616
6
    Sym.Value = Def->getRVA();
617
6
    Sym.SectionNumber = IMAGE_SYM_ABSOLUTE;
618
6
    break;
619
307
  case Symbol::DefinedSyntheticKind:
620
5
    // Relative symbols are unrepresentable in a COFF symbol table.
621
5
    return None;
622
307
  default: {
623
296
    // Don't write symbols that won't be written to the output to the symbol
624
296
    // table.
625
296
    Chunk *C = Def->getChunk();
626
296
    if (!C)
627
1
      return None;
628
295
    OutputSection *OS = C->getOutputSection();
629
295
    if (!OS)
630
10
      return None;
631
285
632
285
    Sym.Value = Def->getRVA() - OS->getRVA();
633
285
    Sym.SectionNumber = OS->SectionIndex;
634
285
    break;
635
285
  }
636
291
  }
637
291
638
291
  StringRef Name = Def->getName();
639
291
  if (Name.size() > COFF::NameSize) {
640
24
    Sym.Name.Offset.Zeroes = 0;
641
24
    Sym.Name.Offset.Offset = addEntryToStringTable(Name);
642
267
  } else {
643
267
    memset(Sym.Name.ShortName, 0, COFF::NameSize);
644
267
    memcpy(Sym.Name.ShortName, Name.data(), Name.size());
645
267
  }
646
291
647
291
  if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
648
279
    COFFSymbolRef Ref = D->getCOFFSymbol();
649
279
    Sym.Type = Ref.getType();
650
279
    Sym.StorageClass = Ref.getStorageClass();
651
279
  } else {
652
12
    Sym.Type = IMAGE_SYM_TYPE_NULL;
653
12
    Sym.StorageClass = IMAGE_SYM_CLASS_EXTERNAL;
654
12
  }
655
291
  Sym.NumberOfAuxSymbols = 0;
656
291
  return Sym;
657
291
}
658
659
405
void Writer::createSymbolAndStringTable() {
660
405
  // PE/COFF images are limited to 8 byte section names. Longer names can be
661
405
  // supported by writing a non-standard string table, but this string table is
662
405
  // not mapped at runtime and the long names will therefore be inaccessible.
663
405
  // link.exe always truncates section names to 8 bytes, whereas binutils always
664
405
  // preserves long section names via the string table. LLD adopts a hybrid
665
405
  // solution where discardable sections have long names preserved and
666
405
  // non-discardable sections have their names truncated, to ensure that any
667
405
  // section which is mapped at runtime also has its name mapped at runtime.
668
843
  for (OutputSection *Sec : OutputSections) {
669
843
    if (Sec->Name.size() <= COFF::NameSize)
670
822
      continue;
671
21
    if ((Sec->Header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE) == 0)
672
3
      continue;
673
18
    Sec->setStringTableOff(addEntryToStringTable(Sec->Name));
674
18
  }
675
405
676
405
  if (Config->DebugDwarf || 
Config->DebugSymtab394
) {
677
13
    for (ObjFile *File : ObjFile::Instances) {
678
400
      for (Symbol *B : File->getSymbols()) {
679
400
        auto *D = dyn_cast_or_null<Defined>(B);
680
400
        if (!D || 
D->WrittenToSymtab307
)
681
93
          continue;
682
307
        D->WrittenToSymtab = true;
683
307
684
307
        if (Optional<coff_symbol16> Sym = createSymbol(D))
685
291
          OutputSymtab.push_back(*Sym);
686
307
      }
687
13
    }
688
13
  }
689
405
690
405
  if (OutputSymtab.empty() && 
Strtab.empty()392
)
691
386
    return;
692
19
693
19
  // We position the symbol table to be adjacent to the end of the last section.
694
19
  uint64_t FileOff = FileSize;
695
19
  PointerToSymbolTable = FileOff;
696
19
  FileOff += OutputSymtab.size() * sizeof(coff_symbol16);
697
19
  FileOff += 4 + Strtab.size();
698
19
  FileSize = alignTo(FileOff, SectorSize);
699
19
}
700
701
405
void Writer::mergeSections() {
702
405
  if (!PdataSec->getChunks().empty()) {
703
39
    FirstPdata = PdataSec->getChunks().front();
704
39
    LastPdata = PdataSec->getChunks().back();
705
39
  }
706
405
707
2.03k
  for (auto &P : Config->Merge) {
708
2.03k
    StringRef ToName = P.second;
709
2.03k
    if (P.first == ToName)
710
2
      continue;
711
2.03k
    StringSet<> Names;
712
2.03k
    while (1) {
713
2.03k
      if (!Names.insert(ToName).second)
714
0
        fatal("/merge: cycle found for section '" + P.first + "'");
715
2.03k
      auto I = Config->Merge.find(ToName);
716
2.03k
      if (I == Config->Merge.end())
717
2.03k
        break;
718
1
      ToName = I->second;
719
1
    }
720
2.03k
    OutputSection *From = findSection(P.first);
721
2.03k
    OutputSection *To = findSection(ToName);
722
2.03k
    if (!From)
723
366
      continue;
724
1.66k
    if (!To) {
725
3
      From->Name = ToName;
726
3
      continue;
727
3
    }
728
1.66k
    To->merge(From);
729
1.66k
  }
730
405
}
731
732
// Visits all sections to assign incremental, non-overlapping RVAs and
733
// file offsets.
734
405
void Writer::assignAddresses() {
735
405
  SizeOfHeaders = DOSStubSize + sizeof(PEMagic) + sizeof(coff_file_header) +
736
405
                  sizeof(data_directory) * NumberfOfDataDirectory +
737
405
                  sizeof(coff_section) * OutputSections.size();
738
405
  SizeOfHeaders +=
739
405
      Config->is64() ? 
sizeof(pe32plus_header)325
:
sizeof(pe32_header)80
;
740
405
  SizeOfHeaders = alignTo(SizeOfHeaders, SectorSize);
741
405
  uint64_t RVA = PageSize; // The first page is kept unmapped.
742
405
  FileSize = SizeOfHeaders;
743
405
744
4.56k
  for (OutputSection *Sec : OutputSections) {
745
4.56k
    if (Sec == RelocSec)
746
405
      addBaserels();
747
4.56k
    uint64_t RawSize = 0, VirtualSize = 0;
748
4.56k
    Sec->Header.VirtualAddress = RVA;
749
4.56k
    for (Chunk *C : Sec->getChunks()) {
750
2.68k
      VirtualSize = alignTo(VirtualSize, C->Alignment);
751
2.68k
      C->setRVA(RVA + VirtualSize);
752
2.68k
      C->OutputSectionOff = VirtualSize;
753
2.68k
      C->finalizeContents();
754
2.68k
      VirtualSize += C->getSize();
755
2.68k
      if (C->hasData())
756
2.39k
        RawSize = alignTo(VirtualSize, SectorSize);
757
2.68k
    }
758
4.56k
    if (VirtualSize > UINT32_MAX)
759
4.56k
      
error("section larger than 4 GiB: " + Sec->Name)1
;
760
4.56k
    Sec->Header.VirtualSize = VirtualSize;
761
4.56k
    Sec->Header.SizeOfRawData = RawSize;
762
4.56k
    if (RawSize != 0)
763
837
      Sec->Header.PointerToRawData = FileSize;
764
4.56k
    RVA += alignTo(VirtualSize, PageSize);
765
4.56k
    FileSize += alignTo(RawSize, SectorSize);
766
4.56k
  }
767
405
  SizeOfImage = alignTo(RVA, PageSize);
768
405
}
769
770
405
template <typename PEHeaderTy> void Writer::writeHeader() {
771
405
  // Write DOS header. For backwards compatibility, the first part of a PE/COFF
772
405
  // executable consists of an MS-DOS MZ executable. If the executable is run
773
405
  // under DOS, that program gets run (usually to just print an error message).
774
405
  // When run under Windows, the loader looks at AddressOfNewExeHeader and uses
775
405
  // the PE header instead.
776
405
  uint8_t *Buf = Buffer->getBufferStart();
777
405
  auto *DOS = reinterpret_cast<dos_header *>(Buf);
778
405
  Buf += sizeof(dos_header);
779
405
  DOS->Magic[0] = 'M';
780
405
  DOS->Magic[1] = 'Z';
781
405
  DOS->UsedBytesInTheLastPage = DOSStubSize % 512;
782
405
  DOS->FileSizeInPages = divideCeil(DOSStubSize, 512);
783
405
  DOS->HeaderSizeInParagraphs = sizeof(dos_header) / 16;
784
405
785
405
  DOS->AddressOfRelocationTable = sizeof(dos_header);
786
405
  DOS->AddressOfNewExeHeader = DOSStubSize;
787
405
788
405
  // Write DOS program.
789
405
  memcpy(Buf, DOSProgram, sizeof(DOSProgram));
790
405
  Buf += sizeof(DOSProgram);
791
405
792
405
  // Write PE magic
793
405
  memcpy(Buf, PEMagic, sizeof(PEMagic));
794
405
  Buf += sizeof(PEMagic);
795
405
796
405
  // Write COFF header
797
405
  auto *COFF = reinterpret_cast<coff_file_header *>(Buf);
798
405
  Buf += sizeof(*COFF);
799
405
  COFF->Machine = Config->Machine;
800
405
  COFF->NumberOfSections = OutputSections.size();
801
405
  COFF->Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
802
405
  if (Config->LargeAddressAware)
803
326
    COFF->Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
804
405
  if (!Config->is64())
805
80
    COFF->Characteristics |= IMAGE_FILE_32BIT_MACHINE;
806
405
  if (Config->DLL)
807
113
    COFF->Characteristics |= IMAGE_FILE_DLL;
808
405
  if (!Config->Relocatable)
809
4
    COFF->Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
810
405
  COFF->SizeOfOptionalHeader =
811
405
      sizeof(PEHeaderTy) + sizeof(data_directory) * NumberfOfDataDirectory;
812
405
813
405
  // Write PE header
814
405
  auto *PE = reinterpret_cast<PEHeaderTy *>(Buf);
815
405
  Buf += sizeof(*PE);
816
405
  PE->Magic = Config->is64() ? 
PE32Header::PE32_PLUS325
:
PE32Header::PE3280
;
817
405
818
405
  // If {Major,Minor}LinkerVersion is left at 0.0, then for some
819
405
  // reason signing the resulting PE file with Authenticode produces a
820
405
  // signature that fails to validate on Windows 7 (but is OK on 10).
821
405
  // Set it to 14.0, which is what VS2015 outputs, and which avoids
822
405
  // that problem.
823
405
  PE->MajorLinkerVersion = 14;
824
405
  PE->MinorLinkerVersion = 0;
825
405
826
405
  PE->ImageBase = Config->ImageBase;
827
405
  PE->SectionAlignment = PageSize;
828
405
  PE->FileAlignment = SectorSize;
829
405
  PE->MajorImageVersion = Config->MajorImageVersion;
830
405
  PE->MinorImageVersion = Config->MinorImageVersion;
831
405
  PE->MajorOperatingSystemVersion = Config->MajorOSVersion;
832
405
  PE->MinorOperatingSystemVersion = Config->MinorOSVersion;
833
405
  PE->MajorSubsystemVersion = Config->MajorOSVersion;
834
405
  PE->MinorSubsystemVersion = Config->MinorOSVersion;
835
405
  PE->Subsystem = Config->Subsystem;
836
405
  PE->SizeOfImage = SizeOfImage;
837
405
  PE->SizeOfHeaders = SizeOfHeaders;
838
405
  if (!Config->NoEntry) {
839
396
    Defined *Entry = cast<Defined>(Config->Entry);
840
396
    PE->AddressOfEntryPoint = Entry->getRVA();
841
396
    // Pointer to thumb code must have the LSB set, so adjust it.
842
396
    if (Config->Machine == ARMNT)
843
9
      PE->AddressOfEntryPoint |= 1;
844
396
  }
845
405
  PE->SizeOfStackReserve = Config->StackReserve;
846
405
  PE->SizeOfStackCommit = Config->StackCommit;
847
405
  PE->SizeOfHeapReserve = Config->HeapReserve;
848
405
  PE->SizeOfHeapCommit = Config->HeapCommit;
849
405
  if (Config->AppContainer)
850
1
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_APPCONTAINER;
851
405
  if (Config->DynamicBase)
852
401
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
853
405
  if (Config->HighEntropyVA)
854
324
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
855
405
  if (!Config->AllowBind)
856
1
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_BIND;
857
405
  if (Config->NxCompat)
858
404
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
859
405
  if (!Config->AllowIsolation)
860
1
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION;
861
405
  if (Config->GuardCF != GuardCFLevel::Off)
862
11
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_GUARD_CF;
863
405
  if (Config->IntegrityCheck)
864
1
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY;
865
405
  if (SetNoSEHCharacteristic)
866
68
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_SEH;
867
405
  if (Config->TerminalServerAware)
868
291
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE;
869
405
  PE->NumberOfRvaAndSize = NumberfOfDataDirectory;
870
405
  if (TextSec->getVirtualSize()) {
871
381
    PE->BaseOfCode = TextSec->getRVA();
872
381
    PE->SizeOfCode = TextSec->getRawSize();
873
381
  }
874
405
  PE->SizeOfInitializedData = getSizeOfInitializedData();
875
405
876
405
  // Write data directory
877
405
  auto *Dir = reinterpret_cast<data_directory *>(Buf);
878
405
  Buf += sizeof(*Dir) * NumberfOfDataDirectory;
879
405
  if (!Config->Exports.empty()) {
880
93
    Dir[EXPORT_TABLE].RelativeVirtualAddress = Edata.getRVA();
881
93
    Dir[EXPORT_TABLE].Size = Edata.getSize();
882
93
  }
883
405
  if (!Idata.empty()) {
884
33
    Dir[IMPORT_TABLE].RelativeVirtualAddress = Idata.getDirRVA();
885
33
    Dir[IMPORT_TABLE].Size = Idata.getDirSize();
886
33
    Dir[IAT].RelativeVirtualAddress = Idata.getIATRVA();
887
33
    Dir[IAT].Size = Idata.getIATSize();
888
33
  }
889
405
  if (RsrcSec->getVirtualSize()) {
890
4
    Dir[RESOURCE_TABLE].RelativeVirtualAddress = RsrcSec->getRVA();
891
4
    Dir[RESOURCE_TABLE].Size = RsrcSec->getVirtualSize();
892
4
  }
893
405
  if (FirstPdata) {
894
39
    Dir[EXCEPTION_TABLE].RelativeVirtualAddress = FirstPdata->getRVA();
895
39
    Dir[EXCEPTION_TABLE].Size =
896
39
        LastPdata->getRVA() + LastPdata->getSize() - FirstPdata->getRVA();
897
39
  }
898
405
  if (RelocSec->getVirtualSize()) {
899
64
    Dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = RelocSec->getRVA();
900
64
    Dir[BASE_RELOCATION_TABLE].Size = RelocSec->getVirtualSize();
901
64
  }
902
405
  if (Symbol *Sym = Symtab->findUnderscore("_tls_used")) {
903
2
    if (Defined *B = dyn_cast<Defined>(Sym)) {
904
2
      Dir[TLS_TABLE].RelativeVirtualAddress = B->getRVA();
905
2
      Dir[TLS_TABLE].Size = Config->is64()
906
2
                                ? 
sizeof(object::coff_tls_directory64)1
907
2
                                : 
sizeof(object::coff_tls_directory32)1
;
908
2
    }
909
2
  }
910
405
  if (Config->Debug) {
911
80
    Dir[DEBUG_DIRECTORY].RelativeVirtualAddress = DebugDirectory->getRVA();
912
80
    Dir[DEBUG_DIRECTORY].Size = DebugDirectory->getSize();
913
80
  }
914
405
  if (Symbol *Sym = Symtab->findUnderscore("_load_config_used")) {
915
18
    if (auto *B = dyn_cast<DefinedRegular>(Sym)) {
916
18
      SectionChunk *SC = B->getChunk();
917
18
      assert(B->getRVA() >= SC->getRVA());
918
18
      uint64_t OffsetInChunk = B->getRVA() - SC->getRVA();
919
18
      if (!SC->hasData() || OffsetInChunk + 4 > SC->getSize())
920
0
        fatal("_load_config_used is malformed");
921
18
922
18
      ArrayRef<uint8_t> SecContents = SC->getContents();
923
18
      uint32_t LoadConfigSize =
924
18
          *reinterpret_cast<const ulittle32_t *>(&SecContents[OffsetInChunk]);
925
18
      if (OffsetInChunk + LoadConfigSize > SC->getSize())
926
0
        fatal("_load_config_used is too large");
927
18
      Dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = B->getRVA();
928
18
      Dir[LOAD_CONFIG_TABLE].Size = LoadConfigSize;
929
18
    }
930
18
  }
931
405
  if (!DelayIdata.empty()) {
932
3
    Dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
933
3
        DelayIdata.getDirRVA();
934
3
    Dir[DELAY_IMPORT_DESCRIPTOR].Size = DelayIdata.getDirSize();
935
3
  }
936
405
937
405
  // Write section table
938
843
  for (OutputSection *Sec : OutputSections) {
939
843
    Sec->writeHeaderTo(Buf);
940
843
    Buf += sizeof(coff_section);
941
843
  }
942
405
  SectionTable = ArrayRef<uint8_t>(
943
405
      Buf - OutputSections.size() * sizeof(coff_section), Buf);
944
405
945
405
  if (OutputSymtab.empty() && 
Strtab.empty()392
)
946
386
    return;
947
19
948
19
  COFF->PointerToSymbolTable = PointerToSymbolTable;
949
19
  uint32_t NumberOfSymbols = OutputSymtab.size();
950
19
  COFF->NumberOfSymbols = NumberOfSymbols;
951
19
  auto *SymbolTable = reinterpret_cast<coff_symbol16 *>(
952
19
      Buffer->getBufferStart() + COFF->PointerToSymbolTable);
953
310
  for (size_t I = 0; I != NumberOfSymbols; 
++I291
)
954
291
    SymbolTable[I] = OutputSymtab[I];
955
19
  // Create the string table, it follows immediately after the symbol table.
956
19
  // The first 4 bytes is length including itself.
957
19
  Buf = reinterpret_cast<uint8_t *>(&SymbolTable[NumberOfSymbols]);
958
19
  write32le(Buf, Strtab.size() + 4);
959
19
  if (!Strtab.empty())
960
13
    memcpy(Buf + 4, Strtab.data(), Strtab.size());
961
19
}
Writer.cpp:void (anonymous namespace)::Writer::writeHeader<llvm::object::pe32plus_header>()
Line
Count
Source
770
325
template <typename PEHeaderTy> void Writer::writeHeader() {
771
325
  // Write DOS header. For backwards compatibility, the first part of a PE/COFF
772
325
  // executable consists of an MS-DOS MZ executable. If the executable is run
773
325
  // under DOS, that program gets run (usually to just print an error message).
774
325
  // When run under Windows, the loader looks at AddressOfNewExeHeader and uses
775
325
  // the PE header instead.
776
325
  uint8_t *Buf = Buffer->getBufferStart();
777
325
  auto *DOS = reinterpret_cast<dos_header *>(Buf);
778
325
  Buf += sizeof(dos_header);
779
325
  DOS->Magic[0] = 'M';
780
325
  DOS->Magic[1] = 'Z';
781
325
  DOS->UsedBytesInTheLastPage = DOSStubSize % 512;
782
325
  DOS->FileSizeInPages = divideCeil(DOSStubSize, 512);
783
325
  DOS->HeaderSizeInParagraphs = sizeof(dos_header) / 16;
784
325
785
325
  DOS->AddressOfRelocationTable = sizeof(dos_header);
786
325
  DOS->AddressOfNewExeHeader = DOSStubSize;
787
325
788
325
  // Write DOS program.
789
325
  memcpy(Buf, DOSProgram, sizeof(DOSProgram));
790
325
  Buf += sizeof(DOSProgram);
791
325
792
325
  // Write PE magic
793
325
  memcpy(Buf, PEMagic, sizeof(PEMagic));
794
325
  Buf += sizeof(PEMagic);
795
325
796
325
  // Write COFF header
797
325
  auto *COFF = reinterpret_cast<coff_file_header *>(Buf);
798
325
  Buf += sizeof(*COFF);
799
325
  COFF->Machine = Config->Machine;
800
325
  COFF->NumberOfSections = OutputSections.size();
801
325
  COFF->Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
802
325
  if (Config->LargeAddressAware)
803
325
    COFF->Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
804
325
  if (!Config->is64())
805
0
    COFF->Characteristics |= IMAGE_FILE_32BIT_MACHINE;
806
325
  if (Config->DLL)
807
86
    COFF->Characteristics |= IMAGE_FILE_DLL;
808
325
  if (!Config->Relocatable)
809
2
    COFF->Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
810
325
  COFF->SizeOfOptionalHeader =
811
325
      sizeof(PEHeaderTy) + sizeof(data_directory) * NumberfOfDataDirectory;
812
325
813
325
  // Write PE header
814
325
  auto *PE = reinterpret_cast<PEHeaderTy *>(Buf);
815
325
  Buf += sizeof(*PE);
816
325
  PE->Magic = Config->is64() ? PE32Header::PE32_PLUS : 
PE32Header::PE320
;
817
325
818
325
  // If {Major,Minor}LinkerVersion is left at 0.0, then for some
819
325
  // reason signing the resulting PE file with Authenticode produces a
820
325
  // signature that fails to validate on Windows 7 (but is OK on 10).
821
325
  // Set it to 14.0, which is what VS2015 outputs, and which avoids
822
325
  // that problem.
823
325
  PE->MajorLinkerVersion = 14;
824
325
  PE->MinorLinkerVersion = 0;
825
325
826
325
  PE->ImageBase = Config->ImageBase;
827
325
  PE->SectionAlignment = PageSize;
828
325
  PE->FileAlignment = SectorSize;
829
325
  PE->MajorImageVersion = Config->MajorImageVersion;
830
325
  PE->MinorImageVersion = Config->MinorImageVersion;
831
325
  PE->MajorOperatingSystemVersion = Config->MajorOSVersion;
832
325
  PE->MinorOperatingSystemVersion = Config->MinorOSVersion;
833
325
  PE->MajorSubsystemVersion = Config->MajorOSVersion;
834
325
  PE->MinorSubsystemVersion = Config->MinorOSVersion;
835
325
  PE->Subsystem = Config->Subsystem;
836
325
  PE->SizeOfImage = SizeOfImage;
837
325
  PE->SizeOfHeaders = SizeOfHeaders;
838
325
  if (!Config->NoEntry) {
839
317
    Defined *Entry = cast<Defined>(Config->Entry);
840
317
    PE->AddressOfEntryPoint = Entry->getRVA();
841
317
    // Pointer to thumb code must have the LSB set, so adjust it.
842
317
    if (Config->Machine == ARMNT)
843
0
      PE->AddressOfEntryPoint |= 1;
844
317
  }
845
325
  PE->SizeOfStackReserve = Config->StackReserve;
846
325
  PE->SizeOfStackCommit = Config->StackCommit;
847
325
  PE->SizeOfHeapReserve = Config->HeapReserve;
848
325
  PE->SizeOfHeapCommit = Config->HeapCommit;
849
325
  if (Config->AppContainer)
850
0
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_APPCONTAINER;
851
325
  if (Config->DynamicBase)
852
323
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
853
325
  if (Config->HighEntropyVA)
854
324
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
855
325
  if (!Config->AllowBind)
856
1
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_BIND;
857
325
  if (Config->NxCompat)
858
324
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
859
325
  if (!Config->AllowIsolation)
860
1
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION;
861
325
  if (Config->GuardCF != GuardCFLevel::Off)
862
10
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_GUARD_CF;
863
325
  if (Config->IntegrityCheck)
864
1
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY;
865
325
  if (SetNoSEHCharacteristic)
866
0
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_SEH;
867
325
  if (Config->TerminalServerAware)
868
238
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE;
869
325
  PE->NumberOfRvaAndSize = NumberfOfDataDirectory;
870
325
  if (TextSec->getVirtualSize()) {
871
307
    PE->BaseOfCode = TextSec->getRVA();
872
307
    PE->SizeOfCode = TextSec->getRawSize();
873
307
  }
874
325
  PE->SizeOfInitializedData = getSizeOfInitializedData();
875
325
876
325
  // Write data directory
877
325
  auto *Dir = reinterpret_cast<data_directory *>(Buf);
878
325
  Buf += sizeof(*Dir) * NumberfOfDataDirectory;
879
325
  if (!Config->Exports.empty()) {
880
71
    Dir[EXPORT_TABLE].RelativeVirtualAddress = Edata.getRVA();
881
71
    Dir[EXPORT_TABLE].Size = Edata.getSize();
882
71
  }
883
325
  if (!Idata.empty()) {
884
22
    Dir[IMPORT_TABLE].RelativeVirtualAddress = Idata.getDirRVA();
885
22
    Dir[IMPORT_TABLE].Size = Idata.getDirSize();
886
22
    Dir[IAT].RelativeVirtualAddress = Idata.getIATRVA();
887
22
    Dir[IAT].Size = Idata.getIATSize();
888
22
  }
889
325
  if (RsrcSec->getVirtualSize()) {
890
4
    Dir[RESOURCE_TABLE].RelativeVirtualAddress = RsrcSec->getRVA();
891
4
    Dir[RESOURCE_TABLE].Size = RsrcSec->getVirtualSize();
892
4
  }
893
325
  if (FirstPdata) {
894
39
    Dir[EXCEPTION_TABLE].RelativeVirtualAddress = FirstPdata->getRVA();
895
39
    Dir[EXCEPTION_TABLE].Size =
896
39
        LastPdata->getRVA() + LastPdata->getSize() - FirstPdata->getRVA();
897
39
  }
898
325
  if (RelocSec->getVirtualSize()) {
899
36
    Dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = RelocSec->getRVA();
900
36
    Dir[BASE_RELOCATION_TABLE].Size = RelocSec->getVirtualSize();
901
36
  }
902
325
  if (Symbol *Sym = Symtab->findUnderscore("_tls_used")) {
903
1
    if (Defined *B = dyn_cast<Defined>(Sym)) {
904
1
      Dir[TLS_TABLE].RelativeVirtualAddress = B->getRVA();
905
1
      Dir[TLS_TABLE].Size = Config->is64()
906
1
                                ? sizeof(object::coff_tls_directory64)
907
1
                                : 
sizeof(object::coff_tls_directory32)0
;
908
1
    }
909
1
  }
910
325
  if (Config->Debug) {
911
64
    Dir[DEBUG_DIRECTORY].RelativeVirtualAddress = DebugDirectory->getRVA();
912
64
    Dir[DEBUG_DIRECTORY].Size = DebugDirectory->getSize();
913
64
  }
914
325
  if (Symbol *Sym = Symtab->findUnderscore("_load_config_used")) {
915
12
    if (auto *B = dyn_cast<DefinedRegular>(Sym)) {
916
12
      SectionChunk *SC = B->getChunk();
917
12
      assert(B->getRVA() >= SC->getRVA());
918
12
      uint64_t OffsetInChunk = B->getRVA() - SC->getRVA();
919
12
      if (!SC->hasData() || OffsetInChunk + 4 > SC->getSize())
920
0
        fatal("_load_config_used is malformed");
921
12
922
12
      ArrayRef<uint8_t> SecContents = SC->getContents();
923
12
      uint32_t LoadConfigSize =
924
12
          *reinterpret_cast<const ulittle32_t *>(&SecContents[OffsetInChunk]);
925
12
      if (OffsetInChunk + LoadConfigSize > SC->getSize())
926
0
        fatal("_load_config_used is too large");
927
12
      Dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = B->getRVA();
928
12
      Dir[LOAD_CONFIG_TABLE].Size = LoadConfigSize;
929
12
    }
930
12
  }
931
325
  if (!DelayIdata.empty()) {
932
1
    Dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
933
1
        DelayIdata.getDirRVA();
934
1
    Dir[DELAY_IMPORT_DESCRIPTOR].Size = DelayIdata.getDirSize();
935
1
  }
936
325
937
325
  // Write section table
938
650
  for (OutputSection *Sec : OutputSections) {
939
650
    Sec->writeHeaderTo(Buf);
940
650
    Buf += sizeof(coff_section);
941
650
  }
942
325
  SectionTable = ArrayRef<uint8_t>(
943
325
      Buf - OutputSections.size() * sizeof(coff_section), Buf);
944
325
945
325
  if (OutputSymtab.empty() && 
Strtab.empty()315
)
946
310
    return;
947
15
948
15
  COFF->PointerToSymbolTable = PointerToSymbolTable;
949
15
  uint32_t NumberOfSymbols = OutputSymtab.size();
950
15
  COFF->NumberOfSymbols = NumberOfSymbols;
951
15
  auto *SymbolTable = reinterpret_cast<coff_symbol16 *>(
952
15
      Buffer->getBufferStart() + COFF->PointerToSymbolTable);
953
278
  for (size_t I = 0; I != NumberOfSymbols; 
++I263
)
954
263
    SymbolTable[I] = OutputSymtab[I];
955
15
  // Create the string table, it follows immediately after the symbol table.
956
15
  // The first 4 bytes is length including itself.
957
15
  Buf = reinterpret_cast<uint8_t *>(&SymbolTable[NumberOfSymbols]);
958
15
  write32le(Buf, Strtab.size() + 4);
959
15
  if (!Strtab.empty())
960
10
    memcpy(Buf + 4, Strtab.data(), Strtab.size());
961
15
}
Writer.cpp:void (anonymous namespace)::Writer::writeHeader<llvm::object::pe32_header>()
Line
Count
Source
770
80
template <typename PEHeaderTy> void Writer::writeHeader() {
771
80
  // Write DOS header. For backwards compatibility, the first part of a PE/COFF
772
80
  // executable consists of an MS-DOS MZ executable. If the executable is run
773
80
  // under DOS, that program gets run (usually to just print an error message).
774
80
  // When run under Windows, the loader looks at AddressOfNewExeHeader and uses
775
80
  // the PE header instead.
776
80
  uint8_t *Buf = Buffer->getBufferStart();
777
80
  auto *DOS = reinterpret_cast<dos_header *>(Buf);
778
80
  Buf += sizeof(dos_header);
779
80
  DOS->Magic[0] = 'M';
780
80
  DOS->Magic[1] = 'Z';
781
80
  DOS->UsedBytesInTheLastPage = DOSStubSize % 512;
782
80
  DOS->FileSizeInPages = divideCeil(DOSStubSize, 512);
783
80
  DOS->HeaderSizeInParagraphs = sizeof(dos_header) / 16;
784
80
785
80
  DOS->AddressOfRelocationTable = sizeof(dos_header);
786
80
  DOS->AddressOfNewExeHeader = DOSStubSize;
787
80
788
80
  // Write DOS program.
789
80
  memcpy(Buf, DOSProgram, sizeof(DOSProgram));
790
80
  Buf += sizeof(DOSProgram);
791
80
792
80
  // Write PE magic
793
80
  memcpy(Buf, PEMagic, sizeof(PEMagic));
794
80
  Buf += sizeof(PEMagic);
795
80
796
80
  // Write COFF header
797
80
  auto *COFF = reinterpret_cast<coff_file_header *>(Buf);
798
80
  Buf += sizeof(*COFF);
799
80
  COFF->Machine = Config->Machine;
800
80
  COFF->NumberOfSections = OutputSections.size();
801
80
  COFF->Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
802
80
  if (Config->LargeAddressAware)
803
1
    COFF->Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
804
80
  if (!Config->is64())
805
80
    COFF->Characteristics |= IMAGE_FILE_32BIT_MACHINE;
806
80
  if (Config->DLL)
807
27
    COFF->Characteristics |= IMAGE_FILE_DLL;
808
80
  if (!Config->Relocatable)
809
2
    COFF->Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
810
80
  COFF->SizeOfOptionalHeader =
811
80
      sizeof(PEHeaderTy) + sizeof(data_directory) * NumberfOfDataDirectory;
812
80
813
80
  // Write PE header
814
80
  auto *PE = reinterpret_cast<PEHeaderTy *>(Buf);
815
80
  Buf += sizeof(*PE);
816
80
  PE->Magic = Config->is64() ? 
PE32Header::PE32_PLUS0
: PE32Header::PE32;
817
80
818
80
  // If {Major,Minor}LinkerVersion is left at 0.0, then for some
819
80
  // reason signing the resulting PE file with Authenticode produces a
820
80
  // signature that fails to validate on Windows 7 (but is OK on 10).
821
80
  // Set it to 14.0, which is what VS2015 outputs, and which avoids
822
80
  // that problem.
823
80
  PE->MajorLinkerVersion = 14;
824
80
  PE->MinorLinkerVersion = 0;
825
80
826
80
  PE->ImageBase = Config->ImageBase;
827
80
  PE->SectionAlignment = PageSize;
828
80
  PE->FileAlignment = SectorSize;
829
80
  PE->MajorImageVersion = Config->MajorImageVersion;
830
80
  PE->MinorImageVersion = Config->MinorImageVersion;
831
80
  PE->MajorOperatingSystemVersion = Config->MajorOSVersion;
832
80
  PE->MinorOperatingSystemVersion = Config->MinorOSVersion;
833
80
  PE->MajorSubsystemVersion = Config->MajorOSVersion;
834
80
  PE->MinorSubsystemVersion = Config->MinorOSVersion;
835
80
  PE->Subsystem = Config->Subsystem;
836
80
  PE->SizeOfImage = SizeOfImage;
837
80
  PE->SizeOfHeaders = SizeOfHeaders;
838
80
  if (!Config->NoEntry) {
839
79
    Defined *Entry = cast<Defined>(Config->Entry);
840
79
    PE->AddressOfEntryPoint = Entry->getRVA();
841
79
    // Pointer to thumb code must have the LSB set, so adjust it.
842
79
    if (Config->Machine == ARMNT)
843
9
      PE->AddressOfEntryPoint |= 1;
844
79
  }
845
80
  PE->SizeOfStackReserve = Config->StackReserve;
846
80
  PE->SizeOfStackCommit = Config->StackCommit;
847
80
  PE->SizeOfHeapReserve = Config->HeapReserve;
848
80
  PE->SizeOfHeapCommit = Config->HeapCommit;
849
80
  if (Config->AppContainer)
850
1
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_APPCONTAINER;
851
80
  if (Config->DynamicBase)
852
78
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
853
80
  if (Config->HighEntropyVA)
854
0
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
855
80
  if (!Config->AllowBind)
856
0
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_BIND;
857
80
  if (Config->NxCompat)
858
80
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
859
80
  if (!Config->AllowIsolation)
860
0
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION;
861
80
  if (Config->GuardCF != GuardCFLevel::Off)
862
1
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_GUARD_CF;
863
80
  if (Config->IntegrityCheck)
864
0
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY;
865
80
  if (SetNoSEHCharacteristic)
866
68
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_SEH;
867
80
  if (Config->TerminalServerAware)
868
53
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE;
869
80
  PE->NumberOfRvaAndSize = NumberfOfDataDirectory;
870
80
  if (TextSec->getVirtualSize()) {
871
74
    PE->BaseOfCode = TextSec->getRVA();
872
74
    PE->SizeOfCode = TextSec->getRawSize();
873
74
  }
874
80
  PE->SizeOfInitializedData = getSizeOfInitializedData();
875
80
876
80
  // Write data directory
877
80
  auto *Dir = reinterpret_cast<data_directory *>(Buf);
878
80
  Buf += sizeof(*Dir) * NumberfOfDataDirectory;
879
80
  if (!Config->Exports.empty()) {
880
22
    Dir[EXPORT_TABLE].RelativeVirtualAddress = Edata.getRVA();
881
22
    Dir[EXPORT_TABLE].Size = Edata.getSize();
882
22
  }
883
80
  if (!Idata.empty()) {
884
11
    Dir[IMPORT_TABLE].RelativeVirtualAddress = Idata.getDirRVA();
885
11
    Dir[IMPORT_TABLE].Size = Idata.getDirSize();
886
11
    Dir[IAT].RelativeVirtualAddress = Idata.getIATRVA();
887
11
    Dir[IAT].Size = Idata.getIATSize();
888
11
  }
889
80
  if (RsrcSec->getVirtualSize()) {
890
0
    Dir[RESOURCE_TABLE].RelativeVirtualAddress = RsrcSec->getRVA();
891
0
    Dir[RESOURCE_TABLE].Size = RsrcSec->getVirtualSize();
892
0
  }
893
80
  if (FirstPdata) {
894
0
    Dir[EXCEPTION_TABLE].RelativeVirtualAddress = FirstPdata->getRVA();
895
0
    Dir[EXCEPTION_TABLE].Size =
896
0
        LastPdata->getRVA() + LastPdata->getSize() - FirstPdata->getRVA();
897
0
  }
898
80
  if (RelocSec->getVirtualSize()) {
899
28
    Dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = RelocSec->getRVA();
900
28
    Dir[BASE_RELOCATION_TABLE].Size = RelocSec->getVirtualSize();
901
28
  }
902
80
  if (Symbol *Sym = Symtab->findUnderscore("_tls_used")) {
903
1
    if (Defined *B = dyn_cast<Defined>(Sym)) {
904
1
      Dir[TLS_TABLE].RelativeVirtualAddress = B->getRVA();
905
1
      Dir[TLS_TABLE].Size = Config->is64()
906
1
                                ? 
sizeof(object::coff_tls_directory64)0
907
1
                                : sizeof(object::coff_tls_directory32);
908
1
    }
909
1
  }
910
80
  if (Config->Debug) {
911
16
    Dir[DEBUG_DIRECTORY].RelativeVirtualAddress = DebugDirectory->getRVA();
912
16
    Dir[DEBUG_DIRECTORY].Size = DebugDirectory->getSize();
913
16
  }
914
80
  if (Symbol *Sym = Symtab->findUnderscore("_load_config_used")) {
915
6
    if (auto *B = dyn_cast<DefinedRegular>(Sym)) {
916
6
      SectionChunk *SC = B->getChunk();
917
6
      assert(B->getRVA() >= SC->getRVA());
918
6
      uint64_t OffsetInChunk = B->getRVA() - SC->getRVA();
919
6
      if (!SC->hasData() || OffsetInChunk + 4 > SC->getSize())
920
0
        fatal("_load_config_used is malformed");
921
6
922
6
      ArrayRef<uint8_t> SecContents = SC->getContents();
923
6
      uint32_t LoadConfigSize =
924
6
          *reinterpret_cast<const ulittle32_t *>(&SecContents[OffsetInChunk]);
925
6
      if (OffsetInChunk + LoadConfigSize > SC->getSize())
926
0
        fatal("_load_config_used is too large");
927
6
      Dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = B->getRVA();
928
6
      Dir[LOAD_CONFIG_TABLE].Size = LoadConfigSize;
929
6
    }
930
6
  }
931
80
  if (!DelayIdata.empty()) {
932
2
    Dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
933
2
        DelayIdata.getDirRVA();
934
2
    Dir[DELAY_IMPORT_DESCRIPTOR].Size = DelayIdata.getDirSize();
935
2
  }
936
80
937
80
  // Write section table
938
193
  for (OutputSection *Sec : OutputSections) {
939
193
    Sec->writeHeaderTo(Buf);
940
193
    Buf += sizeof(coff_section);
941
193
  }
942
80
  SectionTable = ArrayRef<uint8_t>(
943
80
      Buf - OutputSections.size() * sizeof(coff_section), Buf);
944
80
945
80
  if (OutputSymtab.empty() && 
Strtab.empty()77
)
946
76
    return;
947
4
948
4
  COFF->PointerToSymbolTable = PointerToSymbolTable;
949
4
  uint32_t NumberOfSymbols = OutputSymtab.size();
950
4
  COFF->NumberOfSymbols = NumberOfSymbols;
951
4
  auto *SymbolTable = reinterpret_cast<coff_symbol16 *>(
952
4
      Buffer->getBufferStart() + COFF->PointerToSymbolTable);
953
32
  for (size_t I = 0; I != NumberOfSymbols; 
++I28
)
954
28
    SymbolTable[I] = OutputSymtab[I];
955
4
  // Create the string table, it follows immediately after the symbol table.
956
4
  // The first 4 bytes is length including itself.
957
4
  Buf = reinterpret_cast<uint8_t *>(&SymbolTable[NumberOfSymbols]);
958
4
  write32le(Buf, Strtab.size() + 4);
959
4
  if (!Strtab.empty())
960
3
    memcpy(Buf + 4, Strtab.data(), Strtab.size());
961
4
}
962
963
405
void Writer::openFile(StringRef Path) {
964
405
  Buffer = CHECK(
965
405
      FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable),
966
405
      "failed to open " + Path);
967
405
}
968
969
71
void Writer::createSEHTable() {
970
71
  // Set the no SEH characteristic on x86 binaries unless we find exception
971
71
  // handlers.
972
71
  SetNoSEHCharacteristic = true;
973
71
974
71
  SymbolRVASet Handlers;
975
75
  for (ObjFile *File : ObjFile::Instances) {
976
75
    // FIXME: We should error here instead of earlier unless /safeseh:no was
977
75
    // passed.
978
75
    if (!File->hasSafeSEH())
979
46
      return;
980
29
981
29
    markSymbolsForRVATable(File, File->getSXDataChunks(), Handlers);
982
29
  }
983
71
984
71
  // Remove the "no SEH" characteristic if all object files were built with
985
71
  // safeseh, we found some exception handlers, and there is a load config in
986
71
  // the object.
987
71
  SetNoSEHCharacteristic =
988
25
      Handlers.empty() || 
!Symtab->findUnderscore("_load_config_used")6
;
989
25
990
25
  maybeAddRVATable(std::move(Handlers), "__safe_se_handler_table",
991
25
                   "__safe_se_handler_count");
992
25
}
993
994
// Add a symbol to an RVA set. Two symbols may have the same RVA, but an RVA set
995
// cannot contain duplicates. Therefore, the set is uniqued by Chunk and the
996
// symbol's offset into that Chunk.
997
36
static void addSymbolToRVASet(SymbolRVASet &RVASet, Defined *S) {
998
36
  Chunk *C = S->getChunk();
999
36
  if (auto *SC = dyn_cast<SectionChunk>(C))
1000
35
    C = SC->Repl; // Look through ICF replacement.
1001
36
  uint32_t Off = S->getRVA() - (C ? C->getRVA() : 
00
);
1002
36
  RVASet.insert({C, Off});
1003
36
}
1004
1005
// Visit all relocations from all section contributions of this object file and
1006
// mark the relocation target as address-taken.
1007
static void markSymbolsWithRelocations(ObjFile *File,
1008
6
                                       SymbolRVASet &UsedSymbols) {
1009
37
  for (Chunk *C : File->getChunks()) {
1010
37
    // We only care about live section chunks. Common chunks and other chunks
1011
37
    // don't generally contain relocations.
1012
37
    SectionChunk *SC = dyn_cast<SectionChunk>(C);
1013
37
    if (!SC || !SC->isLive())
1014
0
      continue;
1015
37
1016
37
    for (const coff_relocation &Reloc : SC->Relocs) {
1017
27
      if (Config->Machine == I386 && 
Reloc.Type == COFF::IMAGE_REL_I386_REL327
)
1018
1
        // Ignore relative relocations on x86. On x86_64 they can't be ignored
1019
1
        // since they're also used to compute absolute addresses.
1020
1
        continue;
1021
26
1022
26
      Symbol *Ref = SC->File->getSymbol(Reloc.SymbolTableIndex);
1023
26
      if (auto *D = dyn_cast_or_null<DefinedCOFF>(Ref)) {
1024
13
        if (D->getCOFFSymbol().getComplexType() != COFF::IMAGE_SYM_DTYPE_FUNCTION)
1025
5
          // Ignore relocations against non-functions (e.g. labels).
1026
5
          continue;
1027
8
1028
8
        // Mark the symbol if it's in an executable section.
1029
8
        Chunk *RefChunk = D->getChunk();
1030
8
        OutputSection *OS = RefChunk ? RefChunk->getOutputSection() : 
nullptr0
;
1031
8
        if (OS && OS->Header.Characteristics & IMAGE_SCN_MEM_EXECUTE)
1032
8
          addSymbolToRVASet(UsedSymbols, D);
1033
8
      }
1034
26
    }
1035
37
  }
1036
6
}
1037
1038
// Create the guard function id table. This is a table of RVAs of all
1039
// address-taken functions. It is sorted and uniqued, just like the safe SEH
1040
// table.
1041
11
void Writer::createGuardCFTables() {
1042
11
  SymbolRVASet AddressTakenSyms;
1043
11
  SymbolRVASet LongJmpTargets;
1044
14
  for (ObjFile *File : ObjFile::Instances) {
1045
14
    // If the object was compiled with /guard:cf, the address taken symbols
1046
14
    // are in .gfids$y sections, and the longjmp targets are in .gljmp$y
1047
14
    // sections. If the object was not compiled with /guard:cf, we assume there
1048
14
    // were no setjmp targets, and that all code symbols with relocations are
1049
14
    // possibly address-taken.
1050
14
    if (File->hasGuardCF()) {
1051
8
      markSymbolsForRVATable(File, File->getGuardFidChunks(), AddressTakenSyms);
1052
8
      markSymbolsForRVATable(File, File->getGuardLJmpChunks(), LongJmpTargets);
1053
8
    } else {
1054
6
      markSymbolsWithRelocations(File, AddressTakenSyms);
1055
6
    }
1056
14
  }
1057
11
1058
11
  // Mark the image entry as address-taken.
1059
11
  if (Config->Entry)
1060
11
    addSymbolToRVASet(AddressTakenSyms, cast<Defined>(Config->Entry));
1061
11
1062
11
  // Ensure sections referenced in the gfid table are 16-byte aligned.
1063
11
  for (const ChunkAndOffset &C : AddressTakenSyms)
1064
25
    if (C.InputChunk->Alignment < 16)
1065
18
      C.InputChunk->Alignment = 16;
1066
11
1067
11
  maybeAddRVATable(std::move(AddressTakenSyms), "__guard_fids_table",
1068
11
                   "__guard_fids_count");
1069
11
1070
11
  // Add the longjmp target table unless the user told us not to.
1071
11
  if (Config->GuardCF == GuardCFLevel::Full)
1072
5
    maybeAddRVATable(std::move(LongJmpTargets), "__guard_longjmp_table",
1073
5
                     "__guard_longjmp_count");
1074
11
1075
11
  // Set __guard_flags, which will be used in the load config to indicate that
1076
11
  // /guard:cf was enabled.
1077
11
  uint32_t GuardFlags = uint32_t(coff_guard_flags::CFInstrumented) |
1078
11
                        uint32_t(coff_guard_flags::HasFidTable);
1079
11
  if (Config->GuardCF == GuardCFLevel::Full)
1080
5
    GuardFlags |= uint32_t(coff_guard_flags::HasLongJmpTable);
1081
11
  Symbol *FlagSym = Symtab->findUnderscore("__guard_flags");
1082
11
  cast<DefinedAbsolute>(FlagSym)->setVA(GuardFlags);
1083
11
}
1084
1085
// Take a list of input sections containing symbol table indices and add those
1086
// symbols to an RVA table. The challenge is that symbol RVAs are not known and
1087
// depend on the table size, so we can't directly build a set of integers.
1088
void Writer::markSymbolsForRVATable(ObjFile *File,
1089
                                    ArrayRef<SectionChunk *> SymIdxChunks,
1090
45
                                    SymbolRVASet &TableSymbols) {
1091
45
  for (SectionChunk *C : SymIdxChunks) {
1092
19
    // Skip sections discarded by linker GC. This comes up when a .gfids section
1093
19
    // is associated with something like a vtable and the vtable is discarded.
1094
19
    // In this case, the associated gfids section is discarded, and we don't
1095
19
    // mark the virtual member functions as address-taken by the vtable.
1096
19
    if (!C->isLive())
1097
1
      continue;
1098
18
1099
18
    // Validate that the contents look like symbol table indices.
1100
18
    ArrayRef<uint8_t> Data = C->getContents();
1101
18
    if (Data.size() % 4 != 0) {
1102
1
      warn("ignoring " + C->getSectionName() +
1103
1
           " symbol table index section in object " + toString(File));
1104
1
      continue;
1105
1
    }
1106
17
1107
17
    // Read each symbol table index and check if that symbol was included in the
1108
17
    // final link. If so, add it to the table symbol set.
1109
17
    ArrayRef<ulittle32_t> SymIndices(
1110
17
        reinterpret_cast<const ulittle32_t *>(Data.data()), Data.size() / 4);
1111
17
    ArrayRef<Symbol *> ObjSymbols = File->getSymbols();
1112
20
    for (uint32_t SymIndex : SymIndices) {
1113
20
      if (SymIndex >= ObjSymbols.size()) {
1114
1
        warn("ignoring invalid symbol table index in section " +
1115
1
             C->getSectionName() + " in object " + toString(File));
1116
1
        continue;
1117
1
      }
1118
19
      if (Symbol *S = ObjSymbols[SymIndex]) {
1119
18
        if (S->isLive())
1120
17
          addSymbolToRVASet(TableSymbols, cast<Defined>(S));
1121
18
      }
1122
19
    }
1123
17
  }
1124
45
}
1125
1126
// Replace the absolute table symbol with a synthetic symbol pointing to
1127
// TableChunk so that we can emit base relocations for it and resolve section
1128
// relative relocations.
1129
void Writer::maybeAddRVATable(SymbolRVASet TableSymbols, StringRef TableSym,
1130
41
                              StringRef CountSym) {
1131
41
  if (TableSymbols.empty())
1132
23
    return;
1133
18
1134
18
  RVATableChunk *TableChunk = make<RVATableChunk>(std::move(TableSymbols));
1135
18
  RdataSec->addChunk(TableChunk);
1136
18
1137
18
  Symbol *T = Symtab->findUnderscore(TableSym);
1138
18
  Symbol *C = Symtab->findUnderscore(CountSym);
1139
18
  replaceSymbol<DefinedSynthetic>(T, T->getName(), TableChunk);
1140
18
  cast<DefinedAbsolute>(C)->setVA(TableChunk->getSize() / 4);
1141
18
}
1142
1143
// Handles /section options to allow users to overwrite
1144
// section attributes.
1145
405
void Writer::setSectionPermissions() {
1146
405
  for (auto &P : Config->Section) {
1147
6
    StringRef Name = P.first;
1148
6
    uint32_t Perm = P.second;
1149
6
    for (OutputSection *Sec : OutputSections)
1150
11
      if (Sec->Name == Name)
1151
7
        Sec->setPermissions(Perm);
1152
6
  }
1153
405
}
1154
1155
// Write section contents to a mmap'ed file.
1156
405
void Writer::writeSections() {
1157
405
  // Record the number of sections to apply section index relocations
1158
405
  // against absolute symbols. See applySecIdx in Chunks.cpp..
1159
405
  DefinedAbsolute::NumOutputSections = OutputSections.size();
1160
405
1161
405
  uint8_t *Buf = Buffer->getBufferStart();
1162
843
  for (OutputSection *Sec : OutputSections) {
1163
843
    uint8_t *SecBuf = Buf + Sec->getFileOff();
1164
843
    // Fill gaps between functions in .text with INT3 instructions
1165
843
    // instead of leaving as NUL bytes (which can be interpreted as
1166
843
    // ADD instructions).
1167
843
    if (Sec->Header.Characteristics & IMAGE_SCN_CNT_CODE)
1168
392
      memset(SecBuf, 0xCC, Sec->getRawSize());
1169
843
    for_each(parallel::par, Sec->getChunks().begin(), Sec->getChunks().end(),
1170
2.32k
             [&](Chunk *C) { C->writeTo(SecBuf); });
1171
843
  }
1172
405
}
1173
1174
405
void Writer::writeBuildId() {
1175
405
  // There are two important parts to the build ID.
1176
405
  // 1) If building with debug info, the COFF debug directory contains a
1177
405
  //    timestamp as well as a Guid and Age of the PDB.
1178
405
  // 2) In all cases, the PE COFF file header also contains a timestamp.
1179
405
  // For reproducibility, instead of a timestamp we want to use a hash of the
1180
405
  // binary, however when building with debug info the hash needs to take into
1181
405
  // account the debug info, since it's possible to add blank lines to a file
1182
405
  // which causes the debug info to change but not the generated code.
1183
405
  //
1184
405
  // To handle this, we first set the Guid and Age in the debug directory (but
1185
405
  // only if we're doing a debug build).  Then, we hash the binary (thus causing
1186
405
  // the hash to change if only the debug info changes, since the Age will be
1187
405
  // different).  Finally, we write that hash into the debug directory (if
1188
405
  // present) as well as the COFF file header (always).
1189
405
  if (Config->Debug) {
1190
80
    assert(BuildId && "BuildId is not set!");
1191
80
    if (PreviousBuildId.hasValue()) {
1192
21
      *BuildId->BuildId = *PreviousBuildId;
1193
21
      BuildId->BuildId->PDB70.Age = BuildId->BuildId->PDB70.Age + 1;
1194
59
    } else {
1195
59
      BuildId->BuildId->Signature.CVSignature = OMF::Signature::PDB70;
1196
59
      BuildId->BuildId->PDB70.Age = 1;
1197
59
      llvm::getRandomBytes(BuildId->BuildId->PDB70.Signature, 16);
1198
59
    }
1199
80
  }
1200
405
1201
405
  // At this point the only fields in the COFF file which remain unset are the
1202
405
  // "timestamp" in the COFF file header, and the ones in the coff debug
1203
405
  // directory.  Now we can hash the file and write that hash to the various
1204
405
  // timestamp fields in the file.
1205
405
  StringRef OutputFileData(
1206
405
      reinterpret_cast<const char *>(Buffer->getBufferStart()),
1207
405
      Buffer->getBufferSize());
1208
405
1209
405
  uint32_t Timestamp = Config->Timestamp;
1210
405
  if (Config->Repro)
1211
2
    Timestamp = static_cast<uint32_t>(xxHash64(OutputFileData));
1212
405
1213
405
  if (DebugDirectory)
1214
80
    DebugDirectory->setTimeDateStamp(Timestamp);
1215
405
1216
405
  uint8_t *Buf = Buffer->getBufferStart();
1217
405
  Buf += DOSStubSize + sizeof(PEMagic);
1218
405
  object::coff_file_header *CoffHeader =
1219
405
      reinterpret_cast<coff_file_header *>(Buf);
1220
405
  CoffHeader->TimeDateStamp = Timestamp;
1221
405
}
1222
1223
// Sort .pdata section contents according to PE/COFF spec 5.5.
1224
405
void Writer::sortExceptionTable() {
1225
405
  if (!FirstPdata)
1226
366
    return;
1227
39
  // We assume .pdata contains function table entries only.
1228
78
  
auto BufAddr = [&](Chunk *C) 39
{
1229
78
    return Buffer->getBufferStart() + C->getOutputSection()->getFileOff() +
1230
78
           C->getRVA() - C->getOutputSection()->getRVA();
1231
78
  };
1232
39
  uint8_t *Begin = BufAddr(FirstPdata);
1233
39
  uint8_t *End = BufAddr(LastPdata) + LastPdata->getSize();
1234
39
  if (Config->Machine == AMD64) {
1235
38
    struct Entry { ulittle32_t Begin, End, Unwind; };
1236
38
    sort(parallel::par, (Entry *)Begin, (Entry *)End,
1237
38
         [](const Entry &A, const Entry &B) 
{ return A.Begin < B.Begin; }23
);
1238
38
    return;
1239
38
  }
1240
1
  if (Config->Machine == ARMNT || Config->Machine == ARM64) {
1241
1
    struct Entry { ulittle32_t Begin, Unwind; };
1242
1
    sort(parallel::par, (Entry *)Begin, (Entry *)End,
1243
1
         [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
1244
1
    return;
1245
1
  }
1246
0
  errs() << "warning: don't know how to handle .pdata.\n";
1247
0
}
1248
1249
4.06k
OutputSection *Writer::findSection(StringRef Name) {
1250
4.06k
  for (OutputSection *Sec : OutputSections)
1251
22.0k
    if (Sec->Name == Name)
1252
3.69k
      return Sec;
1253
4.06k
  
return nullptr369
;
1254
4.06k
}
1255
1256
405
uint32_t Writer::getSizeOfInitializedData() {
1257
405
  uint32_t Res = 0;
1258
405
  for (OutputSection *S : OutputSections)
1259
843
    if (S->Header.Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
1260
450
      Res += S->getRawSize();
1261
405
  return Res;
1262
405
}
1263
1264
// Add base relocations to .reloc section.
1265
405
void Writer::addBaserels() {
1266
405
  if (!Config->Relocatable)
1267
4
    return;
1268
401
  std::vector<Baserel> V;
1269
4.52k
  for (OutputSection *Sec : OutputSections) {
1270
4.52k
    if (Sec->Header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE)
1271
428
      continue;
1272
4.09k
    // Collect all locations for base relocations.
1273
4.09k
    for (Chunk *C : Sec->getChunks())
1274
2.53k
      C->getBaserels(&V);
1275
4.09k
    // Add the addresses to .reloc section.
1276
4.09k
    if (!V.empty())
1277
81
      addBaserelBlocks(V);
1278
4.09k
    V.clear();
1279
4.09k
  }
1280
401
}
1281
1282
// Add addresses to .reloc section. Note that addresses are grouped by page.
1283
81
void Writer::addBaserelBlocks(std::vector<Baserel> &V) {
1284
81
  const uint32_t Mask = ~uint32_t(PageSize - 1);
1285
81
  uint32_t Page = V[0].RVA & Mask;
1286
81
  size_t I = 0, J = 1;
1287
179
  for (size_t E = V.size(); J < E; 
++J98
) {
1288
98
    uint32_t P = V[J].RVA & Mask;
1289
98
    if (P == Page)
1290
98
      continue;
1291
0
    RelocSec->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
1292
0
    I = J;
1293
0
    Page = P;
1294
0
  }
1295
81
  if (I == J)
1296
0
    return;
1297
81
  RelocSec->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
1298
81
}