Coverage Report

Created: 2019-02-21 13:17

/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
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
9
#include "Writer.h"
10
#include "Config.h"
11
#include "DLL.h"
12
#include "InputFiles.h"
13
#include "MapFile.h"
14
#include "PDB.h"
15
#include "SymbolTable.h"
16
#include "Symbols.h"
17
#include "lld/Common/ErrorHandler.h"
18
#include "lld/Common/Memory.h"
19
#include "lld/Common/Timer.h"
20
#include "llvm/ADT/DenseMap.h"
21
#include "llvm/ADT/STLExtras.h"
22
#include "llvm/ADT/StringSwitch.h"
23
#include "llvm/Support/BinaryStreamReader.h"
24
#include "llvm/Support/Debug.h"
25
#include "llvm/Support/Endian.h"
26
#include "llvm/Support/FileOutputBuffer.h"
27
#include "llvm/Support/Parallel.h"
28
#include "llvm/Support/Path.h"
29
#include "llvm/Support/RandomNumberGenerator.h"
30
#include "llvm/Support/xxhash.h"
31
#include <algorithm>
32
#include <cstdio>
33
#include <map>
34
#include <memory>
35
#include <utility>
36
37
using namespace llvm;
38
using namespace llvm::COFF;
39
using namespace llvm::object;
40
using namespace llvm::support;
41
using namespace llvm::support::endian;
42
using namespace lld;
43
using namespace lld::coff;
44
45
/* To re-generate DOSProgram:
46
$ cat > /tmp/DOSProgram.asm
47
org 0
48
        ; Copy cs to ds.
49
        push cs
50
        pop ds
51
        ; Point ds:dx at the $-terminated string.
52
        mov dx, str
53
        ; Int 21/AH=09h: Write string to standard output.
54
        mov ah, 0x9
55
        int 0x21
56
        ; Int 21/AH=4Ch: Exit with return code (in AL).
57
        mov ax, 0x4C01
58
        int 0x21
59
str:
60
        db 'This program cannot be run in DOS mode.$'
61
align 8, db 0
62
$ nasm -fbin /tmp/DOSProgram.asm -o /tmp/DOSProgram.bin
63
$ xxd -i /tmp/DOSProgram.bin
64
*/
65
static unsigned char DOSProgram[] = {
66
  0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8, 0x01, 0x4c,
67
  0xcd, 0x21, 0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72,
68
  0x61, 0x6d, 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x20, 0x62, 0x65,
69
  0x20, 0x72, 0x75, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20,
70
  0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x24, 0x00, 0x00
71
};
72
static_assert(sizeof(DOSProgram) % 8 == 0,
73
              "DOSProgram size must be multiple of 8");
