xref: /freebsd/contrib/llvm-project/lld/COFF/Chunks.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===- Chunks.cpp ---------------------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "Chunks.h"
10349cc55cSDimitry Andric #include "COFFLinkerContext.h"
110b57cec5SDimitry Andric #include "InputFiles.h"
12349cc55cSDimitry Andric #include "SymbolTable.h"
130b57cec5SDimitry Andric #include "Symbols.h"
140b57cec5SDimitry Andric #include "Writer.h"
15fcaf7f86SDimitry Andric #include "llvm/ADT/STLExtras.h"
1606c3fb27SDimitry Andric #include "llvm/ADT/StringExtras.h"
17bdd1243dSDimitry Andric #include "llvm/ADT/Twine.h"
180b57cec5SDimitry Andric #include "llvm/BinaryFormat/COFF.h"
190b57cec5SDimitry Andric #include "llvm/Object/COFF.h"
200b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
210b57cec5SDimitry Andric #include "llvm/Support/Endian.h"
220b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
230b57cec5SDimitry Andric #include <algorithm>
24bdd1243dSDimitry Andric #include <iterator>
250b57cec5SDimitry Andric 
260b57cec5SDimitry Andric using namespace llvm;
270b57cec5SDimitry Andric using namespace llvm::object;
280b57cec5SDimitry Andric using namespace llvm::support::endian;
290b57cec5SDimitry Andric using namespace llvm::COFF;
300b57cec5SDimitry Andric using llvm::support::ulittle32_t;
310b57cec5SDimitry Andric 
32bdd1243dSDimitry Andric namespace lld::coff {
330b57cec5SDimitry Andric 
SectionChunk(ObjFile * f,const coff_section * h,Kind k)34*0fca6ea1SDimitry Andric SectionChunk::SectionChunk(ObjFile *f, const coff_section *h, Kind k)
35*0fca6ea1SDimitry Andric     : Chunk(k), file(f), header(h), repl(this) {
360b57cec5SDimitry Andric   // Initialize relocs.
37fe6060f1SDimitry Andric   if (file)
380b57cec5SDimitry Andric     setRelocs(file->getCOFFObj()->getRelocations(header));
390b57cec5SDimitry Andric 
400b57cec5SDimitry Andric   // Initialize sectionName.
410b57cec5SDimitry Andric   StringRef sectionName;
42fe6060f1SDimitry Andric   if (file) {
430b57cec5SDimitry Andric     if (Expected<StringRef> e = file->getCOFFObj()->getSectionName(header))
440b57cec5SDimitry Andric       sectionName = *e;
45fe6060f1SDimitry Andric   }
460b57cec5SDimitry Andric   sectionNameData = sectionName.data();
470b57cec5SDimitry Andric   sectionNameSize = sectionName.size();
480b57cec5SDimitry Andric 
490b57cec5SDimitry Andric   setAlignment(header->getAlignment());
500b57cec5SDimitry Andric 
510b57cec5SDimitry Andric   hasData = !(header->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA);
520b57cec5SDimitry Andric 
530b57cec5SDimitry Andric   // If linker GC is disabled, every chunk starts out alive.  If linker GC is
540b57cec5SDimitry Andric   // enabled, treat non-comdat sections as roots. Generally optimized object
550b57cec5SDimitry Andric   // files will be built with -ffunction-sections or /Gy, so most things worth
560b57cec5SDimitry Andric   // stripping will be in a comdat.
57bdd1243dSDimitry Andric   if (file)
58bdd1243dSDimitry Andric     live = !file->ctx.config.doGC || !isCOMDAT();
59fe6060f1SDimitry Andric   else
60fe6060f1SDimitry Andric     live = true;
610b57cec5SDimitry Andric }
620b57cec5SDimitry Andric 
630b57cec5SDimitry Andric // SectionChunk is one of the most frequently allocated classes, so it is
640b57cec5SDimitry Andric // important to keep it as compact as possible. As of this writing, the number
650b57cec5SDimitry Andric // below is the size of this class on x64 platforms.
660b57cec5SDimitry Andric static_assert(sizeof(SectionChunk) <= 88, "SectionChunk grew unexpectedly");
670b57cec5SDimitry Andric 
add16(uint8_t * p,int16_t v)680b57cec5SDimitry Andric static void add16(uint8_t *p, int16_t v) { write16le(p, read16le(p) + v); }
add32(uint8_t * p,int32_t v)690b57cec5SDimitry Andric static void add32(uint8_t *p, int32_t v) { write32le(p, read32le(p) + v); }
add64(uint8_t * p,int64_t v)700b57cec5SDimitry Andric static void add64(uint8_t *p, int64_t v) { write64le(p, read64le(p) + v); }
or16(uint8_t * p,uint16_t v)710b57cec5SDimitry Andric static void or16(uint8_t *p, uint16_t v) { write16le(p, read16le(p) | v); }
or32(uint8_t * p,uint32_t v)720b57cec5SDimitry Andric static void or32(uint8_t *p, uint32_t v) { write32le(p, read32le(p) | v); }
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric // Verify that given sections are appropriate targets for SECREL
750b57cec5SDimitry Andric // relocations. This check is relaxed because unfortunately debug
760b57cec5SDimitry Andric // sections have section-relative relocations against absolute symbols.
checkSecRel(const SectionChunk * sec,OutputSection * os)770b57cec5SDimitry Andric static bool checkSecRel(const SectionChunk *sec, OutputSection *os) {
780b57cec5SDimitry Andric   if (os)
790b57cec5SDimitry Andric     return true;
800b57cec5SDimitry Andric   if (sec->isCodeView())
810b57cec5SDimitry Andric     return false;
820b57cec5SDimitry Andric   error("SECREL relocation cannot be applied to absolute symbols");
830b57cec5SDimitry Andric   return false;
840b57cec5SDimitry Andric }
850b57cec5SDimitry Andric 
applySecRel(const SectionChunk * sec,uint8_t * off,OutputSection * os,uint64_t s)860b57cec5SDimitry Andric static void applySecRel(const SectionChunk *sec, uint8_t *off,
870b57cec5SDimitry Andric                         OutputSection *os, uint64_t s) {
880b57cec5SDimitry Andric   if (!checkSecRel(sec, os))
890b57cec5SDimitry Andric     return;
900b57cec5SDimitry Andric   uint64_t secRel = s - os->getRVA();
910b57cec5SDimitry Andric   if (secRel > UINT32_MAX) {
920b57cec5SDimitry Andric     error("overflow in SECREL relocation in section: " + sec->getSectionName());
930b57cec5SDimitry Andric     return;
940b57cec5SDimitry Andric   }
950b57cec5SDimitry Andric   add32(off, secRel);
960b57cec5SDimitry Andric }
970b57cec5SDimitry Andric 
applySecIdx(uint8_t * off,OutputSection * os,unsigned numOutputSections)98bdd1243dSDimitry Andric static void applySecIdx(uint8_t *off, OutputSection *os,
99bdd1243dSDimitry Andric                         unsigned numOutputSections) {
100bdd1243dSDimitry Andric   // numOutputSections is the largest valid section index. Make sure that
101bdd1243dSDimitry Andric   // it fits in 16 bits.
102bdd1243dSDimitry Andric   assert(numOutputSections <= 0xffff && "size of outputSections is too big");
103bdd1243dSDimitry Andric 
1040b57cec5SDimitry Andric   // Absolute symbol doesn't have section index, but section index relocation
1050b57cec5SDimitry Andric   // against absolute symbol should be resolved to one plus the last output
1060b57cec5SDimitry Andric   // section index. This is required for compatibility with MSVC.
1070b57cec5SDimitry Andric   if (os)
1080b57cec5SDimitry Andric     add16(off, os->sectionIndex);
1090b57cec5SDimitry Andric   else
110bdd1243dSDimitry Andric     add16(off, numOutputSections + 1);
1110b57cec5SDimitry Andric }
1120b57cec5SDimitry Andric 
applyRelX64(uint8_t * off,uint16_t type,OutputSection * os,uint64_t s,uint64_t p,uint64_t imageBase) const1130b57cec5SDimitry Andric void SectionChunk::applyRelX64(uint8_t *off, uint16_t type, OutputSection *os,
114bdd1243dSDimitry Andric                                uint64_t s, uint64_t p,
115bdd1243dSDimitry Andric                                uint64_t imageBase) const {
1160b57cec5SDimitry Andric   switch (type) {
117bdd1243dSDimitry Andric   case IMAGE_REL_AMD64_ADDR32:
118bdd1243dSDimitry Andric     add32(off, s + imageBase);
119bdd1243dSDimitry Andric     break;
120bdd1243dSDimitry Andric   case IMAGE_REL_AMD64_ADDR64:
121bdd1243dSDimitry Andric     add64(off, s + imageBase);
122bdd1243dSDimitry Andric     break;
1230b57cec5SDimitry Andric   case IMAGE_REL_AMD64_ADDR32NB: add32(off, s); break;
1240b57cec5SDimitry Andric   case IMAGE_REL_AMD64_REL32:    add32(off, s - p - 4); break;
1250b57cec5SDimitry Andric   case IMAGE_REL_AMD64_REL32_1:  add32(off, s - p - 5); break;
1260b57cec5SDimitry Andric   case IMAGE_REL_AMD64_REL32_2:  add32(off, s - p - 6); break;
1270b57cec5SDimitry Andric   case IMAGE_REL_AMD64_REL32_3:  add32(off, s - p - 7); break;
1280b57cec5SDimitry Andric   case IMAGE_REL_AMD64_REL32_4:  add32(off, s - p - 8); break;
1290b57cec5SDimitry Andric   case IMAGE_REL_AMD64_REL32_5:  add32(off, s - p - 9); break;
130bdd1243dSDimitry Andric   case IMAGE_REL_AMD64_SECTION:
131bdd1243dSDimitry Andric     applySecIdx(off, os, file->ctx.outputSections.size());
132bdd1243dSDimitry Andric     break;
1330b57cec5SDimitry Andric   case IMAGE_REL_AMD64_SECREL:   applySecRel(this, off, os, s); break;
1340b57cec5SDimitry Andric   default:
1350b57cec5SDimitry Andric     error("unsupported relocation type 0x" + Twine::utohexstr(type) + " in " +
1360b57cec5SDimitry Andric           toString(file));
1370b57cec5SDimitry Andric   }
1380b57cec5SDimitry Andric }
1390b57cec5SDimitry Andric 
applyRelX86(uint8_t * off,uint16_t type,OutputSection * os,uint64_t s,uint64_t p,uint64_t imageBase) const1400b57cec5SDimitry Andric void SectionChunk::applyRelX86(uint8_t *off, uint16_t type, OutputSection *os,
141bdd1243dSDimitry Andric                                uint64_t s, uint64_t p,
142bdd1243dSDimitry Andric                                uint64_t imageBase) const {
1430b57cec5SDimitry Andric   switch (type) {
1440b57cec5SDimitry Andric   case IMAGE_REL_I386_ABSOLUTE: break;
145bdd1243dSDimitry Andric   case IMAGE_REL_I386_DIR32:
146bdd1243dSDimitry Andric     add32(off, s + imageBase);
147bdd1243dSDimitry Andric     break;
1480b57cec5SDimitry Andric   case IMAGE_REL_I386_DIR32NB:  add32(off, s); break;
1490b57cec5SDimitry Andric   case IMAGE_REL_I386_REL32:    add32(off, s - p - 4); break;
150bdd1243dSDimitry Andric   case IMAGE_REL_I386_SECTION:
151bdd1243dSDimitry Andric     applySecIdx(off, os, file->ctx.outputSections.size());
152bdd1243dSDimitry Andric     break;
1530b57cec5SDimitry Andric   case IMAGE_REL_I386_SECREL:   applySecRel(this, off, os, s); break;
1540b57cec5SDimitry Andric   default:
1550b57cec5SDimitry Andric     error("unsupported relocation type 0x" + Twine::utohexstr(type) + " in " +
1560b57cec5SDimitry Andric           toString(file));
1570b57cec5SDimitry Andric   }
1580b57cec5SDimitry Andric }
1590b57cec5SDimitry Andric 
applyMOV(uint8_t * off,uint16_t v)1600b57cec5SDimitry Andric static void applyMOV(uint8_t *off, uint16_t v) {
1610b57cec5SDimitry Andric   write16le(off, (read16le(off) & 0xfbf0) | ((v & 0x800) >> 1) | ((v >> 12) & 0xf));
1620b57cec5SDimitry Andric   write16le(off + 2, (read16le(off + 2) & 0x8f00) | ((v & 0x700) << 4) | (v & 0xff));
1630b57cec5SDimitry Andric }
1640b57cec5SDimitry Andric 
readMOV(uint8_t * off,bool movt)1650b57cec5SDimitry Andric static uint16_t readMOV(uint8_t *off, bool movt) {
1660b57cec5SDimitry Andric   uint16_t op1 = read16le(off);
1670b57cec5SDimitry Andric   if ((op1 & 0xfbf0) != (movt ? 0xf2c0 : 0xf240))
1680b57cec5SDimitry Andric     error("unexpected instruction in " + Twine(movt ? "MOVT" : "MOVW") +
1690b57cec5SDimitry Andric           " instruction in MOV32T relocation");
1700b57cec5SDimitry Andric   uint16_t op2 = read16le(off + 2);
1710b57cec5SDimitry Andric   if ((op2 & 0x8000) != 0)
1720b57cec5SDimitry Andric     error("unexpected instruction in " + Twine(movt ? "MOVT" : "MOVW") +
1730b57cec5SDimitry Andric           " instruction in MOV32T relocation");
1740b57cec5SDimitry Andric   return (op2 & 0x00ff) | ((op2 >> 4) & 0x0700) | ((op1 << 1) & 0x0800) |
1750b57cec5SDimitry Andric          ((op1 & 0x000f) << 12);
1760b57cec5SDimitry Andric }
1770b57cec5SDimitry Andric 
applyMOV32T(uint8_t * off,uint32_t v)1780b57cec5SDimitry Andric void applyMOV32T(uint8_t *off, uint32_t v) {
1790b57cec5SDimitry Andric   uint16_t immW = readMOV(off, false);    // read MOVW operand
1800b57cec5SDimitry Andric   uint16_t immT = readMOV(off + 4, true); // read MOVT operand
1810b57cec5SDimitry Andric   uint32_t imm = immW | (immT << 16);
1820b57cec5SDimitry Andric   v += imm;                         // add the immediate offset
1830b57cec5SDimitry Andric   applyMOV(off, v);           // set MOVW operand
1840b57cec5SDimitry Andric   applyMOV(off + 4, v >> 16); // set MOVT operand
1850b57cec5SDimitry Andric }
1860b57cec5SDimitry Andric 
applyBranch20T(uint8_t * off,int32_t v)1870b57cec5SDimitry Andric static void applyBranch20T(uint8_t *off, int32_t v) {
1880b57cec5SDimitry Andric   if (!isInt<21>(v))
1890b57cec5SDimitry Andric     error("relocation out of range");
1900b57cec5SDimitry Andric   uint32_t s = v < 0 ? 1 : 0;
1910b57cec5SDimitry Andric   uint32_t j1 = (v >> 19) & 1;
1920b57cec5SDimitry Andric   uint32_t j2 = (v >> 18) & 1;
1930b57cec5SDimitry Andric   or16(off, (s << 10) | ((v >> 12) & 0x3f));
1940b57cec5SDimitry Andric   or16(off + 2, (j1 << 13) | (j2 << 11) | ((v >> 1) & 0x7ff));
1950b57cec5SDimitry Andric }
1960b57cec5SDimitry Andric 
applyBranch24T(uint8_t * off,int32_t v)1970b57cec5SDimitry Andric void applyBranch24T(uint8_t *off, int32_t v) {
1980b57cec5SDimitry Andric   if (!isInt<25>(v))
1990b57cec5SDimitry Andric     error("relocation out of range");
2000b57cec5SDimitry Andric   uint32_t s = v < 0 ? 1 : 0;
2010b57cec5SDimitry Andric   uint32_t j1 = ((~v >> 23) & 1) ^ s;
2020b57cec5SDimitry Andric   uint32_t j2 = ((~v >> 22) & 1) ^ s;
2030b57cec5SDimitry Andric   or16(off, (s << 10) | ((v >> 12) & 0x3ff));
2040b57cec5SDimitry Andric   // Clear out the J1 and J2 bits which may be set.
2050b57cec5SDimitry Andric   write16le(off + 2, (read16le(off + 2) & 0xd000) | (j1 << 13) | (j2 << 11) | ((v >> 1) & 0x7ff));
2060b57cec5SDimitry Andric }
2070b57cec5SDimitry Andric 
applyRelARM(uint8_t * off,uint16_t type,OutputSection * os,uint64_t s,uint64_t p,uint64_t imageBase) const2080b57cec5SDimitry Andric void SectionChunk::applyRelARM(uint8_t *off, uint16_t type, OutputSection *os,
209bdd1243dSDimitry Andric                                uint64_t s, uint64_t p,
210bdd1243dSDimitry Andric                                uint64_t imageBase) const {
2110b57cec5SDimitry Andric   // Pointer to thumb code must have the LSB set.
2120b57cec5SDimitry Andric   uint64_t sx = s;
2130b57cec5SDimitry Andric   if (os && (os->header.Characteristics & IMAGE_SCN_MEM_EXECUTE))
2140b57cec5SDimitry Andric     sx |= 1;
2150b57cec5SDimitry Andric   switch (type) {
216bdd1243dSDimitry Andric   case IMAGE_REL_ARM_ADDR32:
217bdd1243dSDimitry Andric     add32(off, sx + imageBase);
218bdd1243dSDimitry Andric     break;
2190b57cec5SDimitry Andric   case IMAGE_REL_ARM_ADDR32NB:  add32(off, sx); break;
220bdd1243dSDimitry Andric   case IMAGE_REL_ARM_MOV32T:
221bdd1243dSDimitry Andric     applyMOV32T(off, sx + imageBase);
222bdd1243dSDimitry Andric     break;
2230b57cec5SDimitry Andric   case IMAGE_REL_ARM_BRANCH20T: applyBranch20T(off, sx - p - 4); break;
2240b57cec5SDimitry Andric   case IMAGE_REL_ARM_BRANCH24T: applyBranch24T(off, sx - p - 4); break;
2250b57cec5SDimitry Andric   case IMAGE_REL_ARM_BLX23T:    applyBranch24T(off, sx - p - 4); break;
226bdd1243dSDimitry Andric   case IMAGE_REL_ARM_SECTION:
227bdd1243dSDimitry Andric     applySecIdx(off, os, file->ctx.outputSections.size());
228bdd1243dSDimitry Andric     break;
2290b57cec5SDimitry Andric   case IMAGE_REL_ARM_SECREL:    applySecRel(this, off, os, s); break;
2300b57cec5SDimitry Andric   case IMAGE_REL_ARM_REL32:     add32(off, sx - p - 4); break;
2310b57cec5SDimitry Andric   default:
2320b57cec5SDimitry Andric     error("unsupported relocation type 0x" + Twine::utohexstr(type) + " in " +
2330b57cec5SDimitry Andric           toString(file));
2340b57cec5SDimitry Andric   }
2350b57cec5SDimitry Andric }
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric // Interpret the existing immediate value as a byte offset to the
2380b57cec5SDimitry Andric // target symbol, then update the instruction with the immediate as
2390b57cec5SDimitry Andric // the page offset from the current instruction to the target.
applyArm64Addr(uint8_t * off,uint64_t s,uint64_t p,int shift)2400b57cec5SDimitry Andric void applyArm64Addr(uint8_t *off, uint64_t s, uint64_t p, int shift) {
2410b57cec5SDimitry Andric   uint32_t orig = read32le(off);
2424824e7fdSDimitry Andric   int64_t imm =
2434824e7fdSDimitry Andric       SignExtend64<21>(((orig >> 29) & 0x3) | ((orig >> 3) & 0x1FFFFC));
2440b57cec5SDimitry Andric   s += imm;
2450b57cec5SDimitry Andric   imm = (s >> shift) - (p >> shift);
2460b57cec5SDimitry Andric   uint32_t immLo = (imm & 0x3) << 29;
2470b57cec5SDimitry Andric   uint32_t immHi = (imm & 0x1FFFFC) << 3;
2480b57cec5SDimitry Andric   uint64_t mask = (0x3 << 29) | (0x1FFFFC << 3);
2490b57cec5SDimitry Andric   write32le(off, (orig & ~mask) | immLo | immHi);
2500b57cec5SDimitry Andric }
2510b57cec5SDimitry Andric 
2520b57cec5SDimitry Andric // Update the immediate field in a AARCH64 ldr, str, and add instruction.
2530b57cec5SDimitry Andric // Optionally limit the range of the written immediate by one or more bits
2540b57cec5SDimitry Andric // (rangeLimit).
applyArm64Imm(uint8_t * off,uint64_t imm,uint32_t rangeLimit)2550b57cec5SDimitry Andric void applyArm64Imm(uint8_t *off, uint64_t imm, uint32_t rangeLimit) {
2560b57cec5SDimitry Andric   uint32_t orig = read32le(off);
2570b57cec5SDimitry Andric   imm += (orig >> 10) & 0xFFF;
2580b57cec5SDimitry Andric   orig &= ~(0xFFF << 10);
2590b57cec5SDimitry Andric   write32le(off, orig | ((imm & (0xFFF >> rangeLimit)) << 10));
2600b57cec5SDimitry Andric }
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric // Add the 12 bit page offset to the existing immediate.
2630b57cec5SDimitry Andric // Ldr/str instructions store the opcode immediate scaled
2640b57cec5SDimitry Andric // by the load/store size (giving a larger range for larger
2650b57cec5SDimitry Andric // loads/stores). The immediate is always (both before and after
2660b57cec5SDimitry Andric // fixing up the relocation) stored scaled similarly.
2670b57cec5SDimitry Andric // Even if larger loads/stores have a larger range, limit the
2680b57cec5SDimitry Andric // effective offset to 12 bit, since it is intended to be a
2690b57cec5SDimitry Andric // page offset.
applyArm64Ldr(uint8_t * off,uint64_t imm)2700b57cec5SDimitry Andric static void applyArm64Ldr(uint8_t *off, uint64_t imm) {
2710b57cec5SDimitry Andric   uint32_t orig = read32le(off);
2720b57cec5SDimitry Andric   uint32_t size = orig >> 30;
2730b57cec5SDimitry Andric   // 0x04000000 indicates SIMD/FP registers
2740b57cec5SDimitry Andric   // 0x00800000 indicates 128 bit
2750b57cec5SDimitry Andric   if ((orig & 0x4800000) == 0x4800000)
2760b57cec5SDimitry Andric     size += 4;
2770b57cec5SDimitry Andric   if ((imm & ((1 << size) - 1)) != 0)
2780b57cec5SDimitry Andric     error("misaligned ldr/str offset");
2790b57cec5SDimitry Andric   applyArm64Imm(off, imm >> size, size);
2800b57cec5SDimitry Andric }
2810b57cec5SDimitry Andric 
applySecRelLow12A(const SectionChunk * sec,uint8_t * off,OutputSection * os,uint64_t s)2820b57cec5SDimitry Andric static void applySecRelLow12A(const SectionChunk *sec, uint8_t *off,
2830b57cec5SDimitry Andric                               OutputSection *os, uint64_t s) {
2840b57cec5SDimitry Andric   if (checkSecRel(sec, os))
2850b57cec5SDimitry Andric     applyArm64Imm(off, (s - os->getRVA()) & 0xfff, 0);
2860b57cec5SDimitry Andric }
2870b57cec5SDimitry Andric 
applySecRelHigh12A(const SectionChunk * sec,uint8_t * off,OutputSection * os,uint64_t s)2880b57cec5SDimitry Andric static void applySecRelHigh12A(const SectionChunk *sec, uint8_t *off,
2890b57cec5SDimitry Andric                                OutputSection *os, uint64_t s) {
2900b57cec5SDimitry Andric   if (!checkSecRel(sec, os))
2910b57cec5SDimitry Andric     return;
2920b57cec5SDimitry Andric   uint64_t secRel = (s - os->getRVA()) >> 12;
2930b57cec5SDimitry Andric   if (0xfff < secRel) {
2940b57cec5SDimitry Andric     error("overflow in SECREL_HIGH12A relocation in section: " +
2950b57cec5SDimitry Andric           sec->getSectionName());
2960b57cec5SDimitry Andric     return;
2970b57cec5SDimitry Andric   }
2980b57cec5SDimitry Andric   applyArm64Imm(off, secRel & 0xfff, 0);
2990b57cec5SDimitry Andric }
3000b57cec5SDimitry Andric 
applySecRelLdr(const SectionChunk * sec,uint8_t * off,OutputSection * os,uint64_t s)3010b57cec5SDimitry Andric static void applySecRelLdr(const SectionChunk *sec, uint8_t *off,
3020b57cec5SDimitry Andric                            OutputSection *os, uint64_t s) {
3030b57cec5SDimitry Andric   if (checkSecRel(sec, os))
3040b57cec5SDimitry Andric     applyArm64Ldr(off, (s - os->getRVA()) & 0xfff);
3050b57cec5SDimitry Andric }
3060b57cec5SDimitry Andric 
applyArm64Branch26(uint8_t * off,int64_t v)3070b57cec5SDimitry Andric void applyArm64Branch26(uint8_t *off, int64_t v) {
3080b57cec5SDimitry Andric   if (!isInt<28>(v))
3090b57cec5SDimitry Andric     error("relocation out of range");
3100b57cec5SDimitry Andric   or32(off, (v & 0x0FFFFFFC) >> 2);
3110b57cec5SDimitry Andric }
3120b57cec5SDimitry Andric 
applyArm64Branch19(uint8_t * off,int64_t v)3130b57cec5SDimitry Andric static void applyArm64Branch19(uint8_t *off, int64_t v) {
3140b57cec5SDimitry Andric   if (!isInt<21>(v))
3150b57cec5SDimitry Andric     error("relocation out of range");
3160b57cec5SDimitry Andric   or32(off, (v & 0x001FFFFC) << 3);
3170b57cec5SDimitry Andric }
3180b57cec5SDimitry Andric 
applyArm64Branch14(uint8_t * off,int64_t v)3190b57cec5SDimitry Andric static void applyArm64Branch14(uint8_t *off, int64_t v) {
3200b57cec5SDimitry Andric   if (!isInt<16>(v))
3210b57cec5SDimitry Andric     error("relocation out of range");
3220b57cec5SDimitry Andric   or32(off, (v & 0x0000FFFC) << 3);
3230b57cec5SDimitry Andric }
3240b57cec5SDimitry Andric 
applyRelARM64(uint8_t * off,uint16_t type,OutputSection * os,uint64_t s,uint64_t p,uint64_t imageBase) const3250b57cec5SDimitry Andric void SectionChunk::applyRelARM64(uint8_t *off, uint16_t type, OutputSection *os,
326bdd1243dSDimitry Andric                                  uint64_t s, uint64_t p,
327bdd1243dSDimitry Andric                                  uint64_t imageBase) const {
3280b57cec5SDimitry Andric   switch (type) {
3290b57cec5SDimitry Andric   case IMAGE_REL_ARM64_PAGEBASE_REL21: applyArm64Addr(off, s, p, 12); break;
3300b57cec5SDimitry Andric   case IMAGE_REL_ARM64_REL21:          applyArm64Addr(off, s, p, 0); break;
3310b57cec5SDimitry Andric   case IMAGE_REL_ARM64_PAGEOFFSET_12A: applyArm64Imm(off, s & 0xfff, 0); break;
3320b57cec5SDimitry Andric   case IMAGE_REL_ARM64_PAGEOFFSET_12L: applyArm64Ldr(off, s & 0xfff); break;
3330b57cec5SDimitry Andric   case IMAGE_REL_ARM64_BRANCH26:       applyArm64Branch26(off, s - p); break;
3340b57cec5SDimitry Andric   case IMAGE_REL_ARM64_BRANCH19:       applyArm64Branch19(off, s - p); break;
3350b57cec5SDimitry Andric   case IMAGE_REL_ARM64_BRANCH14:       applyArm64Branch14(off, s - p); break;
336bdd1243dSDimitry Andric   case IMAGE_REL_ARM64_ADDR32:
337bdd1243dSDimitry Andric     add32(off, s + imageBase);
338bdd1243dSDimitry Andric     break;
3390b57cec5SDimitry Andric   case IMAGE_REL_ARM64_ADDR32NB:       add32(off, s); break;
340bdd1243dSDimitry Andric   case IMAGE_REL_ARM64_ADDR64:
341bdd1243dSDimitry Andric     add64(off, s + imageBase);
342bdd1243dSDimitry Andric     break;
3430b57cec5SDimitry Andric   case IMAGE_REL_ARM64_SECREL:         applySecRel(this, off, os, s); break;
3440b57cec5SDimitry Andric   case IMAGE_REL_ARM64_SECREL_LOW12A:  applySecRelLow12A(this, off, os, s); break;
3450b57cec5SDimitry Andric   case IMAGE_REL_ARM64_SECREL_HIGH12A: applySecRelHigh12A(this, off, os, s); break;
3460b57cec5SDimitry Andric   case IMAGE_REL_ARM64_SECREL_LOW12L:  applySecRelLdr(this, off, os, s); break;
347bdd1243dSDimitry Andric   case IMAGE_REL_ARM64_SECTION:
348bdd1243dSDimitry Andric     applySecIdx(off, os, file->ctx.outputSections.size());
349bdd1243dSDimitry Andric     break;
3500b57cec5SDimitry Andric   case IMAGE_REL_ARM64_REL32:          add32(off, s - p - 4); break;
3510b57cec5SDimitry Andric   default:
3520b57cec5SDimitry Andric     error("unsupported relocation type 0x" + Twine::utohexstr(type) + " in " +
3530b57cec5SDimitry Andric           toString(file));
3540b57cec5SDimitry Andric   }
3550b57cec5SDimitry Andric }
3560b57cec5SDimitry Andric 
maybeReportRelocationToDiscarded(const SectionChunk * fromChunk,Defined * sym,const coff_relocation & rel,bool isMinGW)3570b57cec5SDimitry Andric static void maybeReportRelocationToDiscarded(const SectionChunk *fromChunk,
3580b57cec5SDimitry Andric                                              Defined *sym,
359bdd1243dSDimitry Andric                                              const coff_relocation &rel,
360bdd1243dSDimitry Andric                                              bool isMinGW) {
3610b57cec5SDimitry Andric   // Don't report these errors when the relocation comes from a debug info
3620b57cec5SDimitry Andric   // section or in mingw mode. MinGW mode object files (built by GCC) can
3630b57cec5SDimitry Andric   // have leftover sections with relocations against discarded comdat
3640b57cec5SDimitry Andric   // sections. Such sections are left as is, with relocations untouched.
365bdd1243dSDimitry Andric   if (fromChunk->isCodeView() || fromChunk->isDWARF() || isMinGW)
3660b57cec5SDimitry Andric     return;
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric   // Get the name of the symbol. If it's null, it was discarded early, so we
3690b57cec5SDimitry Andric   // have to go back to the object file.
3700b57cec5SDimitry Andric   ObjFile *file = fromChunk->file;
3710b57cec5SDimitry Andric   StringRef name;
3720b57cec5SDimitry Andric   if (sym) {
3730b57cec5SDimitry Andric     name = sym->getName();
3740b57cec5SDimitry Andric   } else {
3750b57cec5SDimitry Andric     COFFSymbolRef coffSym =
3760b57cec5SDimitry Andric         check(file->getCOFFObj()->getSymbol(rel.SymbolTableIndex));
3775ffd83dbSDimitry Andric     name = check(file->getCOFFObj()->getSymbolName(coffSym));
3780b57cec5SDimitry Andric   }
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric   std::vector<std::string> symbolLocations =
3810b57cec5SDimitry Andric       getSymbolLocations(file, rel.SymbolTableIndex);
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric   std::string out;
3840b57cec5SDimitry Andric   llvm::raw_string_ostream os(out);
3850b57cec5SDimitry Andric   os << "relocation against symbol in discarded section: " + name;
3860b57cec5SDimitry Andric   for (const std::string &s : symbolLocations)
3870b57cec5SDimitry Andric     os << s;
3880b57cec5SDimitry Andric   error(os.str());
3890b57cec5SDimitry Andric }
3900b57cec5SDimitry Andric 
writeTo(uint8_t * buf) const3910b57cec5SDimitry Andric void SectionChunk::writeTo(uint8_t *buf) const {
3920b57cec5SDimitry Andric   if (!hasData)
3930b57cec5SDimitry Andric     return;
3940b57cec5SDimitry Andric   // Copy section contents from source object file to output file.
3950b57cec5SDimitry Andric   ArrayRef<uint8_t> a = getContents();
3960b57cec5SDimitry Andric   if (!a.empty())
3970b57cec5SDimitry Andric     memcpy(buf, a.data(), a.size());
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric   // Apply relocations.
4000b57cec5SDimitry Andric   size_t inputSize = getSize();
401e8d8bef9SDimitry Andric   for (const coff_relocation &rel : getRelocs()) {
4020b57cec5SDimitry Andric     // Check for an invalid relocation offset. This check isn't perfect, because
4030b57cec5SDimitry Andric     // we don't have the relocation size, which is only known after checking the
4040b57cec5SDimitry Andric     // machine and relocation type. As a result, a relocation may overwrite the
4050b57cec5SDimitry Andric     // beginning of the following input section.
4060b57cec5SDimitry Andric     if (rel.VirtualAddress >= inputSize) {
4070b57cec5SDimitry Andric       error("relocation points beyond the end of its parent section");
4080b57cec5SDimitry Andric       continue;
4090b57cec5SDimitry Andric     }
4100b57cec5SDimitry Andric 
411e8d8bef9SDimitry Andric     applyRelocation(buf + rel.VirtualAddress, rel);
412e8d8bef9SDimitry Andric   }
413*0fca6ea1SDimitry Andric 
414*0fca6ea1SDimitry Andric   // Write the offset to EC entry thunk preceding section contents. The low bit
415*0fca6ea1SDimitry Andric   // is always set, so it's effectively an offset from the last byte of the
416*0fca6ea1SDimitry Andric   // offset.
417*0fca6ea1SDimitry Andric   if (Defined *entryThunk = getEntryThunk())
418*0fca6ea1SDimitry Andric     write32le(buf - sizeof(uint32_t), entryThunk->getRVA() - rva + 1);
419e8d8bef9SDimitry Andric }
4200b57cec5SDimitry Andric 
applyRelocation(uint8_t * off,const coff_relocation & rel) const421e8d8bef9SDimitry Andric void SectionChunk::applyRelocation(uint8_t *off,
422e8d8bef9SDimitry Andric                                    const coff_relocation &rel) const {
423e8d8bef9SDimitry Andric   auto *sym = dyn_cast_or_null<Defined>(file->getSymbol(rel.SymbolTableIndex));
4240b57cec5SDimitry Andric 
4250b57cec5SDimitry Andric   // Get the output section of the symbol for this relocation.  The output
4260b57cec5SDimitry Andric   // section is needed to compute SECREL and SECTION relocations used in debug
4270b57cec5SDimitry Andric   // info.
4280b57cec5SDimitry Andric   Chunk *c = sym ? sym->getChunk() : nullptr;
429349cc55cSDimitry Andric   OutputSection *os = c ? file->ctx.getOutputSection(c) : nullptr;
4300b57cec5SDimitry Andric 
4310b57cec5SDimitry Andric   // Skip the relocation if it refers to a discarded section, and diagnose it
4320b57cec5SDimitry Andric   // as an error if appropriate. If a symbol was discarded early, it may be
4330b57cec5SDimitry Andric   // null. If it was discarded late, the output section will be null, unless
4340b57cec5SDimitry Andric   // it was an absolute or synthetic symbol.
4350b57cec5SDimitry Andric   if (!sym ||
4360b57cec5SDimitry Andric       (!os && !isa<DefinedAbsolute>(sym) && !isa<DefinedSynthetic>(sym))) {
437bdd1243dSDimitry Andric     maybeReportRelocationToDiscarded(this, sym, rel, file->ctx.config.mingw);
438e8d8bef9SDimitry Andric     return;
4390b57cec5SDimitry Andric   }
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric   uint64_t s = sym->getRVA();
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric   // Compute the RVA of the relocation for relative relocations.
4440b57cec5SDimitry Andric   uint64_t p = rva + rel.VirtualAddress;
445bdd1243dSDimitry Andric   uint64_t imageBase = file->ctx.config.imageBase;
446*0fca6ea1SDimitry Andric   switch (getArch()) {
447*0fca6ea1SDimitry Andric   case Triple::x86_64:
448bdd1243dSDimitry Andric     applyRelX64(off, rel.Type, os, s, p, imageBase);
4490b57cec5SDimitry Andric     break;
450*0fca6ea1SDimitry Andric   case Triple::x86:
451bdd1243dSDimitry Andric     applyRelX86(off, rel.Type, os, s, p, imageBase);
4520b57cec5SDimitry Andric     break;
453*0fca6ea1SDimitry Andric   case Triple::thumb:
454bdd1243dSDimitry Andric     applyRelARM(off, rel.Type, os, s, p, imageBase);
4550b57cec5SDimitry Andric     break;
456*0fca6ea1SDimitry Andric   case Triple::aarch64:
457bdd1243dSDimitry Andric     applyRelARM64(off, rel.Type, os, s, p, imageBase);
4580b57cec5SDimitry Andric     break;
4590b57cec5SDimitry Andric   default:
4600b57cec5SDimitry Andric     llvm_unreachable("unknown machine type");
4610b57cec5SDimitry Andric   }
4620b57cec5SDimitry Andric }
463e8d8bef9SDimitry Andric 
464e8d8bef9SDimitry Andric // Defend against unsorted relocations. This may be overly conservative.
sortRelocations()465e8d8bef9SDimitry Andric void SectionChunk::sortRelocations() {
466e8d8bef9SDimitry Andric   auto cmpByVa = [](const coff_relocation &l, const coff_relocation &r) {
467e8d8bef9SDimitry Andric     return l.VirtualAddress < r.VirtualAddress;
468e8d8bef9SDimitry Andric   };
469e8d8bef9SDimitry Andric   if (llvm::is_sorted(getRelocs(), cmpByVa))
470e8d8bef9SDimitry Andric     return;
471e8d8bef9SDimitry Andric   warn("some relocations in " + file->getName() + " are not sorted");
472e8d8bef9SDimitry Andric   MutableArrayRef<coff_relocation> newRelocs(
47304eeddc0SDimitry Andric       bAlloc().Allocate<coff_relocation>(relocsSize), relocsSize);
474e8d8bef9SDimitry Andric   memcpy(newRelocs.data(), relocsData, relocsSize * sizeof(coff_relocation));
475e8d8bef9SDimitry Andric   llvm::sort(newRelocs, cmpByVa);
476e8d8bef9SDimitry Andric   setRelocs(newRelocs);
477e8d8bef9SDimitry Andric }
478e8d8bef9SDimitry Andric 
479e8d8bef9SDimitry Andric // Similar to writeTo, but suitable for relocating a subsection of the overall
480e8d8bef9SDimitry Andric // section.
writeAndRelocateSubsection(ArrayRef<uint8_t> sec,ArrayRef<uint8_t> subsec,uint32_t & nextRelocIndex,uint8_t * buf) const481e8d8bef9SDimitry Andric void SectionChunk::writeAndRelocateSubsection(ArrayRef<uint8_t> sec,
482e8d8bef9SDimitry Andric                                               ArrayRef<uint8_t> subsec,
483e8d8bef9SDimitry Andric                                               uint32_t &nextRelocIndex,
484e8d8bef9SDimitry Andric                                               uint8_t *buf) const {
485e8d8bef9SDimitry Andric   assert(!subsec.empty() && !sec.empty());
486e8d8bef9SDimitry Andric   assert(sec.begin() <= subsec.begin() && subsec.end() <= sec.end() &&
487e8d8bef9SDimitry Andric          "subsection is not part of this section");
488e8d8bef9SDimitry Andric   size_t vaBegin = std::distance(sec.begin(), subsec.begin());
489e8d8bef9SDimitry Andric   size_t vaEnd = std::distance(sec.begin(), subsec.end());
490e8d8bef9SDimitry Andric   memcpy(buf, subsec.data(), subsec.size());
491e8d8bef9SDimitry Andric   for (; nextRelocIndex < relocsSize; ++nextRelocIndex) {
492e8d8bef9SDimitry Andric     const coff_relocation &rel = relocsData[nextRelocIndex];
493e8d8bef9SDimitry Andric     // Only apply relocations that apply to this subsection. These checks
494e8d8bef9SDimitry Andric     // assume that all subsections completely contain their relocations.
495e8d8bef9SDimitry Andric     // Relocations must not straddle the beginning or end of a subsection.
496e8d8bef9SDimitry Andric     if (rel.VirtualAddress < vaBegin)
497e8d8bef9SDimitry Andric       continue;
498e8d8bef9SDimitry Andric     if (rel.VirtualAddress + 1 >= vaEnd)
499e8d8bef9SDimitry Andric       break;
500e8d8bef9SDimitry Andric     applyRelocation(&buf[rel.VirtualAddress - vaBegin], rel);
501e8d8bef9SDimitry Andric   }
5020b57cec5SDimitry Andric }
5030b57cec5SDimitry Andric 
addAssociative(SectionChunk * child)5040b57cec5SDimitry Andric void SectionChunk::addAssociative(SectionChunk *child) {
505fe6060f1SDimitry Andric   // Insert the child section into the list of associated children. Keep the
506fe6060f1SDimitry Andric   // list ordered by section name so that ICF does not depend on section order.
5070b57cec5SDimitry Andric   assert(child->assocChildren == nullptr &&
5080b57cec5SDimitry Andric          "associated sections cannot have their own associated children");
509fe6060f1SDimitry Andric   SectionChunk *prev = this;
510fe6060f1SDimitry Andric   SectionChunk *next = assocChildren;
511fe6060f1SDimitry Andric   for (; next != nullptr; prev = next, next = next->assocChildren) {
512fe6060f1SDimitry Andric     if (next->getSectionName() <= child->getSectionName())
513fe6060f1SDimitry Andric       break;
514fe6060f1SDimitry Andric   }
515fe6060f1SDimitry Andric 
516fe6060f1SDimitry Andric   // Insert child between prev and next.
517fe6060f1SDimitry Andric   assert(prev->assocChildren == next);
518fe6060f1SDimitry Andric   prev->assocChildren = child;
519fe6060f1SDimitry Andric   child->assocChildren = next;
5200b57cec5SDimitry Andric }
5210b57cec5SDimitry Andric 
getBaserelType(const coff_relocation & rel,Triple::ArchType arch)522bdd1243dSDimitry Andric static uint8_t getBaserelType(const coff_relocation &rel,
523*0fca6ea1SDimitry Andric                               Triple::ArchType arch) {
524*0fca6ea1SDimitry Andric   switch (arch) {
525*0fca6ea1SDimitry Andric   case Triple::x86_64:
5260b57cec5SDimitry Andric     if (rel.Type == IMAGE_REL_AMD64_ADDR64)
5270b57cec5SDimitry Andric       return IMAGE_REL_BASED_DIR64;
528fe6060f1SDimitry Andric     if (rel.Type == IMAGE_REL_AMD64_ADDR32)
529fe6060f1SDimitry Andric       return IMAGE_REL_BASED_HIGHLOW;
5300b57cec5SDimitry Andric     return IMAGE_REL_BASED_ABSOLUTE;
531*0fca6ea1SDimitry Andric   case Triple::x86:
5320b57cec5SDimitry Andric     if (rel.Type == IMAGE_REL_I386_DIR32)
5330b57cec5SDimitry Andric       return IMAGE_REL_BASED_HIGHLOW;
5340b57cec5SDimitry Andric     return IMAGE_REL_BASED_ABSOLUTE;
535*0fca6ea1SDimitry Andric   case Triple::thumb:
5360b57cec5SDimitry Andric     if (rel.Type == IMAGE_REL_ARM_ADDR32)
5370b57cec5SDimitry Andric       return IMAGE_REL_BASED_HIGHLOW;
5380b57cec5SDimitry Andric     if (rel.Type == IMAGE_REL_ARM_MOV32T)
5390b57cec5SDimitry Andric       return IMAGE_REL_BASED_ARM_MOV32T;
5400b57cec5SDimitry Andric     return IMAGE_REL_BASED_ABSOLUTE;
541*0fca6ea1SDimitry Andric   case Triple::aarch64:
5420b57cec5SDimitry Andric     if (rel.Type == IMAGE_REL_ARM64_ADDR64)
5430b57cec5SDimitry Andric       return IMAGE_REL_BASED_DIR64;
5440b57cec5SDimitry Andric     return IMAGE_REL_BASED_ABSOLUTE;
5450b57cec5SDimitry Andric   default:
5460b57cec5SDimitry Andric     llvm_unreachable("unknown machine type");
5470b57cec5SDimitry Andric   }
5480b57cec5SDimitry Andric }
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric // Windows-specific.
5510b57cec5SDimitry Andric // Collect all locations that contain absolute addresses, which need to be
5520b57cec5SDimitry Andric // fixed by the loader if load-time relocation is needed.
5530b57cec5SDimitry Andric // Only called when base relocation is enabled.
getBaserels(std::vector<Baserel> * res)5540b57cec5SDimitry Andric void SectionChunk::getBaserels(std::vector<Baserel> *res) {
555e8d8bef9SDimitry Andric   for (const coff_relocation &rel : getRelocs()) {
556*0fca6ea1SDimitry Andric     uint8_t ty = getBaserelType(rel, getArch());
5570b57cec5SDimitry Andric     if (ty == IMAGE_REL_BASED_ABSOLUTE)
5580b57cec5SDimitry Andric       continue;
5590b57cec5SDimitry Andric     Symbol *target = file->getSymbol(rel.SymbolTableIndex);
5600b57cec5SDimitry Andric     if (!target || isa<DefinedAbsolute>(target))
5610b57cec5SDimitry Andric       continue;
5620b57cec5SDimitry Andric     res->emplace_back(rva + rel.VirtualAddress, ty);
5630b57cec5SDimitry Andric   }
5640b57cec5SDimitry Andric }
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric // MinGW specific.
5670b57cec5SDimitry Andric // Check whether a static relocation of type Type can be deferred and
5680b57cec5SDimitry Andric // handled at runtime as a pseudo relocation (for references to a module
5690b57cec5SDimitry Andric // local variable, which turned out to actually need to be imported from
5700b57cec5SDimitry Andric // another DLL) This returns the size the relocation is supposed to update,
5710b57cec5SDimitry Andric // in bits, or 0 if the relocation cannot be handled as a runtime pseudo
5720b57cec5SDimitry Andric // relocation.
getRuntimePseudoRelocSize(uint16_t type,llvm::COFF::MachineTypes machine)573bdd1243dSDimitry Andric static int getRuntimePseudoRelocSize(uint16_t type,
574bdd1243dSDimitry Andric                                      llvm::COFF::MachineTypes machine) {
5750b57cec5SDimitry Andric   // Relocations that either contain an absolute address, or a plain
5760b57cec5SDimitry Andric   // relative offset, since the runtime pseudo reloc implementation
5770b57cec5SDimitry Andric   // adds 8/16/32/64 bit values to a memory address.
5780b57cec5SDimitry Andric   //
5790b57cec5SDimitry Andric   // Given a pseudo relocation entry,
5800b57cec5SDimitry Andric   //
5810b57cec5SDimitry Andric   // typedef struct {
5820b57cec5SDimitry Andric   //   DWORD sym;
5830b57cec5SDimitry Andric   //   DWORD target;
5840b57cec5SDimitry Andric   //   DWORD flags;
5850b57cec5SDimitry Andric   // } runtime_pseudo_reloc_item_v2;
5860b57cec5SDimitry Andric   //
5870b57cec5SDimitry Andric   // the runtime relocation performs this adjustment:
5880b57cec5SDimitry Andric   //     *(base + .target) += *(base + .sym) - (base + .sym)
5890b57cec5SDimitry Andric   //
5900b57cec5SDimitry Andric   // This works for both absolute addresses (IMAGE_REL_*_ADDR32/64,
5910b57cec5SDimitry Andric   // IMAGE_REL_I386_DIR32, where the memory location initially contains
5920b57cec5SDimitry Andric   // the address of the IAT slot, and for relative addresses (IMAGE_REL*_REL32),
5930b57cec5SDimitry Andric   // where the memory location originally contains the relative offset to the
5940b57cec5SDimitry Andric   // IAT slot.
5950b57cec5SDimitry Andric   //
5960b57cec5SDimitry Andric   // This requires the target address to be writable, either directly out of
5970b57cec5SDimitry Andric   // the image, or temporarily changed at runtime with VirtualProtect.
5980b57cec5SDimitry Andric   // Since this only operates on direct address values, it doesn't work for
5990b57cec5SDimitry Andric   // ARM/ARM64 relocations, other than the plain ADDR32/ADDR64 relocations.
600bdd1243dSDimitry Andric   switch (machine) {
6010b57cec5SDimitry Andric   case AMD64:
6020b57cec5SDimitry Andric     switch (type) {
6030b57cec5SDimitry Andric     case IMAGE_REL_AMD64_ADDR64:
6040b57cec5SDimitry Andric       return 64;
6050b57cec5SDimitry Andric     case IMAGE_REL_AMD64_ADDR32:
6060b57cec5SDimitry Andric     case IMAGE_REL_AMD64_REL32:
6070b57cec5SDimitry Andric     case IMAGE_REL_AMD64_REL32_1:
6080b57cec5SDimitry Andric     case IMAGE_REL_AMD64_REL32_2:
6090b57cec5SDimitry Andric     case IMAGE_REL_AMD64_REL32_3:
6100b57cec5SDimitry Andric     case IMAGE_REL_AMD64_REL32_4:
6110b57cec5SDimitry Andric     case IMAGE_REL_AMD64_REL32_5:
6120b57cec5SDimitry Andric       return 32;
6130b57cec5SDimitry Andric     default:
6140b57cec5SDimitry Andric       return 0;
6150b57cec5SDimitry Andric     }
6160b57cec5SDimitry Andric   case I386:
6170b57cec5SDimitry Andric     switch (type) {
6180b57cec5SDimitry Andric     case IMAGE_REL_I386_DIR32:
6190b57cec5SDimitry Andric     case IMAGE_REL_I386_REL32:
6200b57cec5SDimitry Andric       return 32;
6210b57cec5SDimitry Andric     default:
6220b57cec5SDimitry Andric       return 0;
6230b57cec5SDimitry Andric     }
6240b57cec5SDimitry Andric   case ARMNT:
6250b57cec5SDimitry Andric     switch (type) {
6260b57cec5SDimitry Andric     case IMAGE_REL_ARM_ADDR32:
6270b57cec5SDimitry Andric       return 32;
6280b57cec5SDimitry Andric     default:
6290b57cec5SDimitry Andric       return 0;
6300b57cec5SDimitry Andric     }
6310b57cec5SDimitry Andric   case ARM64:
6320b57cec5SDimitry Andric     switch (type) {
6330b57cec5SDimitry Andric     case IMAGE_REL_ARM64_ADDR64:
6340b57cec5SDimitry Andric       return 64;
6350b57cec5SDimitry Andric     case IMAGE_REL_ARM64_ADDR32:
6360b57cec5SDimitry Andric       return 32;
6370b57cec5SDimitry Andric     default:
6380b57cec5SDimitry Andric       return 0;
6390b57cec5SDimitry Andric     }
6400b57cec5SDimitry Andric   default:
6410b57cec5SDimitry Andric     llvm_unreachable("unknown machine type");
6420b57cec5SDimitry Andric   }
6430b57cec5SDimitry Andric }
6440b57cec5SDimitry Andric 
6450b57cec5SDimitry Andric // MinGW specific.
6460b57cec5SDimitry Andric // Append information to the provided vector about all relocations that
6470b57cec5SDimitry Andric // need to be handled at runtime as runtime pseudo relocations (references
6480b57cec5SDimitry Andric // to a module local variable, which turned out to actually need to be
6490b57cec5SDimitry Andric // imported from another DLL).
getRuntimePseudoRelocs(std::vector<RuntimePseudoReloc> & res)6500b57cec5SDimitry Andric void SectionChunk::getRuntimePseudoRelocs(
6510b57cec5SDimitry Andric     std::vector<RuntimePseudoReloc> &res) {
6520b57cec5SDimitry Andric   for (const coff_relocation &rel : getRelocs()) {
6530b57cec5SDimitry Andric     auto *target =
6540b57cec5SDimitry Andric         dyn_cast_or_null<Defined>(file->getSymbol(rel.SymbolTableIndex));
6550b57cec5SDimitry Andric     if (!target || !target->isRuntimePseudoReloc)
6560b57cec5SDimitry Andric       continue;
657dfa39133SDimitry Andric     // If the target doesn't have a chunk allocated, it may be a
658dfa39133SDimitry Andric     // DefinedImportData symbol which ended up unnecessary after GC.
659dfa39133SDimitry Andric     // Normally we wouldn't eliminate section chunks that are referenced, but
660dfa39133SDimitry Andric     // references within DWARF sections don't count for keeping section chunks
661dfa39133SDimitry Andric     // alive. Thus such dangling references in DWARF sections are expected.
662dfa39133SDimitry Andric     if (!target->getChunk())
663dfa39133SDimitry Andric       continue;
664bdd1243dSDimitry Andric     int sizeInBits =
665bdd1243dSDimitry Andric         getRuntimePseudoRelocSize(rel.Type, file->ctx.config.machine);
6660b57cec5SDimitry Andric     if (sizeInBits == 0) {
6670b57cec5SDimitry Andric       error("unable to automatically import from " + target->getName() +
6680b57cec5SDimitry Andric             " with relocation type " +
6690b57cec5SDimitry Andric             file->getCOFFObj()->getRelocationTypeName(rel.Type) + " in " +
6700b57cec5SDimitry Andric             toString(file));
6710b57cec5SDimitry Andric       continue;
6720b57cec5SDimitry Andric     }
67306c3fb27SDimitry Andric     int addressSizeInBits = file->ctx.config.is64() ? 64 : 32;
67406c3fb27SDimitry Andric     if (sizeInBits < addressSizeInBits) {
67506c3fb27SDimitry Andric       warn("runtime pseudo relocation in " + toString(file) + " against " +
67606c3fb27SDimitry Andric            "symbol " + target->getName() + " is too narrow (only " +
67706c3fb27SDimitry Andric            Twine(sizeInBits) + " bits wide); this can fail at runtime " +
67806c3fb27SDimitry Andric            "depending on memory layout");
67906c3fb27SDimitry Andric     }
6800b57cec5SDimitry Andric     // sizeInBits is used to initialize the Flags field; currently no
6810b57cec5SDimitry Andric     // other flags are defined.
68206c3fb27SDimitry Andric     res.emplace_back(target, this, rel.VirtualAddress, sizeInBits);
6830b57cec5SDimitry Andric   }
6840b57cec5SDimitry Andric }
6850b57cec5SDimitry Andric 
isCOMDAT() const6860b57cec5SDimitry Andric bool SectionChunk::isCOMDAT() const {
6870b57cec5SDimitry Andric   return header->Characteristics & IMAGE_SCN_LNK_COMDAT;
6880b57cec5SDimitry Andric }
6890b57cec5SDimitry Andric 
printDiscardedMessage() const6900b57cec5SDimitry Andric void SectionChunk::printDiscardedMessage() const {
6910b57cec5SDimitry Andric   // Removed by dead-stripping. If it's removed by ICF, ICF already
6920b57cec5SDimitry Andric   // printed out the name, so don't repeat that here.
6930b57cec5SDimitry Andric   if (sym && this == repl)
69404eeddc0SDimitry Andric     log("Discarded " + sym->getName());
6950b57cec5SDimitry Andric }
6960b57cec5SDimitry Andric 
getDebugName() const6970b57cec5SDimitry Andric StringRef SectionChunk::getDebugName() const {
6980b57cec5SDimitry Andric   if (sym)
6990b57cec5SDimitry Andric     return sym->getName();
7000b57cec5SDimitry Andric   return "";
7010b57cec5SDimitry Andric }
7020b57cec5SDimitry Andric 
getContents() const7030b57cec5SDimitry Andric ArrayRef<uint8_t> SectionChunk::getContents() const {
7040b57cec5SDimitry Andric   ArrayRef<uint8_t> a;
7050b57cec5SDimitry Andric   cantFail(file->getCOFFObj()->getSectionContents(header, a));
7060b57cec5SDimitry Andric   return a;
7070b57cec5SDimitry Andric }
7080b57cec5SDimitry Andric 
consumeDebugMagic()7090b57cec5SDimitry Andric ArrayRef<uint8_t> SectionChunk::consumeDebugMagic() {
7100b57cec5SDimitry Andric   assert(isCodeView());
7110b57cec5SDimitry Andric   return consumeDebugMagic(getContents(), getSectionName());
7120b57cec5SDimitry Andric }
7130b57cec5SDimitry Andric 
consumeDebugMagic(ArrayRef<uint8_t> data,StringRef sectionName)7140b57cec5SDimitry Andric ArrayRef<uint8_t> SectionChunk::consumeDebugMagic(ArrayRef<uint8_t> data,
7150b57cec5SDimitry Andric                                                   StringRef sectionName) {
7160b57cec5SDimitry Andric   if (data.empty())
7170b57cec5SDimitry Andric     return {};
7180b57cec5SDimitry Andric 
7190b57cec5SDimitry Andric   // First 4 bytes are section magic.
7200b57cec5SDimitry Andric   if (data.size() < 4)
7210b57cec5SDimitry Andric     fatal("the section is too short: " + sectionName);
7220b57cec5SDimitry Andric 
72306c3fb27SDimitry Andric   if (!sectionName.starts_with(".debug$"))
7240b57cec5SDimitry Andric     fatal("invalid section: " + sectionName);
7250b57cec5SDimitry Andric 
7260b57cec5SDimitry Andric   uint32_t magic = support::endian::read32le(data.data());
7270b57cec5SDimitry Andric   uint32_t expectedMagic = sectionName == ".debug$H"
7280b57cec5SDimitry Andric                                ? DEBUG_HASHES_SECTION_MAGIC
7290b57cec5SDimitry Andric                                : DEBUG_SECTION_MAGIC;
7300b57cec5SDimitry Andric   if (magic != expectedMagic) {
7310b57cec5SDimitry Andric     warn("ignoring section " + sectionName + " with unrecognized magic 0x" +
7320b57cec5SDimitry Andric          utohexstr(magic));
7330b57cec5SDimitry Andric     return {};
7340b57cec5SDimitry Andric   }
7350b57cec5SDimitry Andric   return data.slice(4);
7360b57cec5SDimitry Andric }
7370b57cec5SDimitry Andric 
findByName(ArrayRef<SectionChunk * > sections,StringRef name)7380b57cec5SDimitry Andric SectionChunk *SectionChunk::findByName(ArrayRef<SectionChunk *> sections,
7390b57cec5SDimitry Andric                                        StringRef name) {
7400b57cec5SDimitry Andric   for (SectionChunk *c : sections)
7410b57cec5SDimitry Andric     if (c->getSectionName() == name)
7420b57cec5SDimitry Andric       return c;
7430b57cec5SDimitry Andric   return nullptr;
7440b57cec5SDimitry Andric }
7450b57cec5SDimitry Andric 
replace(SectionChunk * other)7460b57cec5SDimitry Andric void SectionChunk::replace(SectionChunk *other) {
7470b57cec5SDimitry Andric   p2Align = std::max(p2Align, other->p2Align);
7480b57cec5SDimitry Andric   other->repl = repl;
7490b57cec5SDimitry Andric   other->live = false;
7500b57cec5SDimitry Andric }
7510b57cec5SDimitry Andric 
getSectionNumber() const7520b57cec5SDimitry Andric uint32_t SectionChunk::getSectionNumber() const {
7530b57cec5SDimitry Andric   DataRefImpl r;
7540b57cec5SDimitry Andric   r.p = reinterpret_cast<uintptr_t>(header);
7550b57cec5SDimitry Andric   SectionRef s(r, file->getCOFFObj());
7560b57cec5SDimitry Andric   return s.getIndex() + 1;
7570b57cec5SDimitry Andric }
7580b57cec5SDimitry Andric 
CommonChunk(const COFFSymbolRef s)7590b57cec5SDimitry Andric CommonChunk::CommonChunk(const COFFSymbolRef s) : sym(s) {
7600b57cec5SDimitry Andric   // The value of a common symbol is its size. Align all common symbols smaller
7610b57cec5SDimitry Andric   // than 32 bytes naturally, i.e. round the size up to the next power of two.
7620b57cec5SDimitry Andric   // This is what MSVC link.exe does.
7630b57cec5SDimitry Andric   setAlignment(std::min(32U, uint32_t(PowerOf2Ceil(sym.getValue()))));
7640b57cec5SDimitry Andric   hasData = false;
7650b57cec5SDimitry Andric }
7660b57cec5SDimitry Andric 
getOutputCharacteristics() const7670b57cec5SDimitry Andric uint32_t CommonChunk::getOutputCharacteristics() const {
7680b57cec5SDimitry Andric   return IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ |
7690b57cec5SDimitry Andric          IMAGE_SCN_MEM_WRITE;
7700b57cec5SDimitry Andric }
7710b57cec5SDimitry Andric 
writeTo(uint8_t * buf) const7720b57cec5SDimitry Andric void StringChunk::writeTo(uint8_t *buf) const {
7730b57cec5SDimitry Andric   memcpy(buf, str.data(), str.size());
7740b57cec5SDimitry Andric   buf[str.size()] = '\0';
7750b57cec5SDimitry Andric }
7760b57cec5SDimitry Andric 
ImportThunkChunkX64(COFFLinkerContext & ctx,Defined * s)777bdd1243dSDimitry Andric ImportThunkChunkX64::ImportThunkChunkX64(COFFLinkerContext &ctx, Defined *s)
778bdd1243dSDimitry Andric     : ImportThunkChunk(ctx, s) {
7790b57cec5SDimitry Andric   // Intel Optimization Manual says that all branch targets
7800b57cec5SDimitry Andric   // should be 16-byte aligned. MSVC linker does this too.
7810b57cec5SDimitry Andric   setAlignment(16);
7820b57cec5SDimitry Andric }
7830b57cec5SDimitry Andric 
writeTo(uint8_t * buf) const7840b57cec5SDimitry Andric void ImportThunkChunkX64::writeTo(uint8_t *buf) const {
7850b57cec5SDimitry Andric   memcpy(buf, importThunkX86, sizeof(importThunkX86));
7860b57cec5SDimitry Andric   // The first two bytes is a JMP instruction. Fill its operand.
7870b57cec5SDimitry Andric   write32le(buf + 2, impSymbol->getRVA() - rva - getSize());
7880b57cec5SDimitry Andric }
7890b57cec5SDimitry Andric 
getBaserels(std::vector<Baserel> * res)7900b57cec5SDimitry Andric void ImportThunkChunkX86::getBaserels(std::vector<Baserel> *res) {
791bdd1243dSDimitry Andric   res->emplace_back(getRVA() + 2, ctx.config.machine);
7920b57cec5SDimitry Andric }
7930b57cec5SDimitry Andric 
writeTo(uint8_t * buf) const7940b57cec5SDimitry Andric void ImportThunkChunkX86::writeTo(uint8_t *buf) const {
7950b57cec5SDimitry Andric   memcpy(buf, importThunkX86, sizeof(importThunkX86));
7960b57cec5SDimitry Andric   // The first two bytes is a JMP instruction. Fill its operand.
797bdd1243dSDimitry Andric   write32le(buf + 2, impSymbol->getRVA() + ctx.config.imageBase);
7980b57cec5SDimitry Andric }
7990b57cec5SDimitry Andric 
getBaserels(std::vector<Baserel> * res)8000b57cec5SDimitry Andric void ImportThunkChunkARM::getBaserels(std::vector<Baserel> *res) {
8010b57cec5SDimitry Andric   res->emplace_back(getRVA(), IMAGE_REL_BASED_ARM_MOV32T);
8020b57cec5SDimitry Andric }
8030b57cec5SDimitry Andric 
writeTo(uint8_t * buf) const8040b57cec5SDimitry Andric void ImportThunkChunkARM::writeTo(uint8_t *buf) const {
8050b57cec5SDimitry Andric   memcpy(buf, importThunkARM, sizeof(importThunkARM));
8060b57cec5SDimitry Andric   // Fix mov.w and mov.t operands.
807bdd1243dSDimitry Andric   applyMOV32T(buf, impSymbol->getRVA() + ctx.config.imageBase);
8080b57cec5SDimitry Andric }
8090b57cec5SDimitry Andric 
writeTo(uint8_t * buf) const8100b57cec5SDimitry Andric void ImportThunkChunkARM64::writeTo(uint8_t *buf) const {
8110b57cec5SDimitry Andric   int64_t off = impSymbol->getRVA() & 0xfff;
8120b57cec5SDimitry Andric   memcpy(buf, importThunkARM64, sizeof(importThunkARM64));
8130b57cec5SDimitry Andric   applyArm64Addr(buf, impSymbol->getRVA(), rva, 12);
8140b57cec5SDimitry Andric   applyArm64Ldr(buf + 4, off);
8150b57cec5SDimitry Andric }
8160b57cec5SDimitry Andric 
8170b57cec5SDimitry Andric // A Thumb2, PIC, non-interworking range extension thunk.
8180b57cec5SDimitry Andric const uint8_t armThunk[] = {
8190b57cec5SDimitry Andric     0x40, 0xf2, 0x00, 0x0c, // P:  movw ip,:lower16:S - (P + (L1-P) + 4)
8200b57cec5SDimitry Andric     0xc0, 0xf2, 0x00, 0x0c, //     movt ip,:upper16:S - (P + (L1-P) + 4)
8210b57cec5SDimitry Andric     0xe7, 0x44,             // L1: add  pc, ip
8220b57cec5SDimitry Andric };
8230b57cec5SDimitry Andric 
getSize() const8240b57cec5SDimitry Andric size_t RangeExtensionThunkARM::getSize() const {
825bdd1243dSDimitry Andric   assert(ctx.config.machine == ARMNT);
826bdd1243dSDimitry Andric   (void)&ctx;
8270b57cec5SDimitry Andric   return sizeof(armThunk);
8280b57cec5SDimitry Andric }
8290b57cec5SDimitry Andric 
writeTo(uint8_t * buf) const8300b57cec5SDimitry Andric void RangeExtensionThunkARM::writeTo(uint8_t *buf) const {
831bdd1243dSDimitry Andric   assert(ctx.config.machine == ARMNT);
8320b57cec5SDimitry Andric   uint64_t offset = target->getRVA() - rva - 12;
8330b57cec5SDimitry Andric   memcpy(buf, armThunk, sizeof(armThunk));
8340b57cec5SDimitry Andric   applyMOV32T(buf, uint32_t(offset));
8350b57cec5SDimitry Andric }
8360b57cec5SDimitry Andric 
8370b57cec5SDimitry Andric // A position independent ARM64 adrp+add thunk, with a maximum range of
8380b57cec5SDimitry Andric // +/- 4 GB, which is enough for any PE-COFF.
8390b57cec5SDimitry Andric const uint8_t arm64Thunk[] = {
8400b57cec5SDimitry Andric     0x10, 0x00, 0x00, 0x90, // adrp x16, Dest
8410b57cec5SDimitry Andric     0x10, 0x02, 0x00, 0x91, // add  x16, x16, :lo12:Dest
8420b57cec5SDimitry Andric     0x00, 0x02, 0x1f, 0xd6, // br   x16
8430b57cec5SDimitry Andric };
8440b57cec5SDimitry Andric 
getSize() const8450b57cec5SDimitry Andric size_t RangeExtensionThunkARM64::getSize() const {
846bdd1243dSDimitry Andric   assert(ctx.config.machine == ARM64);
847bdd1243dSDimitry Andric   (void)&ctx;
8480b57cec5SDimitry Andric   return sizeof(arm64Thunk);
8490b57cec5SDimitry Andric }
8500b57cec5SDimitry Andric 
writeTo(uint8_t * buf) const8510b57cec5SDimitry Andric void RangeExtensionThunkARM64::writeTo(uint8_t *buf) const {
852bdd1243dSDimitry Andric   assert(ctx.config.machine == ARM64);
8530b57cec5SDimitry Andric   memcpy(buf, arm64Thunk, sizeof(arm64Thunk));
8540b57cec5SDimitry Andric   applyArm64Addr(buf + 0, target->getRVA(), rva, 12);
8550b57cec5SDimitry Andric   applyArm64Imm(buf + 4, target->getRVA() & 0xfff, 0);
8560b57cec5SDimitry Andric }
8570b57cec5SDimitry Andric 
LocalImportChunk(COFFLinkerContext & c,Defined * s)858bdd1243dSDimitry Andric LocalImportChunk::LocalImportChunk(COFFLinkerContext &c, Defined *s)
859bdd1243dSDimitry Andric     : sym(s), ctx(c) {
860bdd1243dSDimitry Andric   setAlignment(ctx.config.wordsize);
8610b57cec5SDimitry Andric }
8620b57cec5SDimitry Andric 
getBaserels(std::vector<Baserel> * res)863bdd1243dSDimitry Andric void LocalImportChunk::getBaserels(std::vector<Baserel> *res) {
864bdd1243dSDimitry Andric   res->emplace_back(getRVA(), ctx.config.machine);
865bdd1243dSDimitry Andric }
866bdd1243dSDimitry Andric 
getSize() const867bdd1243dSDimitry Andric size_t LocalImportChunk::getSize() const { return ctx.config.wordsize; }
8680b57cec5SDimitry Andric 
writeTo(uint8_t * buf) const8690b57cec5SDimitry Andric void LocalImportChunk::writeTo(uint8_t *buf) const {
870bdd1243dSDimitry Andric   if (ctx.config.is64()) {
871bdd1243dSDimitry Andric     write64le(buf, sym->getRVA() + ctx.config.imageBase);
8720b57cec5SDimitry Andric   } else {
873bdd1243dSDimitry Andric     write32le(buf, sym->getRVA() + ctx.config.imageBase);
8740b57cec5SDimitry Andric   }
8750b57cec5SDimitry Andric }
8760b57cec5SDimitry Andric 
writeTo(uint8_t * buf) const8770b57cec5SDimitry Andric void RVATableChunk::writeTo(uint8_t *buf) const {
8780b57cec5SDimitry Andric   ulittle32_t *begin = reinterpret_cast<ulittle32_t *>(buf);
8790b57cec5SDimitry Andric   size_t cnt = 0;
8800b57cec5SDimitry Andric   for (const ChunkAndOffset &co : syms)
8810b57cec5SDimitry Andric     begin[cnt++] = co.inputChunk->getRVA() + co.offset;
882fcaf7f86SDimitry Andric   llvm::sort(begin, begin + cnt);
8830b57cec5SDimitry Andric   assert(std::unique(begin, begin + cnt) == begin + cnt &&
8840b57cec5SDimitry Andric          "RVA tables should be de-duplicated");
8850b57cec5SDimitry Andric }
8860b57cec5SDimitry Andric 
writeTo(uint8_t * buf) const887fe6060f1SDimitry Andric void RVAFlagTableChunk::writeTo(uint8_t *buf) const {
888fe6060f1SDimitry Andric   struct RVAFlag {
889fe6060f1SDimitry Andric     ulittle32_t rva;
890fe6060f1SDimitry Andric     uint8_t flag;
891fe6060f1SDimitry Andric   };
892fe6060f1SDimitry Andric   auto flags =
893bdd1243dSDimitry Andric       MutableArrayRef(reinterpret_cast<RVAFlag *>(buf), syms.size());
894fe6060f1SDimitry Andric   for (auto t : zip(syms, flags)) {
895fe6060f1SDimitry Andric     const auto &sym = std::get<0>(t);
896fe6060f1SDimitry Andric     auto &flag = std::get<1>(t);
897fe6060f1SDimitry Andric     flag.rva = sym.inputChunk->getRVA() + sym.offset;
898fe6060f1SDimitry Andric     flag.flag = 0;
899fe6060f1SDimitry Andric   }
900fe6060f1SDimitry Andric   llvm::sort(flags,
901fe6060f1SDimitry Andric              [](const RVAFlag &a, const RVAFlag &b) { return a.rva < b.rva; });
902fe6060f1SDimitry Andric   assert(llvm::unique(flags, [](const RVAFlag &a,
903fe6060f1SDimitry Andric                                 const RVAFlag &b) { return a.rva == b.rva; }) ==
904fe6060f1SDimitry Andric              flags.end() &&
905fe6060f1SDimitry Andric          "RVA tables should be de-duplicated");
906fe6060f1SDimitry Andric }
907fe6060f1SDimitry Andric 
getSize() const9085f757f3fSDimitry Andric size_t ECCodeMapChunk::getSize() const {
9095f757f3fSDimitry Andric   return map.size() * sizeof(chpe_range_entry);
9105f757f3fSDimitry Andric }
9115f757f3fSDimitry Andric 
writeTo(uint8_t * buf) const9125f757f3fSDimitry Andric void ECCodeMapChunk::writeTo(uint8_t *buf) const {
9135f757f3fSDimitry Andric   auto table = reinterpret_cast<chpe_range_entry *>(buf);
9145f757f3fSDimitry Andric   for (uint32_t i = 0; i < map.size(); i++) {
9155f757f3fSDimitry Andric     const ECCodeMapEntry &entry = map[i];
9165f757f3fSDimitry Andric     uint32_t start = entry.first->getRVA();
9175f757f3fSDimitry Andric     table[i].StartOffset = start | entry.type;
9185f757f3fSDimitry Andric     table[i].Length = entry.last->getRVA() + entry.last->getSize() - start;
9195f757f3fSDimitry Andric   }
9205f757f3fSDimitry Andric }
9215f757f3fSDimitry Andric 
9220b57cec5SDimitry Andric // MinGW specific, for the "automatic import of variables from DLLs" feature.
getSize() const9230b57cec5SDimitry Andric size_t PseudoRelocTableChunk::getSize() const {
9240b57cec5SDimitry Andric   if (relocs.empty())
9250b57cec5SDimitry Andric     return 0;
9260b57cec5SDimitry Andric   return 12 + 12 * relocs.size();
9270b57cec5SDimitry Andric }
9280b57cec5SDimitry Andric 
9290b57cec5SDimitry Andric // MinGW specific.
writeTo(uint8_t * buf) const9300b57cec5SDimitry Andric void PseudoRelocTableChunk::writeTo(uint8_t *buf) const {
9310b57cec5SDimitry Andric   if (relocs.empty())
9320b57cec5SDimitry Andric     return;
9330b57cec5SDimitry Andric 
9340b57cec5SDimitry Andric   ulittle32_t *table = reinterpret_cast<ulittle32_t *>(buf);
9350b57cec5SDimitry Andric   // This is the list header, to signal the runtime pseudo relocation v2
9360b57cec5SDimitry Andric   // format.
9370b57cec5SDimitry Andric   table[0] = 0;
9380b57cec5SDimitry Andric   table[1] = 0;
9390b57cec5SDimitry Andric   table[2] = 1;
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric   size_t idx = 3;
9420b57cec5SDimitry Andric   for (const RuntimePseudoReloc &rpr : relocs) {
9430b57cec5SDimitry Andric     table[idx + 0] = rpr.sym->getRVA();
9440b57cec5SDimitry Andric     table[idx + 1] = rpr.target->getRVA() + rpr.targetOffset;
9450b57cec5SDimitry Andric     table[idx + 2] = rpr.flags;
9460b57cec5SDimitry Andric     idx += 3;
9470b57cec5SDimitry Andric   }
9480b57cec5SDimitry Andric }
9490b57cec5SDimitry Andric 
9500b57cec5SDimitry Andric // Windows-specific. This class represents a block in .reloc section.
9510b57cec5SDimitry Andric // The format is described here.
9520b57cec5SDimitry Andric //
9530b57cec5SDimitry Andric // On Windows, each DLL is linked against a fixed base address and
9540b57cec5SDimitry Andric // usually loaded to that address. However, if there's already another
9550b57cec5SDimitry Andric // DLL that overlaps, the loader has to relocate it. To do that, DLLs
9560b57cec5SDimitry Andric // contain .reloc sections which contain offsets that need to be fixed
9570b57cec5SDimitry Andric // up at runtime. If the loader finds that a DLL cannot be loaded to its
9580b57cec5SDimitry Andric // desired base address, it loads it to somewhere else, and add <actual
9590b57cec5SDimitry Andric // base address> - <desired base address> to each offset that is
9600b57cec5SDimitry Andric // specified by the .reloc section. In ELF terms, .reloc sections
9610b57cec5SDimitry Andric // contain relative relocations in REL format (as opposed to RELA.)
9620b57cec5SDimitry Andric //
9630b57cec5SDimitry Andric // This already significantly reduces the size of relocations compared
9640b57cec5SDimitry Andric // to ELF .rel.dyn, but Windows does more to reduce it (probably because
9650b57cec5SDimitry Andric // it was invented for PCs in the late '80s or early '90s.)  Offsets in
9660b57cec5SDimitry Andric // .reloc are grouped by page where the page size is 12 bits, and
9670b57cec5SDimitry Andric // offsets sharing the same page address are stored consecutively to
9680b57cec5SDimitry Andric // represent them with less space. This is very similar to the page
9690b57cec5SDimitry Andric // table which is grouped by (multiple stages of) pages.
9700b57cec5SDimitry Andric //
9710b57cec5SDimitry Andric // For example, let's say we have 0x00030, 0x00500, 0x00700, 0x00A00,
9720b57cec5SDimitry Andric // 0x20004, and 0x20008 in a .reloc section for x64. The uppermost 4
9730b57cec5SDimitry Andric // bits have a type IMAGE_REL_BASED_DIR64 or 0xA. In the section, they
9740b57cec5SDimitry Andric // are represented like this:
9750b57cec5SDimitry Andric //
9760b57cec5SDimitry Andric //   0x00000  -- page address (4 bytes)
9770b57cec5SDimitry Andric //   16       -- size of this block (4 bytes)
9780b57cec5SDimitry Andric //     0xA030 -- entries (2 bytes each)
9790b57cec5SDimitry Andric //     0xA500
9800b57cec5SDimitry Andric //     0xA700
9810b57cec5SDimitry Andric //     0xAA00
9820b57cec5SDimitry Andric //   0x20000  -- page address (4 bytes)
9830b57cec5SDimitry Andric //   12       -- size of this block (4 bytes)
9840b57cec5SDimitry Andric //     0xA004 -- entries (2 bytes each)
9850b57cec5SDimitry Andric //     0xA008
9860b57cec5SDimitry Andric //
9870b57cec5SDimitry Andric // Usually we have a lot of relocations for each page, so the number of
9880b57cec5SDimitry Andric // bytes for one .reloc entry is close to 2 bytes on average.
BaserelChunk(uint32_t page,Baserel * begin,Baserel * end)9890b57cec5SDimitry Andric BaserelChunk::BaserelChunk(uint32_t page, Baserel *begin, Baserel *end) {
9900b57cec5SDimitry Andric   // Block header consists of 4 byte page RVA and 4 byte block size.
9910b57cec5SDimitry Andric   // Each entry is 2 byte. Last entry may be padding.
9920b57cec5SDimitry Andric   data.resize(alignTo((end - begin) * 2 + 8, 4));
9930b57cec5SDimitry Andric   uint8_t *p = data.data();
9940b57cec5SDimitry Andric   write32le(p, page);
9950b57cec5SDimitry Andric   write32le(p + 4, data.size());
9960b57cec5SDimitry Andric   p += 8;
9970b57cec5SDimitry Andric   for (Baserel *i = begin; i != end; ++i) {
9980b57cec5SDimitry Andric     write16le(p, (i->type << 12) | (i->rva - page));
9990b57cec5SDimitry Andric     p += 2;
10000b57cec5SDimitry Andric   }
10010b57cec5SDimitry Andric }
10020b57cec5SDimitry Andric 
writeTo(uint8_t * buf) const10030b57cec5SDimitry Andric void BaserelChunk::writeTo(uint8_t *buf) const {
10040b57cec5SDimitry Andric   memcpy(buf, data.data(), data.size());
10050b57cec5SDimitry Andric }
10060b57cec5SDimitry Andric 
getDefaultType(llvm::COFF::MachineTypes machine)1007bdd1243dSDimitry Andric uint8_t Baserel::getDefaultType(llvm::COFF::MachineTypes machine) {
1008bdd1243dSDimitry Andric   switch (machine) {
10090b57cec5SDimitry Andric   case AMD64:
10100b57cec5SDimitry Andric   case ARM64:
10110b57cec5SDimitry Andric     return IMAGE_REL_BASED_DIR64;
10120b57cec5SDimitry Andric   case I386:
10130b57cec5SDimitry Andric   case ARMNT:
10140b57cec5SDimitry Andric     return IMAGE_REL_BASED_HIGHLOW;
10150b57cec5SDimitry Andric   default:
10160b57cec5SDimitry Andric     llvm_unreachable("unknown machine type");
10170b57cec5SDimitry Andric   }
10180b57cec5SDimitry Andric }
10190b57cec5SDimitry Andric 
MergeChunk(uint32_t alignment)10200b57cec5SDimitry Andric MergeChunk::MergeChunk(uint32_t alignment)
1021bdd1243dSDimitry Andric     : builder(StringTableBuilder::RAW, llvm::Align(alignment)) {
10220b57cec5SDimitry Andric   setAlignment(alignment);
10230b57cec5SDimitry Andric }
10240b57cec5SDimitry Andric 
addSection(COFFLinkerContext & ctx,SectionChunk * c)1025349cc55cSDimitry Andric void MergeChunk::addSection(COFFLinkerContext &ctx, SectionChunk *c) {
10260b57cec5SDimitry Andric   assert(isPowerOf2_32(c->getAlignment()));
10270b57cec5SDimitry Andric   uint8_t p2Align = llvm::Log2_32(c->getAlignment());
1028bdd1243dSDimitry Andric   assert(p2Align < std::size(ctx.mergeChunkInstances));
1029349cc55cSDimitry Andric   auto *&mc = ctx.mergeChunkInstances[p2Align];
10300b57cec5SDimitry Andric   if (!mc)
10310b57cec5SDimitry Andric     mc = make<MergeChunk>(c->getAlignment());
10320b57cec5SDimitry Andric   mc->sections.push_back(c);
10330b57cec5SDimitry Andric }
10340b57cec5SDimitry Andric 
finalizeContents()10350b57cec5SDimitry Andric void MergeChunk::finalizeContents() {
10360b57cec5SDimitry Andric   assert(!finalized && "should only finalize once");
10370b57cec5SDimitry Andric   for (SectionChunk *c : sections)
10380b57cec5SDimitry Andric     if (c->live)
10390b57cec5SDimitry Andric       builder.add(toStringRef(c->getContents()));
10400b57cec5SDimitry Andric   builder.finalize();
10410b57cec5SDimitry Andric   finalized = true;
10420b57cec5SDimitry Andric }
10430b57cec5SDimitry Andric 
assignSubsectionRVAs()10440b57cec5SDimitry Andric void MergeChunk::assignSubsectionRVAs() {
10450b57cec5SDimitry Andric   for (SectionChunk *c : sections) {
10460b57cec5SDimitry Andric     if (!c->live)
10470b57cec5SDimitry Andric       continue;
10480b57cec5SDimitry Andric     size_t off = builder.getOffset(toStringRef(c->getContents()));
10490b57cec5SDimitry Andric     c->setRVA(rva + off);
10500b57cec5SDimitry Andric   }
10510b57cec5SDimitry Andric }
10520b57cec5SDimitry Andric 
getOutputCharacteristics() const10530b57cec5SDimitry Andric uint32_t MergeChunk::getOutputCharacteristics() const {
10540b57cec5SDimitry Andric   return IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA;
10550b57cec5SDimitry Andric }
10560b57cec5SDimitry Andric 
getSize() const10570b57cec5SDimitry Andric size_t MergeChunk::getSize() const {
10580b57cec5SDimitry Andric   return builder.getSize();
10590b57cec5SDimitry Andric }
10600b57cec5SDimitry Andric 
writeTo(uint8_t * buf) const10610b57cec5SDimitry Andric void MergeChunk::writeTo(uint8_t *buf) const {
10620b57cec5SDimitry Andric   builder.write(buf);
10630b57cec5SDimitry Andric }
10640b57cec5SDimitry Andric 
10650b57cec5SDimitry Andric // MinGW specific.
getSize() const1066bdd1243dSDimitry Andric size_t AbsolutePointerChunk::getSize() const { return ctx.config.wordsize; }
10670b57cec5SDimitry Andric 
writeTo(uint8_t * buf) const10680b57cec5SDimitry Andric void AbsolutePointerChunk::writeTo(uint8_t *buf) const {
1069bdd1243dSDimitry Andric   if (ctx.config.is64()) {
10700b57cec5SDimitry Andric     write64le(buf, value);
10710b57cec5SDimitry Andric   } else {
10720b57cec5SDimitry Andric     write32le(buf, value);
10730b57cec5SDimitry Andric   }
10740b57cec5SDimitry Andric }
10750b57cec5SDimitry Andric 
1076bdd1243dSDimitry Andric } // namespace lld::coff
1077