Coverage Report

Created: 2019-05-22 02:55

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