74
75
static const int SectorSize = 512;
76
static const int DOSStubSize = sizeof(dos_header) + sizeof(DOSProgram);
77
static_assert(DOSStubSize % 8 == 0, "DOSStub size must be multiple of 8");
78
79
static const int NumberOfDataDirectory = 16;
80
81
namespace {
82
83
class DebugDirectoryChunk : public Chunk {
84
public:
85
  DebugDirectoryChunk(const std::vector<Chunk *> &R, bool WriteRepro)
86
111
      : Records(R), WriteRepro(WriteRepro) {}
87
88
322
  size_t getSize() const override {
89
322
    return (Records.size() + int(WriteRepro)) * sizeof(debug_directory);
90
322
  }
91
92
111
  void writeTo(uint8_t *B) const override {
93
111
    auto *D = reinterpret_cast<debug_directory *>(B + OutputSectionOff);
94
111
95
111
    for (const Chunk *Record : Records) {
96
110
      OutputSection *OS = Record->getOutputSection();
97
110
      uint64_t Offs = OS->getFileOff() + (Record->getRVA() - OS->getRVA());
98
110
      fillEntry(D, COFF::IMAGE_DEBUG_TYPE_CODEVIEW, Record->getSize(),
99
110
                Record->getRVA(), Offs);
100
110
      ++D;
101
110
    }
102
111
103
111
    if (WriteRepro) {
104
4
      // FIXME: The COFF spec allows either a 0-sized entry to just say
105
4
      // "the timestamp field is really a hash", or a 4-byte size field
106
4
      // followed by that many bytes containing a longer hash (with the
107
4
      // lowest 4 bytes usually being the timestamp in little-endian order).
108
4
      // Consider storing the full 8 bytes computed by xxHash64 here.
109
4
      fillEntry(D, COFF::IMAGE_DEBUG_TYPE_REPRO, 0, 0, 0);
110
4
    }
111
111
  }
112
113
111
  void setTimeDateStamp(uint32_t TimeDateStamp) {
114
111
    for (support::ulittle32_t *TDS : TimeDateStamps)
115
114
      *TDS = TimeDateStamp;
116
111
  }
117
118
private:
119
  void fillEntry(debug_directory *D, COFF::DebugType DebugType, size_t Size,
120
114
                 uint64_t RVA, uint64_t Offs) const {
121
114
    D->Characteristics = 0;
122
114
    D->TimeDateStamp = 0;
123
114
    D->MajorVersion = 0;
124
114
    D->MinorVersion = 0;
125
114
    D->Type = DebugType;
126
114
    D->SizeOfData = Size;
127
114
    D->AddressOfRawData = RVA;
128
114
    D->PointerToRawData = Offs;
129
114
130
114
    TimeDateStamps.push_back(&D->TimeDateStamp);
131
114
  }
132
133
  mutable std::vector<support::ulittle32_t *> TimeDateStamps;
134
  const std::vector<Chunk *> &Records;
135
  bool WriteRepro;
136
};
137
138
class CVDebugRecordChunk : public Chunk {
139
public:
140
320
  size_t getSize() const override {
141
320
    return sizeof(codeview::DebugInfo) + Config->PDBAltPath.size() + 1;
142
320
  }
143
144
110
  void writeTo(uint8_t *B) const override {
145
110
    // Save off the DebugInfo entry to backfill the file signature (build id)
146
110
    // in Writer::writeBuildId
147
110
    BuildId = reinterpret_cast<codeview::DebugInfo *>(B + OutputSectionOff);
148
110
149
110
    // variable sized field (PDB Path)
150
110
    char *P = reinterpret_cast<char *>(B + OutputSectionOff + sizeof(*BuildId));
151
110
    if (!Config->PDBAltPath.empty())
152
99
      memcpy(P, Config->PDBAltPath.data(), Config->PDBAltPath.size());
153
110
    P[Config->PDBAltPath.size()] = '\0';
154
110
  }
155
156
  mutable codeview::DebugInfo *BuildId = nullptr;
157
};
158
159
// PartialSection represents a group of chunks that contribute to an
160
// OutputSection. Collating a collection of PartialSections of same name and
161
// characteristics constitutes the OutputSection.
162
class PartialSectionKey {
163
public:
164
  StringRef Name;
165
  unsigned Characteristics;
166
167
5.60k
  bool operator<(const PartialSectionKey &Other) const {
168
5.60k
    int C = Name.compare(Other.Name);
169
5.60k
    if (C == 1)
170
1.35k
      return false;
171
4.24k
    if (C == 0)
172
1.45k
      return Characteristics < Other.Characteristics;
173
2.78k
    return true;
174
2.78k
  }
175
};
176
177
class PartialSection {
178
public:
179
  PartialSection(StringRef N, uint32_t Chars)
180
1.56k
      : Name(N), Characteristics(Chars) {}
181
  StringRef Name;
182
  unsigned Characteristics;
183
  std::vector<Chunk *> Chunks;
184
};
185
186
// The writer writes a SymbolTable result to a file.
187
class Writer {
188
public:
189
514
  Writer() : Buffer(errorHandler().OutputBuffer) {}
190
  void run();
191
192
private:
193
  void createSections();
194
  void createMiscChunks();
195
  void createImportTables();
196
  void appendImportThunks();
197
  void locateImportTables();
198
  void createExportTable();
199
  void mergeSections();
200
  void readRelocTargets();
201
  void removeUnusedSections();
202
  void assignAddresses();
203
  void finalizeAddresses();
204
  void removeEmptySections();
205
  void createSymbolAndStringTable();
206
  void openFile(StringRef OutputPath);
207
  template <typename PEHeaderTy> void writeHeader();
208
  void createSEHTable();
209
  void createRuntimePseudoRelocs();
210
  void insertCtorDtorSymbols();
211
  void createGuardCFTables();
212
  void markSymbolsForRVATable(ObjFile *File,
213
                              ArrayRef<SectionChunk *> SymIdxChunks,
214
                              SymbolRVASet &TableSymbols);
215
  void maybeAddRVATable(SymbolRVASet TableSymbols, StringRef TableSym,
216
                        StringRef CountSym);
217
  void setSectionPermissions();
218
  void writeSections();
219
  void writeBuildId();
220
  void sortExceptionTable();
221
  void sortCRTSectionChunks(std::vector<Chunk *> &Chunks);
222
  void addSyntheticIdata();
223
  bool fixGnuImportChunks();
224
  PartialSection *createPartialSection(StringRef Name, uint32_t OutChars);
225
  PartialSection *findPartialSection(StringRef Name, uint32_t OutChars);
226
227
  llvm::Optional<coff_symbol16> createSymbol(Defined *D);
228
  size_t addEntryToStringTable(StringRef Str);
229
230
  OutputSection *findSection(StringRef Name);
231
  void addBaserels();
232
  void addBaserelBlocks(std::vector<Baserel> &V);
233
234
  uint32_t getSizeOfInitializedData();
235
236
  std::unique_ptr<FileOutputBuffer> &Buffer;
237
  std::map<PartialSectionKey, PartialSection *> PartialSections;
238
  std::vector<OutputSection *> OutputSections;
239
  std::vector<char> Strtab;
240
  std::vector<llvm::object::coff_symbol16> OutputSymtab;
241
  IdataContents Idata;
242
  Chunk *ImportTableStart = nullptr;
243
  uint64_t ImportTableSize = 0;
244
  Chunk *IATStart = nullptr;
245
  uint64_t IATSize = 0;
246
  DelayLoadContents DelayIdata;
247
  EdataContents Edata;
248
  bool SetNoSEHCharacteristic = false;
249
250
  DebugDirectoryChunk *DebugDirectory = nullptr;
251
  std::vector<Chunk *> DebugRecords;
252
  CVDebugRecordChunk *BuildId = nullptr;
253
  ArrayRef<uint8_t> SectionTable;
254
255
  uint64_t FileSize;
256
  uint32_t PointerToSymbolTable = 0;
257
  uint64_t SizeOfImage;
258
  uint64_t SizeOfHeaders;
259
260
  OutputSection *TextSec;
261
  OutputSection *RdataSec;
262
  OutputSection *BuildidSec;
263
  OutputSection *DataSec;
264
  OutputSection *PdataSec;
265
  OutputSection *IdataSec;
266
  OutputSection *EdataSec;
267
  OutputSection *DidatSec;
268
  OutputSection *RsrcSec;
269
  OutputSection *RelocSec;
270
  OutputSection *CtorsSec;
271
  OutputSection *DtorsSec;
272
273
  // The first and last .pdata sections in the output file.
274
  //
275
  // We need to keep track of the location of .pdata in whichever section it
276
  // gets merged into so that we can sort its contents and emit a correct data
277
  // directory entry for the exception table. This is also the case for some
278
  // other sections (such as .edata) but because the contents of those sections
279
  // are entirely linker-generated we can keep track of their locations using
280
  // the chunks that the linker creates. All .pdata chunks come from input
281
  // files, so we need to keep track of them separately.
282
  Chunk *FirstPdata = nullptr;
283
  Chunk *LastPdata;
284
};
285
} // anonymous namespace
286
287
namespace lld {
288
namespace coff {
289
290
static Timer CodeLayoutTimer("Code Layout", Timer::root());
291
static Timer DiskCommitTimer("Commit Output File", Timer::root());
292
293
514
void writeResult() { Writer().run(); }
294
295
3.81k
void OutputSection::addChunk(Chunk *C) {
296
3.81k
  Chunks.push_back(C);
297
3.81k
  C->setOutputSection(this);
298
3.81k
}
299
300
82
void OutputSection::insertChunkAtStart(Chunk *C) {
301
82
  Chunks.insert(Chunks.begin(), C);
302
82
  C->setOutputSection(this);
303
82
}
304
305
7
void OutputSection::setPermissions(uint32_t C) {
306
7
  Header.Characteristics &= ~PermMask;
307
7
  Header.Characteristics |= C;
308
7
}
309
310
2.19k
void OutputSection::merge(OutputSection *Other) {
311
2.19k
  for (Chunk *C : Other->Chunks)
312
1.84k
    C->setOutputSection(this);
313
2.19k
  Chunks.insert(Chunks.end(), Other->Chunks.begin(), Other->Chunks.end());
314
2.19k
  Other->Chunks.clear();
315
2.19k
}
316
317
// Write the section header to a given buffer.
318
1.07k
void OutputSection::writeHeaderTo(uint8_t *Buf) {
319
1.07k
  auto *Hdr = reinterpret_cast<coff_section *>(Buf);
320
1.07k
  *Hdr = Header;
321
1.07k
  if (StringTableOff) {
322
18
    // If name is too long, write offset into the string table as a name.
323
18
    sprintf(Hdr->Name, "/%d", StringTableOff);
324
1.05k
  } else {
325
1.05k
    assert(!Config->Debug || Name.size() <= COFF::NameSize ||
326
1.05k
           (Hdr->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) == 0);
327
1.05k
    strncpy(Hdr->Name, Name.data(),
328
1.05k
            std::min(Name.size(), (size_t)COFF::NameSize));
329
1.05k
  }
330
1.07k
}
331
332
} // namespace coff
333
} // namespace lld
334
335
// Check whether the target address S is in range from a relocation
336
// of type RelType at address P.
337
211
static bool isInRange(uint16_t RelType, uint64_t S, uint64_t P, int Margin) {
338
211
  if (Config->Machine == ARMNT) {
339
155
    int64_t Diff = AbsoluteDifference(S, P + 4) + Margin;
340
155
    switch (RelType) {
341
155
    case IMAGE_REL_ARM_BRANCH20T:
342
126
      return isInt<21>(Diff);
343
155
    case IMAGE_REL_ARM_BRANCH24T:
344
10
    case IMAGE_REL_ARM_BLX23T:
345
10
      return isInt<25>(Diff);
346
19
    default:
347
19
      return true;
348
56
    }
349
56
  } else if (Config->Machine == ARM64) {
350
56
    int64_t Diff = AbsoluteDifference(S, P) + Margin;
351
56
    switch (RelType) {
352
56
    case IMAGE_REL_ARM64_BRANCH26:
353
9
      return isInt<28>(Diff);
354
56
    case IMAGE_REL_ARM64_BRANCH19:
355
1
      return isInt<21>(Diff);
356
56
    case IMAGE_REL_ARM64_BRANCH14:
357
4
      return isInt<16>(Diff);
358
56
    default:
359
42
      return true;
360
0
    }
361
0
  } else {
362
0
    llvm_unreachable("Unexpected architecture");
363
0
  }
364
211
}
365
366
// Return the last thunk for the given target if it is in range,
367
// or create a new one.
368
static std::pair<Defined *, bool>
369
getThunk(DenseMap<uint64_t, Defined *> &LastThunks, Defined *Target, uint64_t P,
370
52
         uint16_t Type, int Margin) {
371
52
  Defined *&LastThunk = LastThunks[Target->getRVA()];
372
52
  if (LastThunk && 
isInRange(Type, LastThunk->getRVA(), P, Margin)2
)
373
1
    return {LastThunk, false};
374
51
  Chunk *C;
375
51
  switch (Config->Machine) {
376
51
  case ARMNT:
377
50
    C = make<RangeExtensionThunkARM>(Target);
378
50
    break;
379
51
  case ARM64:
380
1
    C = make<RangeExtensionThunkARM64>(Target);
381
1
    break;
382
51
  default:
383
0
    llvm_unreachable("Unexpected architecture");
384
51
  }
385
51
  Defined *D = make<DefinedSynthetic>("", C);
386
51
  LastThunk = D;
387
51
  return {D, true};
388
51
}
389
390
// This checks all relocations, and for any relocation which isn't in range
391
// it adds a thunk after the section chunk that contains the relocation.
392
// If the latest thunk for the specific target is in range, that is used
393
// instead of creating a new thunk. All range checks are done with the
394
// specified margin, to make sure that relocations that originally are in
395
// range, but only barely, also get thunks - in case other added thunks makes
396
// the target go out of range.
397
//
398
// After adding thunks, we verify that all relocations are in range (with
399
// no extra margin requirements). If this failed, we restart (throwing away
400
// the previously created thunks) and retry with a wider margin.
401
17
static bool createThunks(OutputSection *OS, int Margin) {
402
17
  bool AddressesChanged = false;
403
17
  DenseMap<uint64_t, Defined *> LastThunks;
404
17
  size_t ThunksSize = 0;
405
17
  // Recheck Chunks.size() each iteration, since we can insert more
406
17
  // elements into it.
407
169
  for (size_t I = 0; I != OS->Chunks.size(); 
++I152
) {
408
152
    SectionChunk *SC = dyn_cast_or_null<SectionChunk>(OS->Chunks[I]);
409
152
    if (!SC)
410
55
      continue;
411
97
    size_t ThunkInsertionSpot = I + 1;
412
97
413
97
    // Try to get a good enough estimate of where new thunks will be placed.
414
97
    // Offset this by the size of the new thunks added so far, to make the
415
97
    // estimate slightly better.
416
97
    size_t ThunkInsertionRVA = SC->getRVA() + SC->getSize() + ThunksSize;
417
179
    for (size_t J = 0, E = SC->Relocs.size(); J < E; 
++J82
) {
418
82
      const coff_relocation &Rel = SC->Relocs[J];
419
82
      Symbol *&RelocTarget = SC->RelocTargets[J];
420
82
421
82
      // The estimate of the source address P should be pretty accurate,
422
82
      // but we don't know whether the target Symbol address should be
423
82
      // offset by ThunkSize or not (or by some of ThunksSize but not all of
424
82
      // it), giving us some uncertainty once we have added one thunk.
425
82
      uint64_t P = SC->getRVA() + Rel.VirtualAddress + ThunksSize;
426
82
427
82
      Defined *Sym = dyn_cast_or_null<Defined>(RelocTarget);
428
82
      if (!Sym)
429
0
        continue;
430
82
431
82
      uint64_t S = Sym->getRVA();
432
82
433
82
      if (isInRange(Rel.Type, S, P, Margin))
434
30
        continue;
435
52
436
52
      // If the target isn't in range, hook it up to an existing or new
437
52
      // thunk.
438
52
      Defined *Thunk;
439
52
      bool WasNew;
440
52
      std::tie(Thunk, WasNew) = getThunk(LastThunks, Sym, P, Rel.Type, Margin);
441
52
      if (WasNew) {
442
51
        Chunk *ThunkChunk = Thunk->getChunk();
443
51
        ThunkChunk->setRVA(
444
51
            ThunkInsertionRVA); // Estimate of where it will be located.
445
51
        ThunkChunk->setOutputSection(OS);
446
51
        OS->Chunks.insert(OS->Chunks.begin() + ThunkInsertionSpot, ThunkChunk);
447
51
        ThunkInsertionSpot++;
448
51
        ThunksSize += ThunkChunk->getSize();
449
51
        ThunkInsertionRVA += ThunkChunk->getSize();
450
51
        AddressesChanged = true;
451
51
      }
452
52
      RelocTarget = Thunk;
453
52
    }
454
97
  }
455
17
  return AddressesChanged;
456
17
}
457
458
// Verify that all relocations are in range, with no extra margin requirements.
459
108
static bool verifyRanges(const std::vector<Chunk *> Chunks) {
460
349
  for (Chunk *C : Chunks) {
461
349
    SectionChunk *SC = dyn_cast_or_null<SectionChunk>(C);
462
349
    if (!SC)
463
229
      continue;
464
120
465
242
    
for (size_t J = 0, E = SC->Relocs.size(); 120
J < E;
++J122
) {
466
127
      const coff_relocation &Rel = SC->Relocs[J];
467
127
      Symbol *RelocTarget = SC->RelocTargets[J];
468
127
469
127
      Defined *Sym = dyn_cast_or_null<Defined>(RelocTarget);
470
127
      if (!Sym)
471
0
        continue;
472
127
473
127
      uint64_t P = SC->getRVA() + Rel.VirtualAddress;
474
127
      uint64_t S = Sym->getRVA();
475
127
476
127
      if (!isInRange(Rel.Type, S, P, 0))
477
5
        return false;
478
127
    }
479
120
  }
480
108
  
return true103
;
481
108
}
482
483
// Assign addresses and add thunks if necessary.
484
514
void Writer::finalizeAddresses() {
485
514
  assignAddresses();
486
514
  if (Config->Machine != ARMNT && 
Config->Machine != ARM64496
)
487
483
    return;
488
31
489
31
  size_t OrigNumChunks = 0;
490
103
  for (OutputSection *Sec : OutputSections) {
491
103
    Sec->OrigChunks = Sec->Chunks;
492
103
    OrigNumChunks += Sec->Chunks.size();
493
103
  }
494
31
495
31
  int Pass = 0;
496
31
  int Margin = 1024 * 100;
497
36
  while (true) {
498
36
    // First check whether we need thunks at all, or if the previous pass of
499
36
    // adding them turned out ok.
500
36
    bool RangesOk = true;
501
36
    size_t NumChunks = 0;
502
108
    for (OutputSection *Sec : OutputSections) {
503
108
      if (!verifyRanges(Sec->Chunks)) {
504
5
        RangesOk = false;
505
5
        break;
506
5
      }
507
103
      NumChunks += Sec->Chunks.size();
508
103
    }
509
36
    if (RangesOk) {
510
31
      if (Pass > 0)
511
4
        log("Added " + Twine(NumChunks - OrigNumChunks) + " thunks with " +
512
4
            "margin " + Twine(Margin) + " in " + Twine(Pass) + " passes");
513
31
      return;
514
31
    }
515
5
516
5
    if (Pass >= 10)
517
0
      fatal("adding thunks hasn't converged after " + Twine(Pass) + " passes");
518
5
519
5
    if (Pass > 0) {
520
1
      // If the previous pass didn't work out, reset everything back to the
521
1
      // original conditions before retrying with a wider margin. This should
522
1
      // ideally never happen under real circumstances.
523
3
      for (OutputSection *Sec : OutputSections) {
524
3
        Sec->Chunks = Sec->OrigChunks;
525
3
        for (Chunk *C : Sec->Chunks)
526
40
          C->resetRelocTargets();
527
3
      }
528
1
      Margin *= 2;
529
1
    }
530
5
531
5
    // Try adding thunks everywhere where it is needed, with a margin
532
5
    // to avoid things going out of range due to the added thunks.
533
5
    bool AddressesChanged = false;
534
5
    for (OutputSection *Sec : OutputSections)
535
17
      AddressesChanged |= createThunks(Sec, Margin);
536
5
    // If the verification above thought we needed thunks, we should have
537
5
    // added some.
538
5
    assert(AddressesChanged);
539
5
540
5
    // Recalculate the layout for the whole image (and verify the ranges at
541
5
    // the start of the next round).
542
5
    assignAddresses();
543
5
544
5
    Pass++;
545
5
  }
546
31
}
547
548
// The main function of the writer.
549
514
void Writer::run() {
550
514
  ScopedTimer T1(CodeLayoutTimer);
551
514
552
514
  createImportTables();
553
514
  createSections();
554
514
  createMiscChunks();
555
514
  appendImportThunks();
556
514
  createExportTable();
557
514
  mergeSections();
558
514
  readRelocTargets();
559
514
  removeUnusedSections();
560
514
  finalizeAddresses();
561
514
  removeEmptySections();
562
514
  setSectionPermissions();
563
514
  createSymbolAndStringTable();
564
514
565
514
  if (FileSize > UINT32_MAX)
566
514
    fatal("image size (" + Twine(FileSize) + ") " +
567
0
        "exceeds maximum allowable size (" + Twine(UINT32_MAX) + ")");
568
514
569
514
  openFile(Config->OutputFile);
570
514
  if (Config->is64()) {
571
409
    writeHeader<pe32plus_header>();
572
409
  } else {
573
105
    writeHeader<pe32_header>();
574
105
  }
575
514
  writeSections();
576
514
  sortExceptionTable();
577
514
578
514
  T1.stop();
579
514
580
514
  if (!Config->PDBPath.empty() && 
Config->Debug99
) {
581
99
    assert(BuildId);
582
99
    createPDB(Symtab, OutputSections, SectionTable, BuildId->BuildId);
583
99
  }
584
514
  writeBuildId();
585
514
586
514
  writeMapFile(OutputSections);
587
514
588
514
  ScopedTimer T2(DiskCommitTimer);
589
514
  if (auto E = Buffer->commit())
590
0
    fatal("failed to write the output file: " + toString(std::move(E)));
591
514
}
592
593
1.56k
static StringRef getOutputSectionName(StringRef Name) {
594
1.56k
  StringRef S = Name.split('$').first;
595
1.56k
596
1.56k
  // Treat a later period as a separator for MinGW, for sections like
597
1.56k
  // ".ctors.01234".
598
1.56k
  return S.substr(0, S.find('.', 1));
599
1.56k
}
600
601
// For /order.
602
4
static void sortBySectionOrder(std::vector<Chunk *> &Chunks) {
603
68
  auto GetPriority = [](const Chunk *C) {
604
68
    if (auto *Sec = dyn_cast<SectionChunk>(C))
605
68
      if (Sec->Sym)
606
68
        return Config->Order.lookup(Sec->Sym->getName());
607
0
    return 0;
608
0
  };
609
4
610
4
  std::stable_sort(Chunks.begin(), Chunks.end(),
611
34
                   [=](const Chunk *A, const Chunk *B) {
612
34
                     return GetPriority(A) < GetPriority(B);
613
34
                   });
614
4
}
615
616
// Sort concrete section chunks from GNU import libraries.
617
//
618
// GNU binutils doesn't use short import files, but instead produces import
619
// libraries that consist of object files, with section chunks for the .idata$*
620
// sections. These are linked just as regular static libraries. Each import
621
// library consists of one header object, one object file for every imported
622
// symbol, and one trailer object. In order for the .idata tables/lists to
623
// be formed correctly, the section chunks within each .idata$* section need
624
// to be grouped by library, and sorted alphabetically within each library
625
// (which makes sure the header comes first and the trailer last).
626
514
bool Writer::fixGnuImportChunks() {
627
514
  uint32_t RDATA = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ;
628
514
629
514
  // Make sure all .idata$* section chunks are mapped as RDATA in order to
630
514
  // be sorted into the same sections as our own synthesized .idata chunks.
631
1.33k
  for (auto It : PartialSections) {
632
1.33k
    PartialSection *PSec = It.second;
633
1.33k
    if (!PSec->Name.startswith(".idata"))
634
1.31k
      continue;
635
20
    if (PSec->Characteristics == RDATA)
636
0
      continue;
637
20
    PartialSection *RDataSec = createPartialSection(PSec->Name, RDATA);
638
20
    RDataSec->Chunks.insert(RDataSec->Chunks.end(), PSec->Chunks.begin(),
639
20
                            PSec->Chunks.end());
640
20
    PSec->Chunks.clear();
641
20
  }
642
514
643
514
  bool HasIdata = false;
644
514
  // Sort all .idata$* chunks, grouping chunks from the same library,
645
514
  // with alphabetical ordering of the object fils within a library.
646
1.35k
  for (auto It : PartialSections) {
647
1.35k
    PartialSection *PSec = It.second;
648
1.35k
    if (!PSec->Name.startswith(".idata"))
649
1.31k
      continue;
650
40
651
40
    std::vector<Chunk *> &Chunks = PSec->Chunks;
652
40
    if (!Chunks.empty())
653
20
      HasIdata = true;
654
40
    std::stable_sort(Chunks.begin(), Chunks.end(), [&](Chunk *S, Chunk *T) {
655
20
      SectionChunk *SC1 = dyn_cast_or_null<SectionChunk>(S);
656
20
      SectionChunk *SC2 = dyn_cast_or_null<SectionChunk>(T);
657
20
      if (!SC1 || !SC2) {
658
0
        // if SC1, order them ascending. If SC2 or both null,
659
0
        // S is not less than T.
660
0
        return SC1 != nullptr;
661
0
      }
662
20
      // Make a string with "libraryname/objectfile" for sorting, achieving
663
20
      // both grouping by library and sorting of objects within a library,
664
20
      // at once.
665
20
      std::string Key1 =
666
20
          (SC1->File->ParentName + "/" + SC1->File->getName()).str();
667
20
      std::string Key2 =
668
20
          (SC2->File->ParentName + "/" + SC2->File->getName()).str();
669
20
      return Key1 < Key2;
670
20
    });
671
40
  }
672
514
  return HasIdata;
673
514
}
674
675
// Add generated idata chunks, for imported symbols and DLLs, and a
676
// terminator in .idata$2.
677
46
void Writer::addSyntheticIdata() {
678
46
  uint32_t RDATA = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ;
679
46
  Idata.create();
680
46
681
46
  // Add the .idata content in the right section groups, to allow
682
46
  // chunks from other linked in object files to be grouped together.
683
46
  // See Microsoft PE/COFF spec 5.4 for details.
684
230
  auto Add = [&](StringRef N, std::vector<Chunk *> &V) {
685
230
    PartialSection *PSec = createPartialSection(N, RDATA);
686
230
    PSec->Chunks.insert(PSec->Chunks.end(), V.begin(), V.end());
687
230
  };
688
46
689
46
  // The loader assumes a specific order of data.
690
46
  // Add each type in the correct order.
691
46
  Add(".idata$2", Idata.Dirs);
692
46
  Add(".idata$4", Idata.Lookups);
693
46
  Add(".idata$5", Idata.Addresses);
694
46
  Add(".idata$6", Idata.Hints);
695
46
  Add(".idata$7", Idata.DLLNames);
696
46
}
697
698
// Locate the first Chunk and size of the import directory list and the
699
// IAT.
700
46
void Writer::locateImportTables() {
701
46
  uint32_t RDATA = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ;
702
46
703
46
  if (PartialSection *ImportDirs = findPartialSection(".idata$2", RDATA)) {
704
46
    if (!ImportDirs->Chunks.empty())
705
46
      ImportTableStart = ImportDirs->Chunks.front();
706
46
    for (Chunk *C : ImportDirs->Chunks)
707
95
      ImportTableSize += C->getSize();
708
46
  }
709
46
710
46
  if (PartialSection *ImportAddresses = findPartialSection(".idata$5", RDATA)) {
711
46
    if (!ImportAddresses->Chunks.empty())
712
46
      IATStart = ImportAddresses->Chunks.front();
713
46
    for (Chunk *C : ImportAddresses->Chunks)
714
146
      IATSize += C->getSize();
715
46
  }
716
46
}
717
718
// Create output section objects and add them to OutputSections.
719
514
void Writer::createSections() {
720
514
  // First, create the builtin sections.
721
514
  const uint32_t DATA = IMAGE_SCN_CNT_INITIALIZED_DATA;
722
514
  const uint32_t BSS = IMAGE_SCN_CNT_UNINITIALIZED_DATA;
723
514
  const uint32_t CODE = IMAGE_SCN_CNT_CODE;
724
514
  const uint32_t DISCARDABLE = IMAGE_SCN_MEM_DISCARDABLE;
725
514
  const uint32_t R = IMAGE_SCN_MEM_READ;
726
514
  const uint32_t W = IMAGE_SCN_MEM_WRITE;
727
514
  const uint32_t X = IMAGE_SCN_MEM_EXECUTE;
728
514
729
514
  SmallDenseMap<std::pair<StringRef, uint32_t>, OutputSection *> Sections;
730
8.25k
  auto CreateSection = [&](StringRef Name, uint32_t OutChars) {
731
8.25k
    OutputSection *&Sec = Sections[{Name, OutChars}];
732
8.25k
    if (!Sec) {
733
6.82k
      Sec = make<OutputSection>(Name, OutChars);
734
6.82k
      OutputSections.push_back(Sec);
735
6.82k
    }
736
8.25k
    return Sec;
737
8.25k
  };
738
514
739
514
  // Try to match the section order used by link.exe.
740
514
  TextSec = CreateSection(".text", CODE | R | X);
741
514
  CreateSection(".bss", BSS | R | W);
742
514
  RdataSec = CreateSection(".rdata", DATA | R);
743
514
  BuildidSec = CreateSection(".buildid", DATA | R);
744
514
  DataSec = CreateSection(".data", DATA | R | W);
745
514
  PdataSec = CreateSection(".pdata", DATA | R);
746
514
  IdataSec = CreateSection(".idata", DATA | R);
747
514
  EdataSec = CreateSection(".edata", DATA | R);
748
514
  DidatSec = CreateSection(".didat", DATA | R);
749
514
  RsrcSec = CreateSection(".rsrc", DATA | R);
750
514
  RelocSec = CreateSection(".reloc", DATA | DISCARDABLE | R);
751
514
  CtorsSec = CreateSection(".ctors", DATA | R | W);
752
514
  DtorsSec = CreateSection(".dtors", DATA | R | W);
753
514
754
514
  // Then bin chunks by name and output characteristics.
755
1.99k
  for (Chunk *C : Symtab->getChunks()) {
756
1.99k
    auto *SC = dyn_cast<SectionChunk>(C);
757
1.99k
    if (SC && 
!SC->Live1.97k
) {
758
67
      if (Config->Verbose)
759
22
        SC->printDiscardedMessage();
760
67
      continue;
761
67
    }
762
1.92k
    PartialSection *PSec = createPartialSection(C->getSectionName(),
763
1.92k
                                                C->getOutputCharacteristics());
764
1.92k
    PSec->Chunks.push_back(C);
765
1.92k
  }
766
514
767
514
  // Even in non MinGW cases, we might need to link against GNU import
768
514
  // libraries.
769
514
  bool HasIdata = fixGnuImportChunks();
770
514
  if (!Idata.empty())
771
44
    HasIdata = true;
772
514
773
514
  if (HasIdata)
774
46
    addSyntheticIdata();
775
514
776
514
  // Process an /order option.
777
514
  if (!Config->Order.empty())
778
4
    for (auto It : PartialSections)
779
4
      sortBySectionOrder(It.second->Chunks);
780
514
781
514
  if (HasIdata)
782
46
    locateImportTables();
783
514
784
514
  // Then create an OutputSection for each section.
785
514
  // '$' and all following characters in input section names are
786
514
  // discarded when determining output section. So, .text$foo
787
514
  // contributes to .text, for example. See PE/COFF spec 3.2.
788
1.56k
  for (auto It : PartialSections) {
789
1.56k
    PartialSection *PSec = It.second;
790
1.56k
    StringRef Name = getOutputSectionName(PSec->Name);
791
1.56k
    uint32_t OutChars = PSec->Characteristics;
792
1.56k
793
1.56k
    if (Name == ".CRT") {
794
22
      // In link.exe, there is a special case for the I386 target where .CRT
795
22
      // sections are treated as if they have output characteristics DATA | R if
796
22
      // their characteristics are DATA | R | W. This implements the same
797
22
      // special case for all architectures.
798
22
      OutChars = DATA | R;
799
22
800
22
      log("Processing section " + PSec->Name + " -> " + Name);
801
22
802
22
      sortCRTSectionChunks(PSec->Chunks);
803
22
    }
804
1.56k
805
1.56k
    OutputSection *Sec = CreateSection(Name, OutChars);
806
1.56k
    for (Chunk *C : PSec->Chunks)
807
2.40k
      Sec->addChunk(C);
808
1.56k
  }
809
514
810
514
  // Finally, move some output sections to the end.
811
17.1k
  auto SectionOrder = [&](OutputSection *S) {
812
17.1k
    // Move DISCARDABLE (or non-memory-mapped) sections to the end of file because
813
17.1k
    // the loader cannot handle holes. Stripping can remove other discardable ones
814
17.1k
    // than .reloc, which is first of them (created early).
815
17.1k
    if (S->Header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE)
816
1.71k
      return 2;
817
15.4k
    // .rsrc should come at the end of the non-discardable sections because its
818
15.4k
    // size may change by the Win32 UpdateResources() function, causing
819
15.4k
    // subsequent sections to move (see https://crbug.com/827082).
820
15.4k
    if (S == RsrcSec)
821
2.16k
      return 1;
822
13.3k
    return 0;
823
13.3k
  };
824
514
  std::stable_sort(OutputSections.begin(), OutputSections.end(),
825
8.59k
                   [&](OutputSection *S, OutputSection *T) {
826
8.59k
                     return SectionOrder(S) < SectionOrder(T);
827
8.59k
                   });
828
514
}
829
830
514
void Writer::createMiscChunks() {
831
514
  for (auto &P : MergeChunk::Instances)
832
5
    RdataSec->addChunk(P.second);
833
514
834
514
  // Create thunks for locally-dllimported symbols.
835
514
  if (!Symtab->LocalImportChunks.empty()) {
836
9
    for (Chunk *C : Symtab->LocalImportChunks)
837
9
      RdataSec->addChunk(C);
838
9
  }
839
514
840
514
  // Create Debug Information Chunks
841
514
  OutputSection *DebugInfoSec = Config->MinGW ? 
BuildidSec41
:
RdataSec473
;
842
514
  if (Config->Debug || 
Config->Repro404
) {
843
111
    DebugDirectory = make<DebugDirectoryChunk>(DebugRecords, Config->Repro);
844
111
    DebugInfoSec->addChunk(DebugDirectory);
845
111
  }
846
514
847
514
  if (Config->Debug) {
848
110
    // Make a CVDebugRecordChunk even when /DEBUG:CV is not specified.  We
849
110
    // output a PDB no matter what, and this chunk provides the only means of
850
110
    // allowing a debugger to match a PDB and an executable.  So we need it even
851
110
    // if we're ultimately not going to write CodeView data to the PDB.
852
110
    BuildId = make<CVDebugRecordChunk>();
853
110
    DebugRecords.push_back(BuildId);
854
110
855
110
    for (Chunk *C : DebugRecords)
856
110
      DebugInfoSec->addChunk(C);
857
110
  }
858
514
859
514
  // Create SEH table. x86-only.
860
514
  if (Config->Machine == I386)
861
87
    createSEHTable();
862
514
863
514
  // Create /guard:cf tables if requested.
864
514
  if (Config->GuardCF != GuardCFLevel::Off)
865
12
    createGuardCFTables();
866
514
867
514
  if (Config->MinGW) {
868
41
    createRuntimePseudoRelocs();
869
41
870
41
    insertCtorDtorSymbols();
871
41
  }
872
514
}
873
874
// Create .idata section for the DLL-imported symbol table.
875
// The format of this section is inherently Windows-specific.
876
// IdataContents class abstracted away the details for us,
877
// so we just let it create chunks and add them to the section.
878
514
void Writer::createImportTables() {
879
514
  // Initialize DLLOrder so that import entries are ordered in
880
514
  // the same order as in the command line. (That affects DLL
881
514
  // initialization order, and this ordering is MSVC-compatible.)
882
514
  for (ImportFile *File : ImportFile::Instances) {
883
99
    if (!File->Live)
884
3
      continue;
885
96
886
96
    std::string DLL = StringRef(File->DLLName).lower();
887
96
    if (Config->DLLOrder.count(DLL) == 0)
888
49
      Config->DLLOrder[DLL] = Config->DLLOrder.size();
889
96
890
96
    if (File->ImpSym && !isa<DefinedImportData>(File->ImpSym))
891
0
      fatal(toString(*File->ImpSym) + " was replaced");
892
96
    DefinedImportData *ImpSym = cast_or_null<DefinedImportData>(File->ImpSym);
893
96
    if (Config->DelayLoads.count(StringRef(File->DLLName).lower())) {
894
7
      if (!File->ThunkSym)
895
0
        fatal("cannot delay-load " + toString(File) +
896
0
              " due to import of data: " + toString(*ImpSym));
897
7
      DelayIdata.add(ImpSym);
898
89
    } else {
899
89
      Idata.add(ImpSym);
900
89
    }
901
96
  }
902
514
}
903
904
514
void Writer::appendImportThunks() {
905
514
  if (ImportFile::Instances.empty())
906
463
    return;
907
51
908
99
  
for (ImportFile *File : ImportFile::Instances)51
{
909
99
    if (!File->Live)
910
3
      continue;
911
96
912
96
    if (!File->ThunkSym)
913
7
      continue;
914
89
915
89
    if (!isa<DefinedImportThunk>(File->ThunkSym))
916
0
      fatal(toString(*File->ThunkSym) + " was replaced");
917
89
    DefinedImportThunk *Thunk = cast<DefinedImportThunk>(File->ThunkSym);
918
89
    if (File->ThunkLive)
919
86
      TextSec->addChunk(Thunk->getChunk());
920
89
  }
921
51
922
51
  if (!DelayIdata.empty()) {
923
4
    Defined *Helper = cast<Defined>(Config->DelayLoadHelper);
924
4
    DelayIdata.create(Helper);
925
4
    for (Chunk *C : DelayIdata.getChunks())
926
29
      DidatSec->addChunk(C);
927
4
    for (Chunk *C : DelayIdata.getDataChunks())
928
15
      DataSec->addChunk(C);
929
4
    for (Chunk *C : DelayIdata.getCodeChunks())
930
7
      TextSec->addChunk(C);
931
4
  }
932
51
}
933
934
514
void Writer::createExportTable() {
935
514
  if (Config->Exports.empty())
936
402
    return;
937
112
  for (Chunk *C : Edata.Chunks)
938
760
    EdataSec->addChunk(C);
939
112
}
940
941
514
void Writer::removeUnusedSections() {
942
514
  // Remove sections that we can be sure won't get content, to avoid
943
514
  // allocating space for their section headers.
944
6.82k
  auto IsUnused = [this](OutputSection *S) {
945
6.82k
    if (S == RelocSec)
946
514
      return false; // This section is populated later.
947
6.30k
    // MergeChunks have zero size at this point, as their size is finalized
948
6.30k
    // later. Only remove sections that have no Chunks at all.
949
6.30k
    return S->Chunks.empty();
950
6.30k
  };
951
514
  OutputSections.erase(
952
514
      std::remove_if(OutputSections.begin(), OutputSections.end(), IsUnused),
953
514
      OutputSections.end());
954
514
}
955
956
// The Windows loader doesn't seem to like empty sections,
957
// so we remove them if any.
958
514
void Writer::removeEmptySections() {
959
1.76k
  auto IsEmpty = [](OutputSection *S) { return S->getVirtualSize() == 0; };
960
514
  OutputSections.erase(
961
514
      std::remove_if(OutputSections.begin(), OutputSections.end(), IsEmpty),
962
514
      OutputSections.end());
963
514
  uint32_t Idx = 1;
964
514
  for (OutputSection *Sec : OutputSections)
965
1.07k
    Sec->SectionIndex = Idx++;
966
514
}
967
968
42
size_t Writer::addEntryToStringTable(StringRef Str) {
969
42
  assert(Str.size() > COFF::NameSize);
970
42
  size_t OffsetOfEntry = Strtab.size() + 4; // +4 for the size field
971
42
  Strtab.insert(Strtab.end(), Str.begin(), Str.end());
972
42
  Strtab.push_back('\0');
973
42
  return OffsetOfEntry;
974
42
}
975
976
307
Optional<coff_symbol16> Writer::createSymbol(Defined *Def) {
977
307
  coff_symbol16 Sym;
978
307
  switch (Def->kind()) {
979
307
  case Symbol::DefinedAbsoluteKind:
980
6
    Sym.Value = Def->getRVA();
981
6
    Sym.SectionNumber = IMAGE_SYM_ABSOLUTE;
982
6
    break;
983
307
  case Symbol::DefinedSyntheticKind:
984
5
    // Relative symbols are unrepresentable in a COFF symbol table.
985
5
    return None;
986
307
  default: {
987
296
    // Don't write symbols that won't be written to the output to the symbol
988
296
    // table.
989
296
    Chunk *C = Def->getChunk();
990
296
    if (!C)
991
1
      return None;
992
295
    OutputSection *OS = C->getOutputSection();
993
295
    if (!OS)
994
9
      return None;
995
286
996
286
    Sym.Value = Def->getRVA() - OS->getRVA();
997
286
    Sym.SectionNumber = OS->SectionIndex;
998
286
    break;
999
286
  }
1000
292
  }
1001
292
1002
292
  StringRef Name = Def->getName();
1003
292
  if (Name.size() > COFF::NameSize) {
1004
24
    Sym.Name.Offset.Zeroes = 0;
1005
24
    Sym.Name.Offset.Offset = addEntryToStringTable(Name);
1006
268
  } else {
1007
268
    memset(Sym.Name.ShortName, 0, COFF::NameSize);
1008
268
    memcpy(Sym.Name.ShortName, Name.data(), Name.size());
1009
268
  }
1010
292
1011
292
  if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
1012
280
    COFFSymbolRef Ref = D->getCOFFSymbol();
1013
280
    Sym.Type = Ref.getType();
1014
280
    Sym.StorageClass = Ref.getStorageClass();
1015
280
  } else {
1016
12
    Sym.Type = IMAGE_SYM_TYPE_NULL;
1017
12
    Sym.StorageClass = IMAGE_SYM_CLASS_EXTERNAL;
1018
12
  }
