summaryrefslogtreecommitdiffstats
path: root/lld/lib/ReaderWriter/PECOFF/WriterPECOFF.cpp
blob: 55d6245e26fc58f088b480d3c22d9f3997d51167 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
//===- lib/ReaderWriter/PECOFF/WriterPECOFF.cpp ---------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// PE/COFF file consists of DOS Header, PE Header, COFF Header and Section
/// Tables followed by raw section data.
///
/// This writer is responsible for writing Core Linker results to an Windows
/// executable file. Currently it can only output ".text" section; other
/// sections including the symbol table are silently ignored.
///
/// This writer currently supports 32 bit PE/COFF for x86 processor only.
///
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "WriterPECOFF"

#include <algorithm>
#include <map>
#include <time.h>
#include <vector>

#include "Atoms.h"

#include "lld/Core/DefinedAtom.h"
#include "lld/Core/File.h"
#include "lld/ReaderWriter/AtomLayout.h"
#include "lld/ReaderWriter/PECOFFLinkingContext.h"
#include "lld/ReaderWriter/Writer.h"

#include "llvm/ADT/ArrayRef.h"
#include "llvm/Object/COFF.h"
#include "llvm/Support/COFF.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/FileOutputBuffer.h"
#include "llvm/Support/Format.h"

using llvm::support::ulittle16_t;
using llvm::support::ulittle32_t;
using llvm::COFF::DataDirectoryIndex;

namespace lld {
namespace pecoff {

// Page size of x86 processor. Some data needs to be aligned at page boundary
// when loaded into memory.
static const int PAGE_SIZE = 4096;

// Disk sector size. Some data needs to be aligned at disk sector boundary in
// file.
static const int SECTOR_SIZE = 512;

namespace {
class SectionChunk;

/// A Chunk is an abstrace contiguous range in an output file.
class Chunk {
public:
  enum Kind {
    kindHeader,
    kindSection,
    kindDataDirectory
  };

  explicit Chunk(Kind kind) : _kind(kind), _size(0) {}
  virtual ~Chunk() {};
  virtual void write(uint8_t *buffer) = 0;
  virtual uint64_t size() const { return _size; }
  virtual uint64_t align() const { return 1; }

  uint64_t fileOffset() const { return _fileOffset; }
  void setFileOffset(uint64_t fileOffset) { _fileOffset = fileOffset; }
  Kind getKind() const { return _kind; }

protected:
  Kind _kind;
  uint64_t _size;
  uint64_t _fileOffset;
};

/// A HeaderChunk is an abstract class to represent a file header for
/// PE/COFF. The data in the header chunk is metadata about program and will
/// be consumed by the windows loader. HeaderChunks are not mapped to memory
/// when executed.
class HeaderChunk : public Chunk {
public:
  HeaderChunk() : Chunk(kindHeader) {}

  static bool classof(const Chunk *c) { return c->getKind() == kindHeader; }
};

/// A DOSStubChunk represents the DOS compatible header at the beginning
/// of PE/COFF files.
class DOSStubChunk : public HeaderChunk {
public:
  explicit DOSStubChunk(const PECOFFLinkingContext &ctx)
      : HeaderChunk(), _context(ctx) {
    // Minimum size of DOS stub is 64 bytes. The next block (PE header) needs to
    // be aligned on 8 byte boundary.
    size_t size = std::max(_context.getDosStub().size(), (size_t)64);
    _size = llvm::RoundUpToAlignment(size, 8);
  }

  virtual void write(uint8_t *buffer) {
    ArrayRef<uint8_t> array = _context.getDosStub();
    std::memcpy(buffer, array.data(), array.size());
    auto *header = reinterpret_cast<llvm::object::dos_header *>(buffer);
    header->AddressOfNewExeHeader = _size;
  }

private:
  const PECOFFLinkingContext &_context;
};

/// A PEHeaderChunk represents PE header including COFF header.
class PEHeaderChunk : public HeaderChunk {
public:
  explicit PEHeaderChunk(const PECOFFLinkingContext &context);

  virtual void write(uint8_t *buffer);

  void setSizeOfHeaders(uint64_t size) {
    // Must be multiple of FileAlignment.
    _peHeader.SizeOfHeaders = llvm::RoundUpToAlignment(size, SECTOR_SIZE);
  }

  void setSizeOfCode(uint64_t size) { _peHeader.SizeOfCode = size; }
  void setBaseOfCode(uint32_t rva) { _peHeader.BaseOfCode = rva; }
  void setBaseOfData(uint32_t rva) { _peHeader.BaseOfData = rva; }
  void setSizeOfImage(uint32_t size) { _peHeader.SizeOfImage = size; }

  void setSizeOfInitializedData(uint64_t size) {
    _peHeader.SizeOfInitializedData = size;
  }

  void setSizeOfUninitializedData(uint64_t size) {
    _peHeader.SizeOfUninitializedData = size;
  }

  void setNumberOfSections(uint32_t num) {
    _coffHeader.NumberOfSections = num;
  }

