Coverage Report

Created: 2018-12-09 11:54

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