Coverage Report

Created: 2018-10-20 12:32

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