  void setAddressOfEntryPoint(uint32_t address) {
    _peHeader.AddressOfEntryPoint = address;
  }

private:
  llvm::object::coff_file_header _coffHeader;
  llvm::object::pe32_header _peHeader;
};

/// A SectionHeaderTableChunk represents Section Table Header of PE/COFF
/// format, which is a list of section headers.
class SectionHeaderTableChunk : public HeaderChunk {
public:
  SectionHeaderTableChunk() : HeaderChunk() {}
  void addSection(SectionChunk *chunk);
  virtual uint64_t size() const;
  virtual void write(uint8_t *buffer);

private:
  static llvm::object::coff_section createSectionHeader(SectionChunk *chunk);

  std::vector<SectionChunk *> _sections;
};

/// An AtomChunk represents a section containing atoms.
class AtomChunk : public Chunk {
public:
  virtual void write(uint8_t *buffer);

  void buildAtomRvaMap(std::map<const Atom *, uint64_t> &atomRva) const;
  void applyRelocations(uint8_t *buffer,
                        std::map<const Atom *, uint64_t> &atomRva,
                        std::vector<uint64_t> &sectionRva,
                        uint64_t imageBaseAddress);
  void printAtomAddresses(uint64_t baseAddr) const;
  void addBaseRelocations(std::vector<uint64_t> &relocSites) const;

  uint64_t getVirtualAddress() {
    assert(_atomLayouts.size() > 0);
    return _atomLayouts[0]->_virtualAddr;
  }

  void setVirtualAddress(uint32_t rva) {
    for (AtomLayout *layout : _atomLayouts)
      layout->_virtualAddr += rva;
  }

  uint64_t getAtomVirtualAddress(StringRef name) {
    for (auto atomLayout : _atomLayouts)
      if (atomLayout->_atom->name() == name)
        return atomLayout->_virtualAddr;
    return 0;
  }

  static bool classof(const Chunk *c) {
    Kind kind = c->getKind();
    return kind == kindSection || kind == kindDataDirectory;
  }

protected:
  explicit AtomChunk(Kind kind) : Chunk(kind) {}
  std::vector<AtomLayout *> _atomLayouts;
};

/// A DataDirectoryChunk represents data directory entries that follows the PE
/// header in the output file. An entry consists of an 8 byte field that
/// indicates a relative virtual address (the starting address of the entry data
/// in memory) and 8 byte entry data size.
class DataDirectoryChunk : public HeaderChunk {
public:
  DataDirectoryChunk()
      : HeaderChunk(), _data(std::vector<llvm::object::data_directory>(16)) {}

  virtual uint64_t size() const {
    return sizeof(llvm::object::data_directory) * _data.size();
  }

  void setField(DataDirectoryIndex index, uint32_t addr, uint32_t size);
  virtual void write(uint8_t *buffer);

private:
  std::vector<llvm::object::data_directory> _data;
};

/// A SectionChunk represents a section containing atoms. It consists of a
/// section header that to be written to PECOFF header and atoms which to be
/// written to the raw data section.
class SectionChunk : public AtomChunk {
public:
  virtual uint64_t align() const { return SECTOR_SIZE; }

  virtual uint64_t rawSize() const { return _size; }

  void appendAtom(const DefinedAtom *atom);
  uint32_t getCharacteristics() const { return _characteristics; }
  StringRef getSectionName() const { return _sectionName; }

  static bool classof(const Chunk *c) { return c->getKind() == kindSection; }

protected:
  SectionChunk(StringRef sectionName, uint32_t characteristics)
    : AtomChunk(kindSection), _sectionName(sectionName),
      _characteristics(characteristics) {}

private:
  StringRef _sectionName;
  const uint32_t _characteristics;
  mutable llvm::BumpPtrAllocator _alloc;
};

// \brief A GenericSectionChunk represents various sections such as .text or
// .data.
class GenericSectionChunk : public SectionChunk {
public:
  virtual void write(uint8_t *buffer);

  GenericSectionChunk(const PECOFFLinkingContext &ctx, StringRef name,
                      const std::vector<const DefinedAtom *> &atoms)
      : SectionChunk(name, computeCharacteristics(ctx, name, atoms)) {
    for (auto *a : atoms)
      appendAtom(a);
  }

private:
  uint32_t
  computeCharacteristics(const PECOFFLinkingContext &ctx, StringRef name,
                         const std::vector<const DefinedAtom *> &atoms) const {
    return ctx.getSectionAttributes(name, getDefaultCharacteristics(name, atoms));
  }

  uint32_t getDefaultCharacteristics(
      StringRef name, const std::vector<const DefinedAtom *> &atoms) const;
};

/// A BaseRelocAtom represents a base relocation block in ".reloc" section.
class BaseRelocAtom : public coff::COFFLinkerInternalAtom {
public:
  BaseRelocAtom(const File &file, uint64_t ordinal, std::vector<uint8_t> data)
      : COFFLinkerInternalAtom(file, ordinal, std::move(data)) {}