1019
292
  Sym.NumberOfAuxSymbols = 0;
1020
292
  return Sym;
1021
292
}
1022
1023
514
void Writer::createSymbolAndStringTable() {
1024
514
  // PE/COFF images are limited to 8 byte section names. Longer names can be
1025
514
  // supported by writing a non-standard string table, but this string table is
1026
514
  // not mapped at runtime and the long names will therefore be inaccessible.
1027
514
  // link.exe always truncates section names to 8 bytes, whereas binutils always
1028
514
  // preserves long section names via the string table. LLD adopts a hybrid
1029
514
  // solution where discardable sections have long names preserved and
1030
514
  // non-discardable sections have their names truncated, to ensure that any
1031
514
  // section which is mapped at runtime also has its name mapped at runtime.
1032
1.07k
  for (OutputSection *Sec : OutputSections) {
1033
1.07k
    if (Sec->Name.size() <= COFF::NameSize)
1034
1.05k
      continue;
1035
22
    if ((Sec->Header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE) == 0)
1036
4
      continue;
1037
18
    Sec->setStringTableOff(addEntryToStringTable(Sec->Name));
1038
18
  }
1039
514
1040
514
  if (Config->DebugDwarf || 
Config->DebugSymtab503
) {
1041
13
    for (ObjFile *File : ObjFile::Instances) {
1042
399
      for (Symbol *B : File->getSymbols()) {
1043
399
        auto *D = dyn_cast_or_null<Defined>(B);
1044
399
        if (!D || 
D->WrittenToSymtab307
)
1045
92
          continue;
1046
307
        D->WrittenToSymtab = true;
1047
307
1048
307
        if (Optional<coff_symbol16> Sym = createSymbol(D))
1049
292
          OutputSymtab.push_back(*Sym);
1050
307
      }
1051
13
    }
1052
13
  }
1053
514
1054
514
  if (OutputSymtab.empty() && 
Strtab.empty()501
)
1055
495
    return;
1056
19
1057
19
  // We position the symbol table to be adjacent to the end of the last section.
1058
19
  uint64_t FileOff = FileSize;
1059
19
  PointerToSymbolTable = FileOff;
1060
19
  FileOff += OutputSymtab.size() * sizeof(coff_symbol16);
1061
19
  FileOff += 4 + Strtab.size();
1062
19
  FileSize = alignTo(FileOff, SectorSize);
1063
19
}
1064
1065
514
void Writer::mergeSections() {
1066
514
  if (!PdataSec->Chunks.empty()) {
1067
49
    FirstPdata = PdataSec->Chunks.front();
1068
49
    LastPdata = PdataSec->Chunks.back();
1069
49
  }
1070
514
1071
2.70k
  for (auto &P : Config->Merge) {
1072
2.70k
    StringRef ToName = P.second;
1073
2.70k
    if (P.first == ToName)
1074
2
      continue;
1075
2.70k
    StringSet<> Names;
1076
2.70k
    while (1) {
1077
2.70k
      if (!Names.insert(ToName).second)
1078
0
        fatal("/merge: cycle found for section '" + P.first + "'");
1079
2.70k
      auto I = Config->Merge.find(ToName);
1080
2.70k
      if (I == Config->Merge.end())
1081
2.70k
        break;
1082
9
      ToName = I->second;
1083
9
    }
1084
2.70k
    OutputSection *From = findSection(P.first);
1085
2.70k
    OutputSection *To = findSection(ToName);
1086
2.70k
    if (!From)
1087
505
      continue;
1088
2.19k
    if (!To) {
1089
3
      From->Name = ToName;
1090
3
      continue;
1091
3
    }
1092
2.19k
    To->merge(From);
1093
2.19k
  }
1094
514
}
1095
1096
// Visits all sections to initialize their relocation targets.
1097
514
void Writer::readRelocTargets() {
1098
514
  for (OutputSection *Sec : OutputSections)
1099
6.82k
    for_each(parallel::par, Sec->Chunks.begin(), Sec->Chunks.end(),
1100
6.82k
             [&](Chunk *C) 
{ C->readRelocTargets(); }3.80k
);
1101
514
}
1102
1103
// Visits all sections to assign incremental, non-overlapping RVAs and
1104
// file offsets.
1105
519
void Writer::assignAddresses() {
1106
519
  SizeOfHeaders = DOSStubSize + sizeof(PEMagic) + sizeof(coff_file_header) +
1107
519
                  sizeof(data_directory) * NumberOfDataDirectory +
1108
519
                  sizeof(coff_section) * OutputSections.size();
1109
519
  SizeOfHeaders +=
1110
519
      Config->is64() ? 
sizeof(pe32plus_header)410
:
sizeof(pe32_header)109
;
1111
519
  SizeOfHeaders = alignTo(SizeOfHeaders, SectorSize);
1112
519
  uint64_t RVA = PageSize; // The first page is kept unmapped.
1113
519
  FileSize = SizeOfHeaders;
1114
519
1115
1.78k
  for (OutputSection *Sec : OutputSections) {
1116
1.78k
    if (Sec == RelocSec)
1117
519
      addBaserels();
1118
1.78k
    uint64_t RawSize = 0, VirtualSize = 0;
1119
1.78k
    Sec->Header.VirtualAddress = RVA;
1120
4.05k
    for (Chunk *C : Sec->Chunks) {
1121
4.05k
      VirtualSize = alignTo(VirtualSize, C->Alignment);
1122
4.05k
      C->setRVA(RVA + VirtualSize);
1123
4.05k
      C->OutputSectionOff = VirtualSize;
1124
4.05k
      C->finalizeContents();
1125
4.05k
      VirtualSize += C->getSize();
1126
4.05k
      if (C->hasData())
1127
3.59k
        RawSize = alignTo(VirtualSize, SectorSize);
1128
4.05k
    }
1129
1.78k
    if (VirtualSize > UINT32_MAX)
1130
1.78k
      
error("section larger than 4 GiB: " + Sec->Name)1
;
1131
1.78k
    Sec->Header.VirtualSize = VirtualSize;
1132
1.78k
    Sec->Header.SizeOfRawData = RawSize;
1133
1.78k
    if (RawSize != 0)
1134
1.07k
      Sec->Header.PointerToRawData = FileSize;
1135
1.78k
    RVA += alignTo(VirtualSize, PageSize);
1136
1.78k
    FileSize += alignTo(RawSize, SectorSize);
1137
1.78k
  }
1138
519
  SizeOfImage = alignTo(RVA, PageSize);
1139
519
}
1140
1141
514
template <typename PEHeaderTy> void Writer::writeHeader() {
1142
514
  // Write DOS header. For backwards compatibility, the first part of a PE/COFF
1143
514
  // executable consists of an MS-DOS MZ executable. If the executable is run
1144
514
  // under DOS, that program gets run (usually to just print an error message).
1145
514
  // When run under Windows, the loader looks at AddressOfNewExeHeader and uses
1146
514
  // the PE header instead.
1147
514
  uint8_t *Buf = Buffer->getBufferStart();
1148
514
  auto *DOS = reinterpret_cast<dos_header *>(Buf);
1149
514
  Buf += sizeof(dos_header);
1150
514
  DOS->Magic[0] = 'M';
1151
514
  DOS->Magic[1] = 'Z';
1152
514
  DOS->UsedBytesInTheLastPage = DOSStubSize % 512;
1153
514
  DOS->FileSizeInPages = divideCeil(DOSStubSize, 512);
1154
514
  DOS->HeaderSizeInParagraphs = sizeof(dos_header) / 16;
1155
514
1156
514
  DOS->AddressOfRelocationTable = sizeof(dos_header);
1157
514
  DOS->AddressOfNewExeHeader = DOSStubSize;
1158
514
1159
514
  // Write DOS program.
1160
514
  memcpy(Buf, DOSProgram, sizeof(DOSProgram));
1161
514
  Buf += sizeof(DOSProgram);
1162
514
1163
514
  // Write PE magic
1164
514
  memcpy(Buf, PEMagic, sizeof(PEMagic));
1165
514
  Buf += sizeof(PEMagic);
1166
514
1167
514
  // Write COFF header
1168
514
  auto *COFF = reinterpret_cast<coff_file_header *>(Buf);
1169
514
  Buf += sizeof(*COFF);
1170
514
  COFF->Machine = Config->Machine;
1171
514
  COFF->NumberOfSections = OutputSections.size();
1172
514
  COFF->Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
1173
514
  if (Config->LargeAddressAware)
1174
410
    COFF->Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
1175
514
  if (!Config->is64())
1176
105
    COFF->Characteristics |= IMAGE_FILE_32BIT_MACHINE;
1177
514
  if (Config->DLL)
1178
157
    COFF->Characteristics |= IMAGE_FILE_DLL;
1179
514
  if (!Config->Relocatable)
1180
5
    COFF->Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
1181
514
  COFF->SizeOfOptionalHeader =
1182
514
      sizeof(PEHeaderTy) + sizeof(data_directory) * NumberOfDataDirectory;
1183
514
1184
514
  // Write PE header
1185
514
  auto *PE = reinterpret_cast<PEHeaderTy *>(Buf);
1186
514
  Buf += sizeof(*PE);
1187
514
  PE->Magic = Config->is64() ? 
PE32Header::PE32_PLUS409
:
PE32Header::PE32105
;
1188
514
1189
514
  // If {Major,Minor}LinkerVersion is left at 0.0, then for some
1190
514
  // reason signing the resulting PE file with Authenticode produces a
1191
514
  // signature that fails to validate on Windows 7 (but is OK on 10).
1192
514
  // Set it to 14.0, which is what VS2015 outputs, and which avoids
1193
514
  // that problem.
1194
514
  PE->MajorLinkerVersion = 14;
1195
514
  PE->MinorLinkerVersion = 0;
1196
514
1197
514
  PE->ImageBase = Config->ImageBase;
1198
514
  PE->SectionAlignment = PageSize;
1199
514
  PE->FileAlignment = SectorSize;
1200
514
  PE->MajorImageVersion = Config->MajorImageVersion;
1201
514
  PE->MinorImageVersion = Config->MinorImageVersion;
1202
514
  PE->MajorOperatingSystemVersion = Config->MajorOSVersion;
1203
514
  PE->MinorOperatingSystemVersion = Config->MinorOSVersion;
1204
514
  PE->MajorSubsystemVersion = Config->MajorOSVersion;
1205
514
  PE->MinorSubsystemVersion = Config->MinorOSVersion;
1206
514
  PE->Subsystem = Config->Subsystem;
1207
514
  PE->SizeOfImage = SizeOfImage;
1208
514
  PE->SizeOfHeaders = SizeOfHeaders;
1209
514
  if (!Config->NoEntry) {
1210
484
    Defined *Entry = cast<Defined>(Config->Entry);
1211
484
    PE->AddressOfEntryPoint = Entry->getRVA();
1212
484
    // Pointer to thumb code must have the LSB set, so adjust it.
1213
484
    if (Config->Machine == ARMNT)
1214
18
      PE->AddressOfEntryPoint |= 1;
1215
484
  }
1216
514
  PE->SizeOfStackReserve = Config->StackReserve;
1217
514
  PE->SizeOfStackCommit = Config->StackCommit;
1218
514
  PE->SizeOfHeapReserve = Config->HeapReserve;
1219
514
  PE->SizeOfHeapCommit = Config->HeapCommit;
1220
514
  if (Config->AppContainer)
1221
1
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_APPCONTAINER;
1222
514
  if (Config->DynamicBase)
1223
509
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
1224
514
  if (Config->HighEntropyVA)
1225
408
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
1226
514
  if (!Config->AllowBind)
1227
1
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_BIND;
1228
514
  if (Config->NxCompat)
1229
513
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
1230
514
  if (!Config->AllowIsolation)
1231
1
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION;
1232
514
  if (Config->GuardCF != GuardCFLevel::Off)
1233
12
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_GUARD_CF;
1234
514
  if (Config->IntegrityCheck)
1235
1
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY;
1236
514
  if (SetNoSEHCharacteristic)
1237
84
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_SEH;
1238
514
  if (Config->TerminalServerAware)
1239
356
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE;
1240
514
  PE->NumberOfRvaAndSize = NumberOfDataDirectory;
1241
514
  if (TextSec->getVirtualSize()) {
1242
467
    PE->BaseOfCode = TextSec->getRVA();
1243
467
    PE->SizeOfCode = TextSec->getRawSize();
1244
467
  }
1245
514
  PE->SizeOfInitializedData = getSizeOfInitializedData();
1246
514
1247
514
  // Write data directory
1248
514
  auto *Dir = reinterpret_cast<data_directory *>(Buf);
1249
514
  Buf += sizeof(*Dir) * NumberOfDataDirectory;
1250
514
  if (!Config->Exports.empty()) {
1251
112
    Dir[EXPORT_TABLE].RelativeVirtualAddress = Edata.getRVA();
1252
112
    Dir[EXPORT_TABLE].Size = Edata.getSize();
1253
112
  }
1254
514
  if (ImportTableStart) {
1255
46
    Dir[IMPORT_TABLE].RelativeVirtualAddress = ImportTableStart->getRVA();
1256
46
    Dir[IMPORT_TABLE].Size = ImportTableSize;
1257
46
  }
1258
514
  if (IATStart) {
1259
46
    Dir[IAT].RelativeVirtualAddress = IATStart->getRVA();
1260
46
    Dir[IAT].Size = IATSize;
1261
46
  }
1262
514
  if (RsrcSec->getVirtualSize()) {
1263
4
    Dir[RESOURCE_TABLE].RelativeVirtualAddress = RsrcSec->getRVA();
1264
4
    Dir[RESOURCE_TABLE].Size = RsrcSec->getVirtualSize();
1265
4
  }
1266
514
  if (FirstPdata) {
1267
49
    Dir[EXCEPTION_TABLE].RelativeVirtualAddress = FirstPdata->getRVA();
1268
49
    Dir[EXCEPTION_TABLE].Size =
1269
49
        LastPdata->getRVA() + LastPdata->getSize() - FirstPdata->getRVA();
1270
49
  }
1271
514
  if (RelocSec->getVirtualSize()) {
1272
80
    Dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = RelocSec->getRVA();
1273
80
    Dir[BASE_RELOCATION_TABLE].Size = RelocSec->getVirtualSize();
1274
80
  }
1275
514
  if (Symbol *Sym = Symtab->findUnderscore("_tls_used")) {
1276
2
    if (Defined *B = dyn_cast<Defined>(Sym)) {
1277
2
      Dir[TLS_TABLE].RelativeVirtualAddress = B->getRVA();
1278
2
      Dir[TLS_TABLE].Size = Config->is64()
1279
2
                                ? 
sizeof(object::coff_tls_directory64)1
1280
2
                                : 
sizeof(object::coff_tls_directory32)1
;
1281
2
    }
1282
2
  }
1283
514
  if (DebugDirectory) {
1284
111
    Dir[DEBUG_DIRECTORY].RelativeVirtualAddress = DebugDirectory->getRVA();
1285
111
    Dir[DEBUG_DIRECTORY].Size = DebugDirectory->getSize();
1286
111
  }
1287
514
  if (Symbol *Sym = Symtab->findUnderscore("_load_config_used")) {
1288
19
    if (auto *B = dyn_cast<DefinedRegular>(Sym)) {
1289
19
      SectionChunk *SC = B->getChunk();
1290
19
      assert(B->getRVA() >= SC->getRVA());
1291
19
      uint64_t OffsetInChunk = B->getRVA() - SC->getRVA();
1292
19
      if (!SC->hasData() || OffsetInChunk + 4 > SC->getSize())
1293
0
        fatal("_load_config_used is malformed");
1294
19
1295
19
      ArrayRef<uint8_t> SecContents = SC->getContents();
1296
19
      uint32_t LoadConfigSize =
1297
19
          *reinterpret_cast<const ulittle32_t *>(&SecContents[OffsetInChunk]);
1298
19
      if (OffsetInChunk + LoadConfigSize > SC->getSize())
1299
0
        fatal("_load_config_used is too large");
1300
19
      Dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = B->getRVA();
1301
19
      Dir[LOAD_CONFIG_TABLE].Size = LoadConfigSize;
1302
19
    }
1303
19
  }
1304
514
  if (!DelayIdata.empty()) {
1305
4
    Dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
1306
4
        DelayIdata.getDirRVA();
1307
4
    Dir[DELAY_IMPORT_DESCRIPTOR].Size = DelayIdata.getDirSize();
1308
4
  }
1309
514
1310
514
  // Write section table
1311
1.07k
  for (OutputSection *Sec : OutputSections) {
1312
1.07k
    Sec->writeHeaderTo(Buf);
1313
1.07k
    Buf += sizeof(coff_section);
1314
1.07k
  }
1315
514
  SectionTable = ArrayRef<uint8_t>(
1316
514
      Buf - OutputSections.size() * sizeof(coff_section), Buf);
1317
514
1318
514
  if (OutputSymtab.empty() && 
Strtab.empty()501
)
1319
495
    return;
1320
19
1321
19
  COFF->PointerToSymbolTable = PointerToSymbolTable;
1322
19
  uint32_t NumberOfSymbols = OutputSymtab.size();
1323
19
  COFF->NumberOfSymbols = NumberOfSymbols;
1324
19
  auto *SymbolTable = reinterpret_cast<coff_symbol16 *>(
1325
19
      Buffer->getBufferStart() + COFF->PointerToSymbolTable);
1326
311
  for (size_t I = 0; I != NumberOfSymbols; 
++I292
)
1327
292
    SymbolTable[I] = OutputSymtab[I];
1328
19
  // Create the string table, it follows immediately after the symbol table.
1329
19
  // The first 4 bytes is length including itself.
1330
19
  Buf = reinterpret_cast<uint8_t *>(&SymbolTable[NumberOfSymbols]);
1331
19
  write32le(Buf, Strtab.size() + 4);
1332
19
  if (!Strtab.empty())
1333
13
    memcpy(Buf + 4, Strtab.data(), Strtab.size());
1334
19
}
Writer.cpp:void (anonymous namespace)::Writer::writeHeader<llvm::object::pe32plus_header>()
Line
Count
Source
1141
409
template <typename PEHeaderTy> void Writer::writeHeader() {
1142
409
  // Write DOS header. For backwards compatibility, the first part of a PE/COFF
1143
409
  // executable consists of an MS-DOS MZ executable. If the executable is run
1144
409
  // under DOS, that program gets run (usually to just print an error message).
1145
409
  // When run under Windows, the loader looks at AddressOfNewExeHeader and uses
1146
409
  // the PE header instead.
1147
409
  uint8_t *Buf = Buffer->getBufferStart();
1148
409
  auto *DOS = reinterpret_cast<dos_header *>(Buf);
1149
409
  Buf += sizeof(dos_header);
1150
409
  DOS->Magic[0] = 'M';
1151
409
  DOS->Magic[1] = 'Z';
1152
409
  DOS->UsedBytesInTheLastPage = DOSStubSize % 512;
1153
409
  DOS->FileSizeInPages = divideCeil(DOSStubSize, 512);
1154
409
  DOS->HeaderSizeInParagraphs = sizeof(dos_header) / 16;
1155
409
1156
409
  DOS->AddressOfRelocationTable = sizeof(dos_header);
1157
409
  DOS->AddressOfNewExeHeader = DOSStubSize;
1158
409
1159
409
  // Write DOS program.
1160
409
  memcpy(Buf, DOSProgram, sizeof(DOSProgram));
1161
409
  Buf += sizeof(DOSProgram);
1162
409
1163
409
  // Write PE magic
1164
409
  memcpy(Buf, PEMagic, sizeof(PEMagic));
1165
409
  Buf += sizeof(PEMagic);
1166
409
1167
409
  // Write COFF header
1168
409
  auto *COFF = reinterpret_cast<coff_file_header *>(Buf);
1169
409
  Buf += sizeof(*COFF);
1170
409
  COFF->Machine = Config->Machine;
1171
409
  COFF->NumberOfSections = OutputSections.size();
1172
409
  COFF->Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
1173
409
  if (Config->LargeAddressAware)
1174
409
    COFF->Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
1175
409
  if (!Config->is64())
1176
0
    COFF->Characteristics |= IMAGE_FILE_32BIT_MACHINE;
1177
409
  if (Config->DLL)
1178
124
    COFF->Characteristics |= IMAGE_FILE_DLL;
1179
409
  if (!Config->Relocatable)
1180
3
    COFF->Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
1181
409
  COFF->SizeOfOptionalHeader =
1182
409
      sizeof(PEHeaderTy) + sizeof(data_directory) * NumberOfDataDirectory;
1183
409
1184
409
  // Write PE header
1185
409
  auto *PE = reinterpret_cast<PEHeaderTy *>(Buf);
1186
409
  Buf += sizeof(*PE);
1187
409
  PE->Magic = Config->is64() ? PE32Header::PE32_PLUS : 
PE32Header::PE320
;
1188
409
1189
409
  // If {Major,Minor}LinkerVersion is left at 0.0, then for some
1190
409
  // reason signing the resulting PE file with Authenticode produces a
1191
409
  // signature that fails to validate on Windows 7 (but is OK on 10).
1192
409
  // Set it to 14.0, which is what VS2015 outputs, and which avoids
1193
409
  // that problem.
1194
409
  PE->MajorLinkerVersion = 14;
1195
409
  PE->MinorLinkerVersion = 0;
1196
409
1197
409
  PE->ImageBase = Config->ImageBase;
1198
409
  PE->SectionAlignment = PageSize;
1199
409
  PE->FileAlignment = SectorSize;
1200
409
  PE->MajorImageVersion = Config->MajorImageVersion;
1201
409
  PE->MinorImageVersion = Config->MinorImageVersion;
1202
409
  PE->MajorOperatingSystemVersion = Config->MajorOSVersion;
1203
409
  PE->MinorOperatingSystemVersion = Config->MinorOSVersion;
1204
409
  PE->MajorSubsystemVersion = Config->MajorOSVersion;
1205
409
  PE->MinorSubsystemVersion = Config->MinorOSVersion;
1206
409
  PE->Subsystem = Config->Subsystem;
1207
409
  PE->SizeOfImage = SizeOfImage;
1208
409
  PE->SizeOfHeaders = SizeOfHeaders;
1209
409
  if (!Config->NoEntry) {
1210
380
    Defined *Entry = cast<Defined>(Config->Entry);
1211
380
    PE->AddressOfEntryPoint = Entry->getRVA();
1212
380
    // Pointer to thumb code must have the LSB set, so adjust it.
1213
380
    if (Config->Machine == ARMNT)
1214
0
      PE->AddressOfEntryPoint |= 1;
1215
380
  }
1216
409
  PE->SizeOfStackReserve = Config->StackReserve;
1217
409
  PE->SizeOfStackCommit = Config->StackCommit;
1218
409
  PE->SizeOfHeapReserve = Config->HeapReserve;
1219
409
  PE->SizeOfHeapCommit = Config->HeapCommit;
1220
409
  if (Config->AppContainer)
1221
0
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_APPCONTAINER;
1222
409
  if (Config->DynamicBase)
1223
406
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
1224
409
  if (Config->HighEntropyVA)
1225
408
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
1226
409
  if (!Config->AllowBind)
1227
1
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_BIND;
1228
409
  if (Config->NxCompat)
1229
408
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
1230
409
  if (!Config->AllowIsolation)
1231
1
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION;
1232
409
  if (Config->GuardCF != GuardCFLevel::Off)
1233
11
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_GUARD_CF;
1234
409
  if (Config->IntegrityCheck)
1235
1
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY;
1236
409
  if (SetNoSEHCharacteristic)
1237
0
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_SEH;
1238
409
  if (Config->TerminalServerAware)
1239
284
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE;
1240
409
  PE->NumberOfRvaAndSize = NumberOfDataDirectory;
1241
409
  if (TextSec->getVirtualSize()) {
1242
368
    PE->BaseOfCode = TextSec->getRVA();
1243
368
    PE->SizeOfCode = TextSec->getRawSize();
1244
368
  }
1245
409
  PE->SizeOfInitializedData = getSizeOfInitializedData();
1246
409
1247
409
  // Write data directory
1248
409
  auto *Dir = reinterpret_cast<data_directory *>(Buf);
1249
409
  Buf += sizeof(*Dir) * NumberOfDataDirectory;
1250
409
  if (!Config->Exports.empty()) {
1251
86
    Dir[EXPORT_TABLE].RelativeVirtualAddress = Edata.getRVA();
1252
86
    Dir[EXPORT_TABLE].Size = Edata.getSize();
1253
86
  }
1254
409
  if (ImportTableStart) {
1255
33
    Dir[IMPORT_TABLE].RelativeVirtualAddress = ImportTableStart->getRVA();
1256
33
    Dir[IMPORT_TABLE].Size = ImportTableSize;
1257
33
  }
1258
409
  if (IATStart) {
1259
33
    Dir[IAT].RelativeVirtualAddress = IATStart->getRVA();
1260
33
    Dir[IAT].Size = IATSize;
1261
33
  }
1262
409
  if (RsrcSec->getVirtualSize()) {
1263
4
    Dir[RESOURCE_TABLE].RelativeVirtualAddress = RsrcSec->getRVA();
1264
4
    Dir[RESOURCE_TABLE].Size = RsrcSec->getVirtualSize();
1265
4
  }
1266
409
  if (FirstPdata) {
1267
49
    Dir[EXCEPTION_TABLE].RelativeVirtualAddress = FirstPdata->getRVA();
1268
49
    Dir[EXCEPTION_TABLE].Size =
1269
49
        LastPdata->getRVA() + LastPdata->getSize() - FirstPdata->getRVA();
1270
49
  }
1271
409
  if (RelocSec->getVirtualSize()) {
1272
47
    Dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = RelocSec->getRVA();
1273
47
    Dir[BASE_RELOCATION_TABLE].Size = RelocSec->getVirtualSize();
1274
47
  }
1275
409
  if (Symbol *Sym = Symtab->findUnderscore("_tls_used")) {
1276
1
    if (Defined *B = dyn_cast<Defined>(Sym)) {
1277
1
      Dir[TLS_TABLE].RelativeVirtualAddress = B->getRVA();
1278
1
      Dir[TLS_TABLE].Size = Config->is64()
1279
1
                                ? sizeof(object::coff_tls_directory64)
1280
1
                                : 
sizeof(object::coff_tls_directory32)0
;
1281
1
    }
1282
1
  }
1283
409
  if (DebugDirectory) {
1284
80
    Dir[DEBUG_DIRECTORY].RelativeVirtualAddress = DebugDirectory->getRVA();
1285
80
    Dir[DEBUG_DIRECTORY].Size = DebugDirectory->getSize();
1286
80
  }
1287
409
  if (Symbol *Sym = Symtab->findUnderscore("_load_config_used")) {
1288
13
    if (auto *B = dyn_cast<DefinedRegular>(Sym)) {
1289
13
      SectionChunk *SC = B->getChunk();
1290
13
      assert(B->getRVA() >= SC->getRVA());
1291
13
      uint64_t OffsetInChunk = B->getRVA() - SC->getRVA();
1292
13
      if (!SC->hasData() || OffsetInChunk + 4 > SC->getSize())
1293
0
        fatal("_load_config_used is malformed");
1294
13
1295
13
      ArrayRef<uint8_t> SecContents = SC->getContents();
1296
13
      uint32_t LoadConfigSize =
1297
13
          *reinterpret_cast<const ulittle32_t *>(&SecContents[OffsetInChunk]);
1298
13
      if (OffsetInChunk + LoadConfigSize > SC->getSize())
1299
0
        fatal("_load_config_used is too large");
1300
13
      Dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = B->getRVA();
1301
13
      Dir[LOAD_CONFIG_TABLE].Size = LoadConfigSize;
1302
13
    }
1303
13
  }
1304
409
  if (!DelayIdata.empty()) {
1305
2
    Dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
1306
2
        DelayIdata.getDirRVA();
1307
2
    Dir[DELAY_IMPORT_DESCRIPTOR].Size = DelayIdata.getDirSize();
1308
2
  }
1309
409
1310
409
  // Write section table
1311
823
  for (OutputSection *Sec : OutputSections) {
1312
823
    Sec->writeHeaderTo(Buf);
1313
823
    Buf += sizeof(coff_section);
1314
823
  }
1315
409
  SectionTable = ArrayRef<uint8_t>(
1316
409
      Buf - OutputSections.size() * sizeof(coff_section), Buf);
1317
409
1318
409
  if (OutputSymtab.empty() && 
Strtab.empty()400
)
1319
395
    return;
1320
14
1321
14
  COFF->PointerToSymbolTable = PointerToSymbolTable;
1322
14
  uint32_t NumberOfSymbols = OutputSymtab.size();
1323
14
  COFF->NumberOfSymbols = NumberOfSymbols;
1324
14
  auto *SymbolTable = reinterpret_cast<coff_symbol16 *>(
1325
14
      Buffer->getBufferStart() + COFF->PointerToSymbolTable);
1326
274
  for (size_t I = 0; I != NumberOfSymbols; 
++I260
)
1327
260
    SymbolTable[I] = OutputSymtab[I];
1328
14
  // Create the string table, it follows immediately after the symbol table.
1329
14
  // The first 4 bytes is length including itself.
1330
14
  Buf = reinterpret_cast<uint8_t *>(&SymbolTable[NumberOfSymbols]);
1331
14
  write32le(Buf, Strtab.size() + 4);
1332
14
  if (!Strtab.empty())
1333
10
    memcpy(Buf + 4, Strtab.data(), Strtab.size());
1334
14
}
Writer.cpp:void (anonymous namespace)::Writer::writeHeader<llvm::object::pe32_header>()
Line
Count
Source
1141
105
template <typename PEHeaderTy> void Writer::writeHeader() {
1142
105
  // Write DOS header. For backwards compatibility, the first part of a PE/COFF
1143
105
  // executable consists of an MS-DOS MZ executable. If the executable is run
1144
105
  // under DOS, that program gets run (usually to just print an error message).
1145
105
  // When run under Windows, the loader looks at AddressOfNewExeHeader and uses
1146
105
  // the PE header instead.
1147
105
  uint8_t *Buf = Buffer->getBufferStart();
1148
105
  auto *DOS = reinterpret_cast<dos_header *>(Buf);
1149
105
  Buf += sizeof(dos_header);
1150
105
  DOS->Magic[0] = 'M';
1151
105
  DOS->Magic[1] = 'Z';
1152
105
  DOS->UsedBytesInTheLastPage = DOSStubSize % 512;
1153
105
  DOS->FileSizeInPages = divideCeil(DOSStubSize, 512);
1154
105
  DOS->HeaderSizeInParagraphs = sizeof(dos_header) / 16;
1155
105
1156
105
  DOS->AddressOfRelocationTable = sizeof(dos_header);
1157
105
  DOS->AddressOfNewExeHeader = DOSStubSize;
1158
105
1159
105
  // Write DOS program.
1160
105
  memcpy(Buf, DOSProgram, sizeof(DOSProgram));
1161
105
  Buf += sizeof(DOSProgram);
1162
105
1163
105
  // Write PE magic
1164
105
  memcpy(Buf, PEMagic, sizeof(PEMagic));
1165
105
  Buf += sizeof(PEMagic);
1166
105
1167
105
  // Write COFF header
1168
105
  auto *COFF = reinterpret_cast<coff_file_header *>(Buf);
1169
105
  Buf += sizeof(*COFF);
1170
105
  COFF->Machine = Config->Machine;
1171
105
  COFF->NumberOfSections = OutputSections.size();
1172
105
  COFF->Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
1173
105
  if (Config->LargeAddressAware)
1174
1
    COFF->Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
1175
105
  if (!Config->is64())
1176
105
    COFF->Characteristics |= IMAGE_FILE_32BIT_MACHINE;
1177
105
  if (Config->DLL)
1178
33
    COFF->Characteristics |= IMAGE_FILE_DLL;
1179
105
  if (!Config->Relocatable)
1180
2
    COFF->Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
1181
105
  COFF->SizeOfOptionalHeader =
1182
105
      sizeof(PEHeaderTy) + sizeof(data_directory) * NumberOfDataDirectory;
1183
105
1184
105
  // Write PE header
1185
105
  auto *PE = reinterpret_cast<PEHeaderTy *>(Buf);
1186
105
  Buf += sizeof(*PE);
1187
105
  PE->Magic = Config->is64() ? 
PE32Header::PE32_PLUS0
: PE32Header::PE32;
1188
105
1189
105
  // If {Major,Minor}LinkerVersion is left at 0.0, then for some
1190
105
  // reason signing the resulting PE file with Authenticode produces a
1191
105
  // signature that fails to validate on Windows 7 (but is OK on 10).
1192
105
  // Set it to 14.0, which is what VS2015 outputs, and which avoids
1193
105
  // that problem.
1194
105
  PE->MajorLinkerVersion = 14;
1195
105
  PE->MinorLinkerVersion = 0;
1196
105
1197
105
  PE->ImageBase = Config->ImageBase;
1198
105
  PE->SectionAlignment = PageSize;
1199
105
  PE->FileAlignment = SectorSize;
1200
105
  PE->MajorImageVersion = Config->MajorImageVersion;
1201
105
  PE->MinorImageVersion = Config->MinorImageVersion;
1202
105
  PE->MajorOperatingSystemVersion = Config->MajorOSVersion;
1203
105
  PE->MinorOperatingSystemVersion = Config->MinorOSVersion;
1204
105
  PE->MajorSubsystemVersion = Config->MajorOSVersion;
1205
105
  PE->MinorSubsystemVersion = Config->MinorOSVersion;
1206
105
  PE->Subsystem = Config->Subsystem;
1207
105
  PE->SizeOfImage = SizeOfImage;
1208
105
  PE->SizeOfHeaders = SizeOfHeaders;
1209
105
  if (!Config->NoEntry) {
1210
104
    Defined *Entry = cast<Defined>(Config->Entry);
1211
104
    PE->AddressOfEntryPoint = Entry->getRVA();
1212
104
    // Pointer to thumb code must have the LSB set, so adjust it.
1213
104
    if (Config->Machine == ARMNT)
1214
18
      PE->AddressOfEntryPoint |= 1;
1215
104
  }
1216
105
  PE->SizeOfStackReserve = Config->StackReserve;
1217
105
  PE->SizeOfStackCommit = Config->StackCommit;
1218
105
  PE->SizeOfHeapReserve = Config->HeapReserve;
1219
105
  PE->SizeOfHeapCommit = Config->HeapCommit;
1220
105
  if (Config->AppContainer)
1221
1
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_APPCONTAINER;
1222
105
  if (Config->DynamicBase)
1223
103
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
1224
105
  if (Config->HighEntropyVA)
1225
0
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
1226
105
  if (!Config->AllowBind)
1227
0
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_BIND;
1228
105
  if (Config->NxCompat)
1229
105
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
1230
105
  if (!Config->AllowIsolation)
1231
0
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION;
1232
105
  if (Config->GuardCF != GuardCFLevel::Off)
1233
1
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_GUARD_CF;
1234
105
  if (Config->IntegrityCheck)
1235
0
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY;
1236
105
  if (SetNoSEHCharacteristic)
1237
84
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_SEH;
1238
105
  if (Config->TerminalServerAware)
1239
72
    PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE;
1240
105
  PE->NumberOfRvaAndSize = NumberOfDataDirectory;
1241
105
  if (TextSec->getVirtualSize()) {
1242
99
    PE->BaseOfCode = TextSec->getRVA();
1243
99
    PE->SizeOfCode = TextSec->getRawSize();
1244
99
  }
1245
105
  PE->SizeOfInitializedData = getSizeOfInitializedData();
1246
105
1247
105
  // Write data directory
1248
105
  auto *Dir = reinterpret_cast<data_directory *>(Buf);
1249
105
  Buf += sizeof(*Dir) * NumberOfDataDirectory;
1250
105
  if (!Config->Exports.empty()) {
1251
26
    Dir[EXPORT_TABLE].RelativeVirtualAddress = Edata.getRVA();
1252
26
    Dir[EXPORT_TABLE].Size = Edata.getSize();
1253
26
  }
1254
105
  if (ImportTableStart) {
1255
13
    Dir[IMPORT_TABLE].RelativeVirtualAddress = ImportTableStart->getRVA();
1256
13
    Dir[IMPORT_TABLE].Size = ImportTableSize;
1257
13
  }
1258
105
  if (IATStart) {
1259
13
    Dir[IAT].RelativeVirtualAddress = IATStart->getRVA();
1260
13
    Dir[IAT].Size = IATSize;
1261
13
  }
1262
105
  if (RsrcSec->getVirtualSize()) {
1263
0
    Dir[RESOURCE_TABLE].RelativeVirtualAddress = RsrcSec->getRVA();
1264
0
    Dir[RESOURCE_TABLE].Size = RsrcSec->getVirtualSize();
1265
0
  }
1266
105
  if (FirstPdata) {
1267
0
    Dir[EXCEPTION_TABLE].RelativeVirtualAddress = FirstPdata->getRVA();
1268
0
    Dir[EXCEPTION_TABLE].Size =
1269
0
        LastPdata->getRVA() + LastPdata->getSize() - FirstPdata->getRVA();
1270
0
  }
1271
105
  if (RelocSec->getVirtualSize()) {
1272
33
    Dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = RelocSec->getRVA();
1273
33
    Dir[BASE_RELOCATION_TABLE].Size = RelocSec->getVirtualSize();
1274
33
  }
1275
105
  if (Symbol *Sym = Symtab->findUnderscore("_tls_used")) {
1276
1
    if (Defined *B = dyn_cast<Defined>(Sym)) {
1277
1
      Dir[TLS_TABLE].RelativeVirtualAddress = B->getRVA();
1278
1
      Dir[TLS_TABLE].Size = Config->is64()
1279
1
                                ? 
sizeof(object::coff_tls_directory64)0
1280
1
                                : sizeof(object::coff_tls_directory32);
1281
1
    }
1282
1
  }
1283
105
  if (DebugDirectory) {
1284
31
    Dir[DEBUG_DIRECTORY].RelativeVirtualAddress = DebugDirectory->getRVA();
1285
31
    Dir[DEBUG_DIRECTORY].Size = DebugDirectory->getSize();
1286
31
  }
1287
105
  if (Symbol *Sym = Symtab->findUnderscore("_load_config_used")) {
1288
6
    if (auto *B = dyn_cast<DefinedRegular>(Sym)) {
1289
6
      SectionChunk *SC = B->getChunk();
1290
6
      assert(B->getRVA() >= SC->getRVA());
1291
6
      uint64_t OffsetInChunk = B->getRVA() - SC->getRVA();
1292
6
      if (!SC->hasData() || OffsetInChunk + 4 > SC->getSize())
1293
0
        fatal("_load_config_used is malformed");
1294
6
1295
6
      ArrayRef<uint8_t> SecContents = SC->getContents();
1296
6
      uint32_t LoadConfigSize =
1297
6
          *reinterpret_cast<const ulittle32_t *>(&SecContents[OffsetInChunk]);
1298
6
      if (OffsetInChunk + LoadConfigSize > SC->getSize())
1299
0
        fatal("_load_config_used is too large");
1300
6
      Dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = B->getRVA();
1301
6
      Dir[LOAD_CONFIG_TABLE].Size = LoadConfigSize;
1302
6
    }
1303
6
  }
1304
105
  if (!DelayIdata.empty()) {
1305
2
    Dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
1306
2
        DelayIdata.getDirRVA();
1307
2
    Dir[DELAY_IMPORT_DESCRIPTOR].Size = DelayIdata.getDirSize();
1308
2
  }
1309
105
1310
105
  // Write section table
1311
253
  for (OutputSection *Sec : OutputSections) {
1312
253
    Sec->writeHeaderTo(Buf);
1313
253
    Buf += sizeof(coff_section);
1314
253
  }
1315
105
  SectionTable = ArrayRef<uint8_t>(
1316
105
      Buf - OutputSections.size() * sizeof(coff_section), Buf);
1317
105
1318
105
  if (OutputSymtab.empty() && 
Strtab.empty()101
)
1319
100
    return;
1320
5
1321
5
  COFF->PointerToSymbolTable = PointerToSymbolTable;
1322
5
  uint32_t NumberOfSymbols = OutputSymtab.size();
1323
5
  COFF->NumberOfSymbols = NumberOfSymbols;
1324
5
  auto *SymbolTable = reinterpret_cast<coff_symbol16 *>(
1325
5
      Buffer->getBufferStart() + COFF->PointerToSymbolTable);
1326
37
  for (size_t I = 0; I != NumberOfSymbols; 
++I32
)
1327
32
    SymbolTable[I] = OutputSymtab[I];
1328
5
  // Create the string table, it follows immediately after the symbol table.
1329
5
  // The first 4 bytes is length including itself.
1330
5
  Buf = reinterpret_cast<uint8_t *>(&SymbolTable[NumberOfSymbols]);
1331
5
  write32le(Buf, Strtab.size() + 4);
1332
5
  if (!Strtab.empty())
1333
3
    memcpy(Buf + 4, Strtab.data(), Strtab.size());
1334
5
}
1335
1336
514
void Writer::openFile(StringRef Path) {
1337
514
  Buffer = CHECK(
1338
514
      FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable),
1339
514
      "failed to open " + Path);
