Coverage Report

Created: 2018-06-25 02:00

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