  virtual ContentType contentType() const { return typeData; }
  virtual Alignment alignment() const { return Alignment(2); }
};

/// A BaseRelocChunk represents ".reloc" section.
///
/// .reloc section contains a list of addresses. If the PE/COFF loader decides
/// to load the binary at a memory address different from its preferred base
/// address, which is specified by ImageBase field in the COFF header, the
/// loader needs to relocate the binary, so that all the addresses in the binary
/// point to new locations. The loader will do that by fixing up the addresses
/// specified by .reloc section.
///
/// The executable is almost always loaded at the preferred base address because
/// it's loaded into an empty address space. The DLL is however an subject of
/// load-time relocation because it may conflict with other DLLs or the
/// executable.
class BaseRelocChunk : public SectionChunk {
  typedef std::vector<std::unique_ptr<Chunk>> ChunkVectorT;
  typedef std::map<uint64_t, std::vector<uint16_t>> PageOffsetT;

public:
  explicit BaseRelocChunk(const File &linkedFile)
      : SectionChunk(".reloc", characteristics), _file(linkedFile) {}

  void setContents(ChunkVectorT &chunks);

private:
  // When loaded into memory, reloc section should be readable and writable.
  static const uint32_t characteristics =
      llvm::COFF::IMAGE_SCN_MEM_READ |
      llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
      llvm::COFF::IMAGE_SCN_MEM_DISCARDABLE;

  // Returns a list of RVAs that needs to be relocated if the binary is loaded
  // at an address different from its preferred one.
  std::vector<uint64_t> listRelocSites(ChunkVectorT &chunks) const;

  // Divide the given RVAs into blocks.
  PageOffsetT groupByPage(const std::vector<uint64_t> &relocSites) const;

  // Create the content of a relocation block.
  DefinedAtom *createBaseRelocBlock(const File &file, uint64_t ordinal,
                                    uint64_t pageAddr,
                                    const std::vector<uint16_t> &offsets);