1340
514
}
1341
1342
87
void Writer::createSEHTable() {
1343
87
  // Set the no SEH characteristic on x86 binaries unless we find exception
1344
87
  // handlers.
1345
87
  SetNoSEHCharacteristic = true;
1346
87
1347
87
  SymbolRVASet Handlers;
1348
91
  for (ObjFile *File : ObjFile::Instances) {
1349
91
    // FIXME: We should error here instead of earlier unless /safeseh:no was
1350
91
    // passed.
1351
91
    if (!File->hasSafeSEH())
1352
49
      return;
1353
42
1354
42
    markSymbolsForRVATable(File, File->getSXDataChunks(), Handlers);
1355
42
  }
1356
87
1357
87
  // Remove the "no SEH" characteristic if all object files were built with
1358
87
  // safeseh, we found some exception handlers, and there is a load config in
1359
87
  // the object.
1360
87
  SetNoSEHCharacteristic =
1361
38
      Handlers.empty() || 
!Symtab->findUnderscore("_load_config_used")6
;
1362
38
1363
38
  maybeAddRVATable(std::move(Handlers), "__safe_se_handler_table",
1364
38
                   "__safe_se_handler_count");
1365
38
}
1366
1367
// Add a symbol to an RVA set. Two symbols may have the same RVA, but an RVA set
1368
// cannot contain duplicates. Therefore, the set is uniqued by Chunk and the
1369
// symbol's offset into that Chunk.
1370
36
static void addSymbolToRVASet(SymbolRVASet &RVASet, Defined *S) {
1371
36
  Chunk *C = S->getChunk();
1372
36
  if (auto *SC = dyn_cast<SectionChunk>(C))
1373
35
    C = SC->Repl; // Look through ICF replacement.
1374
36
  uint32_t Off = S->getRVA() - (C ? C->getRVA() : 
00
);
1375
36
  RVASet.insert({C, Off});
1376
36
}
1377
1378
// Given a symbol, add it to the GFIDs table if it is a live, defined, function
1379
// symbol in an executable section.
1380
static void maybeAddAddressTakenFunction(SymbolRVASet &AddressTakenSyms,
1381
43
                                         Symbol *S) {
1382
43
  auto *D = dyn_cast_or_null<DefinedCOFF>(S);
1383
43
1384
43
  // Ignore undefined symbols and references to non-functions (e.g. globals and
1385
43
  // labels).
1386
43
  if (!D ||
1387
43
      
D->getCOFFSymbol().getComplexType() != COFF::IMAGE_SYM_DTYPE_FUNCTION27
)
1388
24
    return;
1389
19
1390
19
  // Mark the symbol as address taken if it's in an executable section.
1391
19
  Chunk *RefChunk = D->getChunk();
1392
19
  OutputSection *OS = RefChunk ? RefChunk->getOutputSection() : 
nullptr0
;
1393
19
  if (OS && OS->Header.Characteristics & IMAGE_SCN_MEM_EXECUTE)
1394
19
    addSymbolToRVASet(AddressTakenSyms, D);
1395
19
}
1396
1397
// Visit all relocations from all section contributions of this object file and
1398
// mark the relocation target as address-taken.
1399
static void markSymbolsWithRelocations(ObjFile *File,
1400
7
                                       SymbolRVASet &UsedSymbols) {
1401
42
  for (Chunk *C : File->getChunks()) {
1402
42
    // We only care about live section chunks. Common chunks and other chunks
1403
42
    // don't generally contain relocations.
1404
42
    SectionChunk *SC = dyn_cast<SectionChunk>(C);
1405
42
    if (!SC || !SC->Live)
1406
0
      continue;
1407
42
1408
42
    for (const coff_relocation &Reloc : SC->Relocs) {
1409
30
      if (Config->Machine == I386 && 
Reloc.Type == COFF::IMAGE_REL_I386_REL327
)
1410
1
        // Ignore relative relocations on x86. On x86_64 they can't be ignored
1411
1
        // since they're also used to compute absolute addresses.
1412
1
        continue;
1413
29
1414
29
      Symbol *Ref = SC->File->getSymbol(Reloc.SymbolTableIndex);
1415
29
      maybeAddAddressTakenFunction(UsedSymbols, Ref);
1416
29
    }
1417
42
  }
1418
7
}
1419
1420
// Create the guard function id table. This is a table of RVAs of all
1421
// address-taken functions. It is sorted and uniqued, just like the safe SEH
1422
// table.
1423
12
void Writer::createGuardCFTables() {
1424
12
  SymbolRVASet AddressTakenSyms;
1425
12
  SymbolRVASet LongJmpTargets;
1426
15
  for (ObjFile *File : ObjFile::Instances) {
1427
15
    // If the object was compiled with /guard:cf, the address taken symbols
1428
15
    // are in .gfids$y sections, and the longjmp targets are in .gljmp$y
1429
15
    // sections. If the object was not compiled with /guard:cf, we assume there
1430
15
    // were no setjmp targets, and that all code symbols with relocations are
1431
15
    // possibly address-taken.
1432
15
    if (File->hasGuardCF()) {
1433
8
      markSymbolsForRVATable(File, File->getGuardFidChunks(), AddressTakenSyms);
1434
8
      markSymbolsForRVATable(File, File->getGuardLJmpChunks(), LongJmpTargets);
1435
8
    } else {
1436
7
      markSymbolsWithRelocations(File, AddressTakenSyms);
1437
7
    }
1438
15
  }
1439
12
1440
12
  // Mark the image entry as address-taken.
1441
12
  if (Config->Entry)
1442
11
    maybeAddAddressTakenFunction(AddressTakenSyms, Config->Entry);
1443
12
1444
12
  // Mark exported symbols in executable sections as address-taken.
1445
12
  for (Export &E : Config->Exports)
1446
3
    maybeAddAddressTakenFunction(AddressTakenSyms, E.Sym);
1447
12
1448
12
  // Ensure sections referenced in the gfid table are 16-byte aligned.
1449
12
  for (const ChunkAndOffset &C : AddressTakenSyms)
1450
25
    if (C.InputChunk->Alignment < 16)
1451
17
      C.InputChunk->Alignment = 16;
1452
12
1453
12
  maybeAddRVATable(std::move(AddressTakenSyms), "__guard_fids_table",
1454
12
                   "__guard_fids_count");
1455
12
1456
12
  // Add the longjmp target table unless the user told us not to.
1457
12
  if (Config->GuardCF == GuardCFLevel::Full)
1458
6
    maybeAddRVATable(std::move(LongJmpTargets), "__guard_longjmp_table",
1459
6
                     "__guard_longjmp_count");
1460
12
1461
12
  // Set __guard_flags, which will be used in the load config to indicate that
1462
12
  // /guard:cf was enabled.
1463
12
  uint32_t GuardFlags = uint32_t(coff_guard_flags::CFInstrumented) |
1464
12
                        uint32_t(coff_guard_flags::HasFidTable);
1465
12
  if (Config->GuardCF == GuardCFLevel::Full)
1466
6
    GuardFlags |= uint32_t(coff_guard_flags::HasLongJmpTable);
1467
12
  Symbol *FlagSym = Symtab->findUnderscore("__guard_flags");
1468
12
  cast<DefinedAbsolute>(FlagSym)->setVA(GuardFlags);
1469
12
}
1470
1471
// Take a list of input sections containing symbol table indices and add those
1472
// symbols to an RVA table. The challenge is that symbol RVAs are not known and
1473
// depend on the table size, so we can't directly build a set of integers.
1474
void Writer::markSymbolsForRVATable(ObjFile *File,
1475
                                    ArrayRef<SectionChunk *> SymIdxChunks,
1476
58
                                    SymbolRVASet &TableSymbols) {
1477
58
  for (SectionChunk *C : SymIdxChunks) {
1478
19
    // Skip sections discarded by linker GC. This comes up when a .gfids section
1479
19
    // is associated with something like a vtable and the vtable is discarded.
1480
19
    // In this case, the associated gfids section is discarded, and we don't
1481
19
    // mark the virtual member functions as address-taken by the vtable.
1482
19
    if (!C->Live)
1483
1
      continue;
1484
18
1485
18
    // Validate that the contents look like symbol table indices.
1486
18
    ArrayRef<uint8_t> Data = C->getContents();
1487
18
    if (Data.size() % 4 != 0) {
1488
1
      warn("ignoring " + C->getSectionName() +
1489
1
           " symbol table index section in object " + toString(File));
1490
1
      continue;
1491
1
    }
1492
17
1493
17
    // Read each symbol table index and check if that symbol was included in the
1494
17
    // final link. If so, add it to the table symbol set.
1495
17
    ArrayRef<ulittle32_t> SymIndices(
1496
17
        reinterpret_cast<const ulittle32_t *>(Data.data()), Data.size() / 4);
1497
17
    ArrayRef<Symbol *> ObjSymbols = File->getSymbols();
1498
20
    for (uint32_t SymIndex : SymIndices) {
1499
20
      if (SymIndex >= ObjSymbols.size()) {
1500
1
        warn("ignoring invalid symbol table index in section " +
1501
1
             C->getSectionName() + " in object " + toString(File));
1502
1
        continue;
1503
1
      }
1504
19
      if (Symbol *S = ObjSymbols[SymIndex]) {
1505
18
        if (S->isLive())
1506
17
          addSymbolToRVASet(TableSymbols, cast<Defined>(S));
1507
18
      }
1508
19
    }
1509
17
  }
1510
58
}
1511
1512
// Replace the absolute table symbol with a synthetic symbol pointing to
1513
// TableChunk so that we can emit base relocations for it and resolve section
1514
// relative relocations.
1515
void Writer::maybeAddRVATable(SymbolRVASet TableSymbols, StringRef TableSym,
1516
56
                              StringRef CountSym) {
1517
56
  if (TableSymbols.empty())
1518
37
    return;
1519
19
1520
19
  RVATableChunk *TableChunk = make<RVATableChunk>(std::move(TableSymbols));
1521
19
  RdataSec->addChunk(TableChunk);
1522
19
1523
19
  Symbol *T = Symtab->findUnderscore(TableSym);
1524
19
  Symbol *C = Symtab->findUnderscore(CountSym);
1525
19
  replaceSymbol<DefinedSynthetic>(T, T->getName(), TableChunk);
1526
19
  cast<DefinedAbsolute>(C)->setVA(TableChunk->getSize() / 4);
1527
19
}
1528
1529
// MinGW specific. Gather all relocations that are imported from a DLL even
1530
// though the code didn't expect it to, produce the table that the runtime
1531
// uses for fixing them up, and provide the synthetic symbols that the
1532
// runtime uses for finding the table.
1533
41
void Writer::createRuntimePseudoRelocs() {
1534
41
  std::vector<RuntimePseudoReloc> Rels;
1535
41
1536
225
  for (Chunk *C : Symtab->getChunks()) {
1537
225
    auto *SC = dyn_cast<SectionChunk>(C);
1538
225
    if (!SC || 
!SC->Live224
)
1539
4
      continue;
1540
221
    SC->getRuntimePseudoRelocs(Rels);
1541
221
  }
1542
41
1543
41
  if (!Rels.empty())
1544
4
    log("Writing " + Twine(Rels.size()) + " runtime pseudo relocations");
1545
41
  PseudoRelocTableChunk *Table = make<PseudoRelocTableChunk>(Rels);
1546
41
  RdataSec->addChunk(Table);
1547
41
  EmptyChunk *EndOfList = make<EmptyChunk>();
1548
41
  RdataSec->addChunk(EndOfList);
1549
41
1550
41
  Symbol *HeadSym = Symtab->findUnderscore("__RUNTIME_PSEUDO_RELOC_LIST__");
1551
41
  Symbol *EndSym = Symtab->findUnderscore("__RUNTIME_PSEUDO_RELOC_LIST_END__");
1552
41
  replaceSymbol<DefinedSynthetic>(HeadSym, HeadSym->getName(), Table);
1553
41
  replaceSymbol<DefinedSynthetic>(EndSym, EndSym->getName(), EndOfList);
1554
41
}
1555
1556
// MinGW specific.
1557
// The MinGW .ctors and .dtors lists have sentinels at each end;
1558
// a (uintptr_t)-1 at the start and a (uintptr_t)0 at the end.
1559
// There's a symbol pointing to the start sentinel pointer, __CTOR_LIST__
1560
// and __DTOR_LIST__ respectively.
1561
41
void Writer::insertCtorDtorSymbols() {
1562
41
  AbsolutePointerChunk *CtorListHead = make<AbsolutePointerChunk>(-1);
1563
41
  AbsolutePointerChunk *CtorListEnd = make<AbsolutePointerChunk>(0);
1564
41
  AbsolutePointerChunk *DtorListHead = make<AbsolutePointerChunk>(-1);
1565
41
  AbsolutePointerChunk *DtorListEnd = make<AbsolutePointerChunk>(0);
1566
41
  CtorsSec->insertChunkAtStart(CtorListHead);
1567
41
  CtorsSec->addChunk(CtorListEnd);
1568
41
  DtorsSec->insertChunkAtStart(DtorListHead);
1569
41
  DtorsSec->addChunk(DtorListEnd);
1570
41
1571
41
  Symbol *CtorListSym = Symtab->findUnderscore("__CTOR_LIST__");
1572
41
  Symbol *DtorListSym = Symtab->findUnderscore("__DTOR_LIST__");
1573
41
  replaceSymbol<DefinedSynthetic>(CtorListSym, CtorListSym->getName(),
1574
41
                                  CtorListHead);
1575
41
  replaceSymbol<DefinedSynthetic>(DtorListSym, DtorListSym->getName(),
1576
41
                                  DtorListHead);
1577
41
}
1578
1579
// Handles /section options to allow users to overwrite
1580
// section attributes.
1581
514
void Writer::setSectionPermissions() {
1582
514
  for (auto &P : Config->Section) {
1583
6
    StringRef Name = P.first;
1584
6
    uint32_t Perm = P.second;
1585
6
    for (OutputSection *Sec : OutputSections)
1586
11
      if (Sec->Name == Name)
1587
7
        Sec->setPermissions(Perm);
1588
6
  }
1589
514
}
1590
1591
// Write section contents to a mmap'ed file.
1592
514
void Writer::writeSections() {
1593
514
  // Record the number of sections to apply section index relocations
1594
514
  // against absolute symbols. See applySecIdx in Chunks.cpp..
1595
514
  DefinedAbsolute::NumOutputSections = OutputSections.size();
1596
514
1597
514
  uint8_t *Buf = Buffer->getBufferStart();
1598
1.07k
  for (OutputSection *Sec : OutputSections) {
1599
1.07k
    uint8_t *SecBuf = Buf + Sec->getFileOff();
1600
1.07k
    // Fill gaps between functions in .text with INT3 instructions
1601
1.07k
    // instead of leaving as NUL bytes (which can be interpreted as
1602
1.07k
    // ADD instructions).
1603
1.07k
    if (Sec->Header.Characteristics & IMAGE_SCN_CNT_CODE)
1604
480
      memset(SecBuf, 0xCC, Sec->getRawSize());
1605
1.07k
    for_each(parallel::par, Sec->Chunks.begin(), Sec->Chunks.end(),
1606
3.36k
             [&](Chunk *C) { C->writeTo(SecBuf); });
1607
1.07k
  }
1608
514
}
1609
1610
514
void Writer::writeBuildId() {
1611
514
  // There are two important parts to the build ID.
1612
514
  // 1) If building with debug info, the COFF debug directory contains a
1613
514
  //    timestamp as well as a Guid and Age of the PDB.
1614
514
  // 2) In all cases, the PE COFF file header also contains a timestamp.
1615
514
  // For reproducibility, instead of a timestamp we want to use a hash of the
1616
514
  // PE contents.
1617
514
  if (Config->Debug) {
1618
110
    assert(BuildId && "BuildId is not set!");
1619
110
    // BuildId->BuildId was filled in when the PDB was written.
1620
110
  }
1621
514
1622
514
  // At this point the only fields in the COFF file which remain unset are the
1623
514
  // "timestamp" in the COFF file header, and the ones in the coff debug
1624
514
  // directory.  Now we can hash the file and write that hash to the various
1625
514
  // timestamp fields in the file.
1626
514
  StringRef OutputFileData(
1627
514
      reinterpret_cast<const char *>(Buffer->getBufferStart()),
1628
514
      Buffer->getBufferSize());
1629
514
1630
514
  uint32_t Timestamp = Config->Timestamp;
1631
514
  uint64_t Hash = 0;
1632
514
  bool GenerateSyntheticBuildId =
1633
514
      Config->MinGW && 
Config->Debug41
&&
Config->PDBPath.empty()2
;
1634
514
1635
514
  if (Config->Repro || 
GenerateSyntheticBuildId510
)
1636
6
    Hash = xxHash64(OutputFileData);
1637
514
1638
514
  if (Config->Repro)
1639
4
    Timestamp = static_cast<uint32_t>(Hash);
1640
514
1641
514
  if (GenerateSyntheticBuildId) {
1642
2
    // For MinGW builds without a PDB file, we still generate a build id
1643
2
    // to allow associating a crash dump to the executable.
1644
2
    BuildId->BuildId->PDB70.CVSignature = OMF::Signature::PDB70;
1645
2
    BuildId->BuildId->PDB70.Age = 1;
1646
2
    memcpy(BuildId->BuildId->PDB70.Signature, &Hash, 8);
1647
2
    // xxhash only gives us 8 bytes, so put some fixed data in the other half.
1648
2
    memcpy(&BuildId->BuildId->PDB70.Signature[8], "LLD PDB.", 8);
1649
2
  }
1650
514
1651
514
  if (DebugDirectory)
1652
111
    DebugDirectory->setTimeDateStamp(Timestamp);
1653
514
1654
514
  uint8_t *Buf = Buffer->getBufferStart();
1655
514
  Buf += DOSStubSize + sizeof(PEMagic);
1656
514
  object::coff_file_header *CoffHeader =
1657
514
      reinterpret_cast<coff_file_header *>(Buf);
1658
514
  CoffHeader->TimeDateStamp = Timestamp;
1659
514
}
1660
1661
// Sort .pdata section contents according to PE/COFF spec 5.5.
1662
514
void Writer::sortExceptionTable() {
1663
514
  if (!FirstPdata)
1664
465
    return;
1665
49
  // We assume .pdata contains function table entries only.
1666
98
  
auto BufAddr = [&](Chunk *C) 49
{
1667
98
    return Buffer->getBufferStart() + C->getOutputSection()->getFileOff() +
1668
98
           C->getRVA() - C->getOutputSection()->getRVA();
1669
98
  };
1670
49
  uint8_t *Begin = BufAddr(FirstPdata);
1671
49
  uint8_t *End = BufAddr(LastPdata) + LastPdata->getSize();
1672
49
  if (Config->Machine == AMD64) {
1673
48
    struct Entry { ulittle32_t Begin, End, Unwind; };
1674
48
    sort(parallel::par, (Entry *)Begin, (Entry *)End,
1675
48
         [](const Entry &A, const Entry &B) 
{ return A.Begin < B.Begin; }33
);
1676
48
    return;
1677
48
  }
1678
1
  if (Config->Machine == ARMNT || Config->Machine == ARM64) {
1679
1
    struct Entry { ulittle32_t Begin, Unwind; };
1680
1
    sort(parallel::par, (Entry *)Begin, (Entry *)End,
1681
1
         [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
1682
1
    return;
1683
1
  }
1684
0
  errs() << "warning: don't know how to handle .pdata.\n";
1685
0
}
1686
1687
// The CRT section contains, among other things, the array of function
1688
// pointers that initialize every global variable that is not trivially
1689
// constructed. The CRT calls them one after the other prior to invoking
1690
// main().
1691
//
1692
// As per C++ spec, 3.6.2/2.3,
1693
// "Variables with ordered initialization defined within a single
1694
// translation unit shall be initialized in the order of their definitions
1695
// in the translation unit"
1696
//
1697
// It is therefore critical to sort the chunks containing the function
1698
// pointers in the order that they are listed in the object file (top to
1699
// bottom), otherwise global objects might not be initialized in the
1700
// correct order.
1701
22
void Writer::sortCRTSectionChunks(std::vector<Chunk *> &Chunks) {
1702
48
  auto SectionChunkOrder = [](const Chunk *A, const Chunk *B) {
1703
48
    auto SA = dyn_cast<SectionChunk>(A);
1704
48
    auto SB = dyn_cast<SectionChunk>(B);
1705
48
    assert(SA && SB && "Non-section chunks in CRT section!");
1706
48
1707
48
    StringRef SAObj = SA->File->MB.getBufferIdentifier();
1708
48
    StringRef SBObj = SB->File->MB.getBufferIdentifier();
1709
48
1710
48
    return SAObj == SBObj && 
SA->getSectionNumber() < SB->getSectionNumber()36
;
1711
48
  };
1712
22
  std::stable_sort(Chunks.begin(), Chunks.end(), SectionChunkOrder);
1713
22
1714
22
  if (Config->Verbose) {
1715
0
    for (auto &C : Chunks) {
1716
0
      auto SC = dyn_cast<SectionChunk>(C);
1717
0
      log("  " + SC->File->MB.getBufferIdentifier().str() +
1718
0
          ", SectionID: " + Twine(SC->getSectionNumber()));
1719
0
    }
1720
0
  }
1721
22
}
1722
1723
5.40k
OutputSection *Writer::findSection(StringRef Name) {
1724
5.40k
  for (OutputSection *Sec : OutputSections)
1725
30.7k
    if (Sec->Name == Name)
1726
4.89k
      return Sec;
1727
5.40k
  
return nullptr508
;
1728
5.40k
}
1729
1730
514
uint32_t Writer::getSizeOfInitializedData() {
1731
514
  uint32_t Res = 0;
1732
514
  for (OutputSection *S : OutputSections)
1733
1.07k
    if (S->Header.Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
1734
595
      Res += S->getRawSize();
1735
514
  return Res;
1736
514
}
1737
1738
// Add base relocations to .reloc section.
1739
519
void Writer::addBaserels() {
1740
519
  if (!Config->Relocatable)
1741
5
    return;
1742
514
  RelocSec->Chunks.clear();
1743
514
  std::vector<Baserel> V;
1744
1.76k
  for (OutputSection *Sec : OutputSections) {
1745
1.76k
    if (Sec->Header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE)
1746
541
      continue;
1747
1.22k
    // Collect all locations for base relocations.
1748
1.22k
    for (Chunk *C : Sec->Chunks)
1749
3.86k
      C->getBaserels(&V);
1750
1.22k
    // Add the addresses to .reloc section.
1751
1.22k
    if (!V.empty())
1752
99
      addBaserelBlocks(V);
1753
1.22k
    V.clear();
1754
1.22k
  }
1755
514
}
1756
1757
// Add addresses to .reloc section. Note that addresses are grouped by page.
1758
99
void Writer::addBaserelBlocks(std::vector<Baserel> &V) {
1759
99
  const uint32_t Mask = ~uint32_t(PageSize - 1);
1760
99
  uint32_t Page = V[0].RVA & Mask;
1761
99
  size_t I = 0, J = 1;
1762
209
  for (size_t E = V.size(); J < E; 
++J110
) {
1763
110
    uint32_t P = V[J].RVA & Mask;
1764
110
    if (P == Page)
1765
110
      continue;
1766
0
    RelocSec->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
1767
0
    I = J;
1768
0
    Page = P;
1769
0
  }
1770
99
  if (I == J)
1771
0
    return;
1772
99
  RelocSec->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
1773
99
}
1774
1775
PartialSection *Writer::createPartialSection(StringRef Name,
1776
2.17k
                                             uint32_t OutChars) {
1777
2.17k
  PartialSection *&PSec = PartialSections[{Name, OutChars}];
1778
2.17k
  if (PSec)
1779
605
    return PSec;
1780
1.56k
  PSec = make<PartialSection>(Name, OutChars);
1781
1.56k
  return PSec;
1782
1.56k
}
1783
1784
92
PartialSection *Writer::findPartialSection(StringRef Name, uint32_t OutChars) {
1785
92
  auto It = PartialSections.find({Name, OutChars});
1786
92
  if (It != PartialSections.end())
1787
92
    return It->second;
1788
0
  return nullptr;
1789
0
}