  mutable llvm::BumpPtrAllocator _alloc;
  const File &_file;
};

PEHeaderChunk::PEHeaderChunk(const PECOFFLinkingContext &context)
    : HeaderChunk() {
  // Set the size of the chunk and initialize the header with null bytes.
  _size = sizeof(llvm::COFF::PEMagic) + sizeof(_coffHeader) + sizeof(_peHeader);
  std::memset(&_coffHeader, 0, sizeof(_coffHeader));
  std::memset(&_peHeader, 0, sizeof(_peHeader));

  _coffHeader.Machine = context.getMachineType();
  _coffHeader.TimeDateStamp = time(nullptr);

  // The size of PE header including optional data directory is always 224.
  _coffHeader.SizeOfOptionalHeader = 224;

  // Attributes of the executable.
  uint16_t characteristics = llvm::COFF::IMAGE_FILE_32BIT_MACHINE |
                             llvm::COFF::IMAGE_FILE_EXECUTABLE_IMAGE;
  if (context.getLargeAddressAware())
    characteristics |= llvm::COFF::IMAGE_FILE_LARGE_ADDRESS_AWARE;
  if (context.getSwapRunFromCD())
    characteristics |= llvm::COFF::IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP;
  if (context.getSwapRunFromNet())
    characteristics |= llvm::COFF::IMAGE_FILE_NET_RUN_FROM_SWAP;
  if (!context.getBaseRelocationEnabled())
    characteristics |= llvm::COFF::IMAGE_FILE_RELOCS_STRIPPED;

  _coffHeader.Characteristics = characteristics;

  // 0x10b indicates a normal PE32 executable. For PE32+ it should be 0x20b.
  _peHeader.Magic = 0x10b;

  // The address of entry point relative to ImageBase. Windows executable
  // usually starts at address 0x401000.
  _peHeader.AddressOfEntryPoint = 0x1000;

  // The address of the executable when loaded into memory. The default for
  // DLLs is 0x10000000. The default for executables is 0x400000.
  _peHeader.ImageBase = context.getBaseAddress();

  // Sections should be page-aligned when loaded into memory, which is 4KB on
  // x86.
  _peHeader.SectionAlignment = context.getSectionDefaultAlignment();

  // Sections in an executable file on disk should be sector-aligned (512 byte).
  _peHeader.FileAlignment = SECTOR_SIZE;

  // The version number of the resultant executable/DLL. The number is purely
  // informative, and neither the linker nor the loader won't use it. User can
  // set the value using /version command line option. Default is 0.0.
  PECOFFLinkingContext::Version imageVersion = context.getImageVersion();
  _peHeader.MajorImageVersion = imageVersion.majorVersion;
  _peHeader.MinorImageVersion = imageVersion.minorVersion;

  // The required Windows version number. This is the internal version and
  // shouldn't be confused with product name. Windows 7 is version 6.1 and
  // Windows 8 is 6.2, for example.
  PECOFFLinkingContext::Version minOSVersion = context.getMinOSVersion();
  _peHeader.MajorOperatingSystemVersion = minOSVersion.majorVersion;
  _peHeader.MinorOperatingSystemVersion = minOSVersion.minorVersion;
  _peHeader.MajorSubsystemVersion = minOSVersion.majorVersion;
  _peHeader.MinorSubsystemVersion = minOSVersion.minorVersion;

  _peHeader.Subsystem = context.getSubsystem();

  // Despite its name, DLL characteristics field has meaning both for
  // executables and DLLs. We are not very sure if the following bits must
  // be set, but regular binaries seem to have these bits, so we follow
  // them.
  uint16_t dllCharacteristics = llvm::COFF::IMAGE_DLL_CHARACTERISTICS_NO_SEH;
  if (context.isTerminalServerAware())
    dllCharacteristics |=
        llvm::COFF::IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE;
  if (context.isNxCompat())
    dllCharacteristics |= llvm::COFF::IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
  if (context.getDynamicBaseEnabled())
    dllCharacteristics |= llvm::COFF::IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
  if (!context.getAllowBind())
    dllCharacteristics |= llvm::COFF::IMAGE_DLL_CHARACTERISTICS_NO_BIND;
  if (!context.getAllowIsolation())
    dllCharacteristics |= llvm::COFF::IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION;
  _peHeader.DLLCharacteristics = dllCharacteristics;

  _peHeader.SizeOfStackReserve = context.getStackReserve();
  _peHeader.SizeOfStackCommit = context.getStackCommit();
  _peHeader.SizeOfHeapReserve = context.getHeapReserve();
  _peHeader.SizeOfHeapCommit = context.getHeapCommit();

  // The number of data directory entries. We always have 16 entries.
  _peHeader.NumberOfRvaAndSize = 16;
}

void PEHeaderChunk::write(uint8_t *buffer) {
  std::memcpy(buffer, llvm::COFF::PEMagic, sizeof(llvm::COFF::PEMagic));
  buffer += sizeof(llvm::COFF::PEMagic);
  std::memcpy(buffer, &_coffHeader, sizeof(_coffHeader));
  buffer += sizeof(_coffHeader);
  std::memcpy(buffer, &_peHeader, sizeof(_peHeader));
}

void AtomChunk::write(uint8_t *buffer) {
  for (const auto *layout : _atomLayouts) {
    const DefinedAtom *atom = cast<DefinedAtom>(layout->_atom);
    ArrayRef<uint8_t> rawContent = atom->rawContent();
    std::memcpy(buffer + layout->_fileOffset, rawContent.data(),
                rawContent.size());
  }
}

// Add all atoms to the given map. This data will be used to do relocation.
void
AtomChunk::buildAtomRvaMap(std::map<const Atom *, uint64_t> &atomRva) const {
  for (const auto *layout : _atomLayouts)
    atomRva[layout->_atom] = layout->_virtualAddr;
}

void AtomChunk::applyRelocations(uint8_t *buffer,
                                 std::map<const Atom *, uint64_t> &atomRva,
                                 std::vector<uint64_t> &sectionRva,
                                 uint64_t imageBaseAddress) {
  buffer += _fileOffset;
  for (const auto *layout : _atomLayouts) {
    const DefinedAtom *atom = cast<DefinedAtom>(layout->_atom);
    for (const Reference *ref : *atom) {
      // Skip if this reference is not for relocation.
      if (ref->kind() < lld::Reference::kindTargetLow)
        continue;

      auto relocSite32 = reinterpret_cast<ulittle32_t *>(
          buffer + layout->_fileOffset + ref->offsetInAtom());
      auto relocSite16 = reinterpret_cast<ulittle16_t *>(relocSite32);
      uint64_t targetAddr = atomRva[ref->target()];
      // Also account for whatever offset is already stored at the relocation
      // site.
      targetAddr += *relocSite32;

      switch (ref->kind()) {
      case llvm::COFF::IMAGE_REL_I386_ABSOLUTE:
        // This relocation is no-op.
        break;
      case llvm::COFF::IMAGE_REL_I386_DIR32:
        // Set target's 32-bit VA.
        *relocSite32 = targetAddr + imageBaseAddress;
        break;
      case llvm::COFF::IMAGE_REL_I386_DIR32NB:
        // Set target's 32-bit RVA.
        *relocSite32 = targetAddr;
        break;
      case llvm::COFF::IMAGE_REL_I386_REL32: {
        // Set 32-bit relative address of the target. This relocation is
        // usually used for relative branch or call instruction.
        uint32_t disp = atomRva[atom] + ref->offsetInAtom() + 4;
        *relocSite32 = targetAddr - disp;
        break;
      }
      case llvm::COFF::IMAGE_REL_I386_SECTION: {
        // The 16-bit section index that contains the target symbol.
        uint16_t i = 1;
        for (uint64_t rva : sectionRva) {
          if (targetAddr < rva) {
            *relocSite16 = i;
            break;
          }
          ++i;
        }
        break;
      }
      case llvm::COFF::IMAGE_REL_I386_SECREL:
        // The 32-bit relative address from the beginning of the section that
        // contains the target symbol.
        for (int i = 0, e = sectionRva.size(); i < e; ++i) {
          if (i == e - 1 ||
              (sectionRva[i] <= targetAddr && targetAddr <= sectionRva[i + 1])) {
            *relocSite32 = targetAddr - sectionRva[i];
            break;
          }
        }
        break;
      default:
        llvm_unreachable("Unsupported relocation kind");
      }
    }
  }
}

/// Print atom VAs. Used only for debugging.
void AtomChunk::printAtomAddresses(uint64_t baseAddr) const {
  for (const auto *layout : _atomLayouts) {
    const DefinedAtom *atom = cast<DefinedAtom>(layout->_atom);
    uint64_t addr = layout->_virtualAddr;
    llvm::dbgs() << llvm::format("0x%08llx: ", addr + baseAddr)
                 << (atom->name().empty() ? "(anonymous)" : atom->name())
                 << "\n";
  }
}

/// List all virtual addresses (and not relative virtual addresses) that need
/// to be fixed up if image base is relocated. The only relocation type that
/// needs to be fixed is DIR32 on i386. REL32 is not (and should not be)
/// fixed up because it's PC-relative.
void AtomChunk::addBaseRelocations(std::vector<uint64_t> &relocSites) const {
  // TODO: llvm-objdump doesn't support parsing the base relocation table, so
  // we can't really test this at the moment. As a temporary solution, we
  // should output debug messages with atom names and addresses so that we
  // can inspect relocations, and fix the tests (base-reloc.test, maybe
  // others) to use those messages.
  for (const auto *layout : _atomLayouts) {
    const DefinedAtom *atom = cast<DefinedAtom>(layout->_atom);
    for (const Reference *ref : *atom)
      if (ref->kind() == llvm::COFF::IMAGE_REL_I386_DIR32)
        relocSites.push_back(layout->_virtualAddr + ref->offsetInAtom());
  }
}

void DataDirectoryChunk::setField(DataDirectoryIndex index, uint32_t addr,
                                  uint32_t size) {
  llvm::object::data_directory &dir = _data[index];
  dir.RelativeVirtualAddress = addr;
  dir.Size = size;
}

void DataDirectoryChunk::write(uint8_t *buffer) {
  std::memcpy(buffer, &_data[0], size());
}

void SectionChunk::appendAtom(const DefinedAtom *atom) {
  // Atom may have to be at a proper alignment boundary. If so, move the
  // pointer to make a room after the last atom before adding new one.
  _size = llvm::RoundUpToAlignment(_size, 1 << atom->alignment().powerOf2);

  // Create an AtomLayout and move the current pointer.
  auto *layout = new (_alloc) AtomLayout(atom, _size, _size);
  _atomLayouts.push_back(layout);
  _size += atom->size();
}

void GenericSectionChunk::write(uint8_t *buffer) {
  if (_atomLayouts.empty())
    return;
  if (getCharacteristics() & llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
    return;
  if (getCharacteristics() & llvm::COFF::IMAGE_SCN_CNT_CODE) {
    // Fill the section with INT 3 (0xCC) rather than NUL, so that the
    // disassembler will not interpret a garbage between atoms as the beginning
    // of multi-byte machine code. This does not change the behavior of
    // resulting binary but help debugging.
    uint8_t *start = buffer + _atomLayouts.front()->_fileOffset;
    uint8_t *end = buffer + _atomLayouts.back()->_fileOffset;
    memset(start, 0xCC, end - start);
  }
  SectionChunk::write(buffer);
}

uint32_t GenericSectionChunk::getDefaultCharacteristics(
    StringRef name, const std::vector<const DefinedAtom *> &atoms) const {
  const uint32_t code = llvm::COFF::IMAGE_SCN_CNT_CODE;
  const uint32_t execute = llvm::COFF::IMAGE_SCN_MEM_EXECUTE;
  const uint32_t read = llvm::COFF::IMAGE_SCN_MEM_READ;
  const uint32_t write = llvm::COFF::IMAGE_SCN_MEM_WRITE;
  const uint32_t data = llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
  const uint32_t bss = llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
  if (name == ".text")
    return code | execute | read;
  if (name == ".data")
    return data | read | write;
  if (name == ".rdata")
    return data | read;
  if (name == ".bss")
    return bss | read | write;
  assert(atoms.size() > 0);
  switch (atoms[0]->permissions()) {
    case DefinedAtom::permR__:
      return data | read;
    case DefinedAtom::permRW_:
      return data | read | write;
    case DefinedAtom::permR_X:
      return code | execute | read;
    case DefinedAtom::permRWX:
      return code | execute | read | write;
    default:
      llvm_unreachable("Unsupported permission");
  }
}

void SectionHeaderTableChunk::addSection(SectionChunk *chunk) {
  _sections.push_back(chunk);
}

uint64_t SectionHeaderTableChunk::size() const {
  return _sections.size() * sizeof(llvm::object::coff_section);
}

void SectionHeaderTableChunk::write(uint8_t *buffer) {
  uint64_t offset = 0;
  for (SectionChunk *chunk : _sections) {
    llvm::object::coff_section header = createSectionHeader(chunk);
    std::memcpy(buffer + offset, &header, sizeof(header));
    offset += sizeof(header);
  }
}

llvm::object::coff_section
SectionHeaderTableChunk::createSectionHeader(SectionChunk *chunk) {
  llvm::object::coff_section header;

  // Section name equal to or shorter than 8 byte fits in the section
  // header. Longer names should be stored to string table, which is not
  // implemented yet.
  StringRef sectionName = chunk->getSectionName();
  if (sizeof(header.Name) < sectionName.size())
    llvm_unreachable("Cannot handle section name longer than 8 byte");

  // Name field must be NUL-padded. If the name is exactly 8 byte long,
  // there's no terminating NUL.
  std::memset(header.Name, 0, sizeof(header.Name));
  std::strncpy(header.Name, sectionName.data(),
               std::min(sizeof(header.Name), sectionName.size()));

  uint32_t characteristics = chunk->getCharacteristics();
  header.VirtualAddress = chunk->getVirtualAddress();
  header.PointerToRelocations = 0;
  header.PointerToLinenumbers = 0;
  header.NumberOfRelocations = 0;
  header.NumberOfLinenumbers = 0;
  header.SizeOfRawData = chunk->size();
  header.Characteristics = characteristics;

  if (characteristics & llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) {
    header.VirtualSize = 0;
    header.PointerToRawData = 0;
  } else {
    header.VirtualSize = chunk->rawSize();
    header.PointerToRawData = chunk->fileOffset();
  }
  return header;
}

/// Creates .reloc section content from the other sections. The content of
/// .reloc is basically a list of relocation sites. The relocation sites are
/// divided into blocks. Each block represents the base relocation for a 4K
/// page.
///
/// By dividing 32 bit RVAs into blocks, COFF saves disk and memory space for
/// the base relocation. A block consists of a 32 bit page RVA and 16 bit
/// relocation entries which represent offsets in the page. That is a more
/// compact representation than a simple vector of 32 bit RVAs.
void BaseRelocChunk::setContents(ChunkVectorT &chunks) {
  std::vector<uint64_t> relocSites = listRelocSites(chunks);
  PageOffsetT blocks = groupByPage(relocSites);
  uint64_t ordinal = 0;
  for (auto &i : blocks) {
    uint64_t pageAddr = i.first;
    const std::vector<uint16_t> &offsetsInPage = i.second;
    appendAtom(createBaseRelocBlock(_file, ordinal++, pageAddr, offsetsInPage));
  }
}

// Returns a list of RVAs that needs to be relocated if the binary is loaded
// at an address different from its preferred one.
std::vector<uint64_t>
BaseRelocChunk::listRelocSites(ChunkVectorT &chunks) const {
  std::vector<uint64_t> ret;
  for (auto &cp : chunks)
    if (SectionChunk *chunk = dyn_cast<SectionChunk>(&*cp))
      chunk->addBaseRelocations(ret);
  return ret;
}

// Divide the given RVAs into blocks.
BaseRelocChunk::PageOffsetT
BaseRelocChunk::groupByPage(const std::vector<uint64_t> &relocSites) const {
  PageOffsetT blocks;
  uint64_t mask = static_cast<uint64_t>(PAGE_SIZE) - 1;
  for (uint64_t addr : relocSites)
    blocks[addr & ~mask].push_back(addr & mask);
  return blocks;
}

// Create the content of a relocation block.
DefinedAtom *
BaseRelocChunk::createBaseRelocBlock(const File &file, uint64_t ordinal,
                                     uint64_t pageAddr,
                                     const std::vector<uint16_t> &offsets) {
  // Relocation blocks should be padded with IMAGE_REL_I386_ABSOLUTE to be
  // aligned to a DWORD size boundary.
  uint32_t size = llvm::RoundUpToAlignment(
      sizeof(ulittle32_t) * 2 + sizeof(ulittle16_t) * offsets.size(),
      sizeof(ulittle32_t));
  std::vector<uint8_t> contents(size);
  uint8_t *ptr = &contents[0];

  // The first four bytes is the page RVA.
  *reinterpret_cast<ulittle32_t *>(ptr) = pageAddr;
  ptr += sizeof(ulittle32_t);

  // The second four bytes is the size of the block, including the the page
  // RVA and this size field.
  *reinterpret_cast<ulittle32_t *>(ptr) = size;
  ptr += sizeof(ulittle32_t);

  // The rest of the block consists of offsets in the page.
  for (uint16_t offset : offsets) {
    assert(offset < PAGE_SIZE);
    uint16_t val = (llvm::COFF::IMAGE_REL_BASED_HIGHLOW << 12) | offset;
    *reinterpret_cast<ulittle16_t *>(ptr) = val;
    ptr += sizeof(ulittle16_t);
  }
  return new (_alloc) BaseRelocAtom(file, ordinal, std::move(contents));
}

} // end anonymous namespace

class ExecutableWriter : public Writer {
public:
  explicit ExecutableWriter(const PECOFFLinkingContext &context)
      : _PECOFFLinkingContext(context), _numSections(0),
        _imageSizeInMemory(PAGE_SIZE), _imageSizeOnDisk(0) {}

  void build(const File &linkedFile);
  virtual error_code writeFile(const File &linkedFile, StringRef path);

private:
  void applyAllRelocations(uint8_t *bufferStart);
  void printAllAtomAddresses() const;
  void addChunk(Chunk *chunk);
  void addSectionChunk(SectionChunk *chunk, SectionHeaderTableChunk *table);
  void setImageSizeOnDisk();
  void setAddressOfEntryPoint(SectionChunk *text, PEHeaderChunk *peHeader);
  uint64_t
  calcSectionSize(llvm::COFF::SectionCharacteristics sectionType) const;

  uint64_t calcSizeOfInitializedData() const {
    return calcSectionSize(llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA);
  }

  uint64_t calcSizeOfUninitializedData() const {
    return calcSectionSize(llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA);
  }

  uint64_t calcSizeOfCode() const {
    return calcSectionSize(llvm::COFF::IMAGE_SCN_CNT_CODE);
  }

  std::vector<std::unique_ptr<Chunk>> _chunks;
  const PECOFFLinkingContext &_PECOFFLinkingContext;
  uint32_t _numSections;

  // The size of the image in memory. This is initialized with PAGE_SIZE, as the
  // first page starting at ImageBase is usually left unmapped. IIUC there's no
  // technical reason to do so, but we'll follow that convention so that we
  // don't produce odd-looking binary.
  uint32_t _imageSizeInMemory;

  // The size of the image on disk. This is basically the sum of all chunks in
  // the output file with paddings between them.
  uint32_t _imageSizeOnDisk;
};

StringRef customSectionName(const DefinedAtom *atom) {
  assert(atom->sectionChoice() == DefinedAtom::sectionCustomRequired);
  StringRef s = atom->customSectionName();
  size_t pos = s.find('$');
  return (pos == StringRef::npos) ? s : s.substr(0, pos);
}

StringRef chooseSectionByContent(const DefinedAtom *atom) {
  switch (atom->contentType()) {
  case DefinedAtom::typeCode:
    return ".text";
  case DefinedAtom::typeZeroFill:
    return ".bss";
  case DefinedAtom::typeData:
    if (atom->permissions() == DefinedAtom::permR__)
      return ".rdata";
    if (atom->permissions() == DefinedAtom::permRW_)
      return ".data";
    break;
  default:
    break;
  }
  llvm::errs() << "Atom: contentType=" << atom->contentType()
               << " permission=" << atom->permissions() << "\n";
  llvm_unreachable("Failed to choose section based on content");
}

typedef std::map<StringRef, std::vector<const DefinedAtom *> > AtomVectorMap;

void groupAtoms(const PECOFFLinkingContext &ctx, const File &file,
                AtomVectorMap &result) {
  for (const DefinedAtom *atom : file.defined()) {
    if (atom->sectionChoice() == DefinedAtom::sectionCustomRequired) {
      StringRef section = customSectionName(atom);
      result[ctx.getOutputSectionName(section)].push_back(atom);
      continue;
    }
    if (atom->sectionChoice() == DefinedAtom::sectionBasedOnContent) {
      StringRef section = chooseSectionByContent(atom);
      result[ctx.getOutputSectionName(section)].push_back(atom);
      continue;
    }
    llvm_unreachable("Unknown section choice");
  }
}

// Create all chunks that consist of the output file.
void ExecutableWriter::build(const File &linkedFile) {
  AtomVectorMap atoms;
  groupAtoms(_PECOFFLinkingContext, linkedFile, atoms);

  // Create file chunks and add them to the list.
  auto *dosStub = new DOSStubChunk(_PECOFFLinkingContext);
  auto *peHeader = new PEHeaderChunk(_PECOFFLinkingContext);
  auto *dataDirectory = new DataDirectoryChunk();
  auto *sectionTable = new SectionHeaderTableChunk();
  addChunk(dosStub);
  addChunk(peHeader);
  addChunk(dataDirectory);
  addChunk(sectionTable);

  for (auto i : atoms) {
    StringRef sectionName = i.first;
    std::vector<const DefinedAtom *> &contents = i.second;
    auto *section = new GenericSectionChunk(_PECOFFLinkingContext, sectionName,
                                            contents);
    addSectionChunk(section, sectionTable);
  }

  // Now that we know the addresses of all defined atoms that needs to be
  // relocated. So we can create the ".reloc" section which contains all the
  // relocation sites.
  if (_PECOFFLinkingContext.getBaseRelocationEnabled()) {
    BaseRelocChunk *baseReloc = new BaseRelocChunk(linkedFile);
    baseReloc->setContents(_chunks);
    if (baseReloc->size()) {
      addSectionChunk(baseReloc, sectionTable);
      dataDirectory->setField(DataDirectoryIndex::BASE_RELOCATION_TABLE,
                              baseReloc->getVirtualAddress(),
                              baseReloc->rawSize());
    }
  }

  setImageSizeOnDisk();

  for (std::unique_ptr<Chunk> &chunk : _chunks) {
    SectionChunk *section = dyn_cast<SectionChunk>(chunk.get());
    if (!section)
      continue;
    if (section->getSectionName() == ".text") {
      peHeader->setBaseOfCode(section->getVirtualAddress());
      setAddressOfEntryPoint(section, peHeader);
    }
    if (section->getSectionName() == ".data")
      peHeader->setBaseOfData(section->getVirtualAddress());
    if (section->getSectionName() == ".idata.a")
      dataDirectory->setField(DataDirectoryIndex::IAT,
                              section->getVirtualAddress(), section->rawSize());
    if (section->getSectionName() == ".idata.d")
      dataDirectory->setField(DataDirectoryIndex::IMPORT_TABLE,
                              section->getVirtualAddress(), section->rawSize());
  }

  // Now that we know the size and file offset of sections. Set the file
  // header accordingly.
  peHeader->setSizeOfCode(calcSizeOfCode());
  peHeader->setSizeOfInitializedData(calcSizeOfInitializedData());
  peHeader->setSizeOfUninitializedData(calcSizeOfUninitializedData());
  peHeader->setNumberOfSections(_numSections);
  peHeader->setSizeOfImage(_imageSizeInMemory);
  peHeader->setSizeOfHeaders(sectionTable->fileOffset() + sectionTable->size());
}

error_code ExecutableWriter::writeFile(const File &linkedFile, StringRef path) {
  this->build(linkedFile);

  uint64_t totalSize = _chunks.back()->fileOffset() + _chunks.back()->size();
  OwningPtr<llvm::FileOutputBuffer> buffer;
  error_code ec = llvm::FileOutputBuffer::create(
      path, totalSize, buffer, llvm::FileOutputBuffer::F_executable);
  if (ec)
    return ec;

  for (std::unique_ptr<Chunk> &chunk : _chunks)
    chunk->write(buffer->getBufferStart() + chunk->fileOffset());
  applyAllRelocations(buffer->getBufferStart());
  DEBUG(printAllAtomAddresses());
  return buffer->commit();
}

/// Apply relocations to the output file buffer. This two pass. In the first
/// pass, we visit all atoms to create a map from atom to its virtual
/// address. In the second pass, we visit all relocation references to fix
/// up addresses in the buffer.
void ExecutableWriter::applyAllRelocations(uint8_t *bufferStart) {
  std::map<const Atom *, uint64_t> atomRva;
  std::vector<uint64_t> sectionRva;

  // Create the list of section start addresses.
  for (auto &cp : _chunks)
    if (SectionChunk *section = dyn_cast<SectionChunk>(&*cp))
      sectionRva.push_back(section->getVirtualAddress());

  // Pass 1
  for (auto &cp : _chunks)
    if (AtomChunk *chunk = dyn_cast<AtomChunk>(&*cp))
      chunk->buildAtomRvaMap(atomRva);

  // Pass 2
  for (auto &cp : _chunks)
    if (AtomChunk *chunk = dyn_cast<AtomChunk>(&*cp))
      chunk->applyRelocations(bufferStart, atomRva, sectionRva,
                              _PECOFFLinkingContext.getBaseAddress());
}

/// Print atom VAs. Used only for debugging.
void ExecutableWriter::printAllAtomAddresses() const {
  for (auto &cp : _chunks)
    if (AtomChunk *chunk = dyn_cast<AtomChunk>(&*cp))
      chunk->printAtomAddresses(_PECOFFLinkingContext.getBaseAddress());
}

void ExecutableWriter::addChunk(Chunk *chunk) {
  _chunks.push_back(std::unique_ptr<Chunk>(chunk));
}

void ExecutableWriter::addSectionChunk(SectionChunk *chunk,
                                       SectionHeaderTableChunk *table) {
  _chunks.push_back(std::unique_ptr<Chunk>(chunk));
  table->addSection(chunk);
  _numSections++;

  // Compute and set the starting address of sections when loaded in
  // memory. They are different from positions on disk because sections need
  // to be sector-aligned on disk but page-aligned in memory.
  chunk->setVirtualAddress(_imageSizeInMemory);
  _imageSizeInMemory =
      llvm::RoundUpToAlignment(_imageSizeInMemory + chunk->size(), PAGE_SIZE);
}

void ExecutableWriter::setImageSizeOnDisk() {
  for (auto &chunk : _chunks) {
    // Compute and set the offset of the chunk in the output file.
    _imageSizeOnDisk =
        llvm::RoundUpToAlignment(_imageSizeOnDisk, chunk->align());
    chunk->setFileOffset(_imageSizeOnDisk);
    _imageSizeOnDisk += chunk->size();
  }
}

void ExecutableWriter::setAddressOfEntryPoint(SectionChunk *text,
                                              PEHeaderChunk *peHeader) {
  // Find the virtual address of the entry point symbol if any.
  // PECOFF spec says that entry point for dll images is optional, in which
  // case it must be set to 0.
  if (_PECOFFLinkingContext.entrySymbolName().empty() &&
      _PECOFFLinkingContext.getImageType() == PECOFFLinkingContext::IMAGE_DLL) {
    peHeader->setAddressOfEntryPoint(0);
  } else {
    uint64_t entryPointAddress =
        text->getAtomVirtualAddress(_PECOFFLinkingContext.entrySymbolName());
    if (entryPointAddress != 0)
      peHeader->setAddressOfEntryPoint(entryPointAddress);
  }
}

uint64_t ExecutableWriter::calcSectionSize(
    llvm::COFF::SectionCharacteristics sectionType) const {
  uint64_t ret = 0;
  for (auto &cp : _chunks)
    if (SectionChunk *chunk = dyn_cast<SectionChunk>(&*cp))
      if (chunk->getCharacteristics() & sectionType)
        ret += chunk->size();
  return ret;
}

} // end namespace pecoff

std::unique_ptr<Writer> createWriterPECOFF(const PECOFFLinkingContext &info) {
  return std::unique_ptr<Writer>(new pecoff::ExecutableWriter(info));
}

} // end namespace lld
OpenPOWER on IntegriCloud