xref: /llvm-project-15.0.7/lld/COFF/Chunks.cpp (revision e00799ea)
1 //===- Chunks.cpp ---------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "Chunks.h"
11 #include "InputFiles.h"
12 #include "Symbols.h"
13 #include "Writer.h"
14 #include "lld/Common/ErrorHandler.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/BinaryFormat/COFF.h"
17 #include "llvm/Object/COFF.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/Endian.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include <algorithm>
22 
23 using namespace llvm;
24 using namespace llvm::object;
25 using namespace llvm::support::endian;
26 using namespace llvm::COFF;
27 using llvm::support::ulittle32_t;
28 
29 namespace lld {
30 namespace coff {
31 
32 SectionChunk::SectionChunk(ObjFile *F, const coff_section *H)
33     : Chunk(SectionKind), Repl(this), Header(H), File(F),
34       Relocs(File->getCOFFObj()->getRelocations(Header)),
35       NumRelocs(std::distance(Relocs.begin(), Relocs.end())) {
36   // Initialize SectionName.
37   File->getCOFFObj()->getSectionName(Header, SectionName);
38 
39   Alignment = Header->getAlignment();
40 
41   // If linker GC is disabled, every chunk starts out alive.  If linker GC is
42   // enabled, treat non-comdat sections as roots. Generally optimized object
43   // files will be built with -ffunction-sections or /Gy, so most things worth
44   // stripping will be in a comdat.
45   Live = !Config->DoGC || !isCOMDAT();
46 }
47 
48 static void add16(uint8_t *P, int16_t V) { write16le(P, read16le(P) + V); }
49 static void add32(uint8_t *P, int32_t V) { write32le(P, read32le(P) + V); }
50 static void add64(uint8_t *P, int64_t V) { write64le(P, read64le(P) + V); }
51 static void or16(uint8_t *P, uint16_t V) { write16le(P, read16le(P) | V); }
52 static void or32(uint8_t *P, uint32_t V) { write32le(P, read32le(P) | V); }
53 
54 // Verify that given sections are appropriate targets for SECREL
55 // relocations. This check is relaxed because unfortunately debug
56 // sections have section-relative relocations against absolute symbols.
57 static bool checkSecRel(const SectionChunk *Sec, OutputSection *OS) {
58   if (OS)
59     return true;
60   if (Sec->isCodeView())
61     return false;
62   fatal("SECREL relocation cannot be applied to absolute symbols");
63 }
64 
65 static void applySecRel(const SectionChunk *Sec, uint8_t *Off,
66                         OutputSection *OS, uint64_t S) {
67   if (!checkSecRel(Sec, OS))
68     return;
69   uint64_t SecRel = S - OS->getRVA();
70   if (SecRel > UINT32_MAX) {
71     error("overflow in SECREL relocation in section: " + Sec->getSectionName());
72     return;
73   }
74   add32(Off, SecRel);
75 }
76 
77 static void applySecIdx(uint8_t *Off, OutputSection *OS) {
78   // Absolute symbol doesn't have section index, but section index relocation
79   // against absolute symbol should be resolved to one plus the last output
80   // section index. This is required for compatibility with MSVC.
81   if (OS)
82     add16(Off, OS->SectionIndex);
83   else
84     add16(Off, DefinedAbsolute::NumOutputSections + 1);
85 }
86 
87 void SectionChunk::applyRelX64(uint8_t *Off, uint16_t Type, OutputSection *OS,
88                                uint64_t S, uint64_t P) const {
89   switch (Type) {
90   case IMAGE_REL_AMD64_ADDR32:   add32(Off, S + Config->ImageBase); break;
91   case IMAGE_REL_AMD64_ADDR64:   add64(Off, S + Config->ImageBase); break;
92   case IMAGE_REL_AMD64_ADDR32NB: add32(Off, S); break;
93   case IMAGE_REL_AMD64_REL32:    add32(Off, S - P - 4); break;
94   case IMAGE_REL_AMD64_REL32_1:  add32(Off, S - P - 5); break;
95   case IMAGE_REL_AMD64_REL32_2:  add32(Off, S - P - 6); break;
96   case IMAGE_REL_AMD64_REL32_3:  add32(Off, S - P - 7); break;
97   case IMAGE_REL_AMD64_REL32_4:  add32(Off, S - P - 8); break;
98   case IMAGE_REL_AMD64_REL32_5:  add32(Off, S - P - 9); break;
99   case IMAGE_REL_AMD64_SECTION:  applySecIdx(Off, OS); break;
100   case IMAGE_REL_AMD64_SECREL:   applySecRel(this, Off, OS, S); break;
101   default:
102     fatal("unsupported relocation type 0x" + Twine::utohexstr(Type));
103   }
104 }
105 
106 void SectionChunk::applyRelX86(uint8_t *Off, uint16_t Type, OutputSection *OS,
107                                uint64_t S, uint64_t P) const {
108   switch (Type) {
109   case IMAGE_REL_I386_ABSOLUTE: break;
110   case IMAGE_REL_I386_DIR32:    add32(Off, S + Config->ImageBase); break;
111   case IMAGE_REL_I386_DIR32NB:  add32(Off, S); break;
112   case IMAGE_REL_I386_REL32:    add32(Off, S - P - 4); break;
113   case IMAGE_REL_I386_SECTION:  applySecIdx(Off, OS); break;
114   case IMAGE_REL_I386_SECREL:   applySecRel(this, Off, OS, S); break;
115   default:
116     fatal("unsupported relocation type 0x" + Twine::utohexstr(Type));
117   }
118 }
119 
120 static void applyMOV(uint8_t *Off, uint16_t V) {
121   write16le(Off, (read16le(Off) & 0xfbf0) | ((V & 0x800) >> 1) | ((V >> 12) & 0xf));
122   write16le(Off + 2, (read16le(Off + 2) & 0x8f00) | ((V & 0x700) << 4) | (V & 0xff));
123 }
124 
125 static uint16_t readMOV(uint8_t *Off) {
126   uint16_t Op1 = read16le(Off);
127   uint16_t Op2 = read16le(Off + 2);
128   return (Op2 & 0x00ff) | ((Op2 >> 4) & 0x0700) | ((Op1 << 1) & 0x0800) |
129          ((Op1 & 0x000f) << 12);
130 }
131 
132 void applyMOV32T(uint8_t *Off, uint32_t V) {
133   uint16_t ImmW = readMOV(Off);     // read MOVW operand
134   uint16_t ImmT = readMOV(Off + 4); // read MOVT operand
135   uint32_t Imm = ImmW | (ImmT << 16);
136   V += Imm;                         // add the immediate offset
137   applyMOV(Off, V);           // set MOVW operand
138   applyMOV(Off + 4, V >> 16); // set MOVT operand
139 }
140 
141 static void applyBranch20T(uint8_t *Off, int32_t V) {
142   if (!isInt<21>(V))
143     fatal("relocation out of range");
144   uint32_t S = V < 0 ? 1 : 0;
145   uint32_t J1 = (V >> 19) & 1;
146   uint32_t J2 = (V >> 18) & 1;
147   or16(Off, (S << 10) | ((V >> 12) & 0x3f));
148   or16(Off + 2, (J1 << 13) | (J2 << 11) | ((V >> 1) & 0x7ff));
149 }
150 
151 void applyBranch24T(uint8_t *Off, int32_t V) {
152   if (!isInt<25>(V))
153     fatal("relocation out of range");
154   uint32_t S = V < 0 ? 1 : 0;
155   uint32_t J1 = ((~V >> 23) & 1) ^ S;
156   uint32_t J2 = ((~V >> 22) & 1) ^ S;
157   or16(Off, (S << 10) | ((V >> 12) & 0x3ff));
158   // Clear out the J1 and J2 bits which may be set.
159   write16le(Off + 2, (read16le(Off + 2) & 0xd000) | (J1 << 13) | (J2 << 11) | ((V >> 1) & 0x7ff));
160 }
161 
162 void SectionChunk::applyRelARM(uint8_t *Off, uint16_t Type, OutputSection *OS,
163                                uint64_t S, uint64_t P) const {
164   // Pointer to thumb code must have the LSB set.
165   uint64_t SX = S;
166   if (OS && (OS->getPermissions() & IMAGE_SCN_MEM_EXECUTE))
167     SX |= 1;
168   switch (Type) {
169   case IMAGE_REL_ARM_ADDR32:    add32(Off, SX + Config->ImageBase); break;
170   case IMAGE_REL_ARM_ADDR32NB:  add32(Off, SX); break;
171   case IMAGE_REL_ARM_MOV32T:    applyMOV32T(Off, SX + Config->ImageBase); break;
172   case IMAGE_REL_ARM_BRANCH20T: applyBranch20T(Off, SX - P - 4); break;
173   case IMAGE_REL_ARM_BRANCH24T: applyBranch24T(Off, SX - P - 4); break;
174   case IMAGE_REL_ARM_BLX23T:    applyBranch24T(Off, SX - P - 4); break;
175   case IMAGE_REL_ARM_SECTION:   applySecIdx(Off, OS); break;
176   case IMAGE_REL_ARM_SECREL:    applySecRel(this, Off, OS, S); break;
177   default:
178     fatal("unsupported relocation type 0x" + Twine::utohexstr(Type));
179   }
180 }
181 
182 // Interpret the existing immediate value as a byte offset to the
183 // target symbol, then update the instruction with the immediate as
184 // the page offset from the current instruction to the target.
185 static void applyArm64Addr(uint8_t *Off, uint64_t S, uint64_t P) {
186   uint32_t Orig = read32le(Off);
187   uint64_t Imm = ((Orig >> 29) & 0x3) | ((Orig >> 3) & 0x1FFFFC);
188   S += Imm;
189   Imm = (S >> 12) - (P >> 12);
190   uint32_t ImmLo = (Imm & 0x3) << 29;
191   uint32_t ImmHi = (Imm & 0x1FFFFC) << 3;
192   uint64_t Mask = (0x3 << 29) | (0x1FFFFC << 3);
193   write32le(Off, (Orig & ~Mask) | ImmLo | ImmHi);
194 }
195 
196 // Update the immediate field in a AARCH64 ldr, str, and add instruction.
197 // Optionally limit the range of the written immediate by one or more bits
198 // (RangeLimit).
199 static void applyArm64Imm(uint8_t *Off, uint64_t Imm, uint32_t RangeLimit) {
200   uint32_t Orig = read32le(Off);
201   Imm += (Orig >> 10) & 0xFFF;
202   Orig &= ~(0xFFF << 10);
203   write32le(Off, Orig | ((Imm & (0xFFF >> RangeLimit)) << 10));
204 }
205 
206 // Add the 12 bit page offset to the existing immediate.
207 // Ldr/str instructions store the opcode immediate scaled
208 // by the load/store size (giving a larger range for larger
209 // loads/stores). The immediate is always (both before and after
210 // fixing up the relocation) stored scaled similarly.
211 // Even if larger loads/stores have a larger range, limit the
212 // effective offset to 12 bit, since it is intended to be a
213 // page offset.
214 static void applyArm64Ldr(uint8_t *Off, uint64_t Imm) {
215   uint32_t Orig = read32le(Off);
216   uint32_t Size = Orig >> 30;
217   // 0x04000000 indicates SIMD/FP registers
218   // 0x00800000 indicates 128 bit
219   if ((Orig & 0x4800000) == 0x4800000)
220     Size += 4;
221   if ((Imm & ((1 << Size) - 1)) != 0)
222     fatal("misaligned ldr/str offset");
223   applyArm64Imm(Off, Imm >> Size, Size);
224 }
225 
226 static void applySecRelLow12A(const SectionChunk *Sec, uint8_t *Off,
227                               OutputSection *OS, uint64_t S) {
228   if (checkSecRel(Sec, OS))
229     applyArm64Imm(Off, (S - OS->getRVA()) & 0xfff, 0);
230 }
231 
232 static void applySecRelHigh12A(const SectionChunk *Sec, uint8_t *Off,
233                                OutputSection *OS, uint64_t S) {
234   if (!checkSecRel(Sec, OS))
235     return;
236   uint64_t SecRel = (S - OS->getRVA()) >> 12;
237   if (0xfff < SecRel) {
238     error("overflow in SECREL_HIGH12A relocation in section: " +
239           Sec->getSectionName());
240     return;
241   }
242   applyArm64Imm(Off, SecRel & 0xfff, 0);
243 }
244 
245 static void applySecRelLdr(const SectionChunk *Sec, uint8_t *Off,
246                            OutputSection *OS, uint64_t S) {
247   if (checkSecRel(Sec, OS))
248     applyArm64Ldr(Off, (S - OS->getRVA()) & 0xfff);
249 }
250 
251 void SectionChunk::applyRelARM64(uint8_t *Off, uint16_t Type, OutputSection *OS,
252                                  uint64_t S, uint64_t P) const {
253   switch (Type) {
254   case IMAGE_REL_ARM64_PAGEBASE_REL21: applyArm64Addr(Off, S, P); break;
255   case IMAGE_REL_ARM64_PAGEOFFSET_12A: applyArm64Imm(Off, S & 0xfff, 0); break;
256   case IMAGE_REL_ARM64_PAGEOFFSET_12L: applyArm64Ldr(Off, S & 0xfff); break;
257   case IMAGE_REL_ARM64_BRANCH26:       or32(Off, ((S - P) & 0x0FFFFFFC) >> 2); break;
258   case IMAGE_REL_ARM64_ADDR32:         add32(Off, S + Config->ImageBase); break;
259   case IMAGE_REL_ARM64_ADDR32NB:       add32(Off, S); break;
260   case IMAGE_REL_ARM64_ADDR64:         add64(Off, S + Config->ImageBase); break;
261   case IMAGE_REL_ARM64_SECREL:         applySecRel(this, Off, OS, S); break;
262   case IMAGE_REL_ARM64_SECREL_LOW12A:  applySecRelLow12A(this, Off, OS, S); break;
263   case IMAGE_REL_ARM64_SECREL_HIGH12A: applySecRelHigh12A(this, Off, OS, S); break;
264   case IMAGE_REL_ARM64_SECREL_LOW12L:  applySecRelLdr(this, Off, OS, S); break;
265   default:
266     fatal("unsupported relocation type 0x" + Twine::utohexstr(Type));
267   }
268 }
269 
270 void SectionChunk::writeTo(uint8_t *Buf) const {
271   if (!hasData())
272     return;
273   // Copy section contents from source object file to output file.
274   ArrayRef<uint8_t> A = getContents();
275   memcpy(Buf + OutputSectionOff, A.data(), A.size());
276 
277   // Apply relocations.
278   size_t InputSize = getSize();
279   for (const coff_relocation &Rel : Relocs) {
280     // Check for an invalid relocation offset. This check isn't perfect, because
281     // we don't have the relocation size, which is only known after checking the
282     // machine and relocation type. As a result, a relocation may overwrite the
283     // beginning of the following input section.
284     if (Rel.VirtualAddress >= InputSize)
285       fatal("relocation points beyond the end of its parent section");
286 
287     uint8_t *Off = Buf + OutputSectionOff + Rel.VirtualAddress;
288 
289     // Get the output section of the symbol for this relocation.  The output
290     // section is needed to compute SECREL and SECTION relocations used in debug
291     // info.
292     auto *Sym =
293         dyn_cast_or_null<Defined>(File->getSymbol(Rel.SymbolTableIndex));
294     if (!Sym) {
295       if (isCodeView() || isDWARF())
296         continue;
297       // Symbols in early discarded sections are represented using null pointers,
298       // so we need to retrieve the name from the object file.
299       COFFSymbolRef Sym =
300           check(File->getCOFFObj()->getSymbol(Rel.SymbolTableIndex));
301       StringRef Name;
302       File->getCOFFObj()->getSymbolName(Sym, Name);
303       fatal("relocation against symbol in discarded section: " + Name);
304     }
305     Chunk *C = Sym->getChunk();
306     OutputSection *OS = C ? C->getOutputSection() : nullptr;
307 
308     // Only absolute and __ImageBase symbols lack an output section. For any
309     // other symbol, this indicates that the chunk was discarded.  Normally
310     // relocations against discarded sections are an error.  However, debug info
311     // sections are not GC roots and can end up with these kinds of relocations.
312     // Skip these relocations.
313     if (!OS && !isa<DefinedAbsolute>(Sym) && !isa<DefinedSynthetic>(Sym)) {
314       if (isCodeView() || isDWARF())
315         continue;
316       fatal("relocation against symbol in discarded section: " +
317             Sym->getName());
318     }
319     uint64_t S = Sym->getRVA();
320 
321     // Compute the RVA of the relocation for relative relocations.
322     uint64_t P = RVA + Rel.VirtualAddress;
323     switch (Config->Machine) {
324     case AMD64:
325       applyRelX64(Off, Rel.Type, OS, S, P);
326       break;
327     case I386:
328       applyRelX86(Off, Rel.Type, OS, S, P);
329       break;
330     case ARMNT:
331       applyRelARM(Off, Rel.Type, OS, S, P);
332       break;
333     case ARM64:
334       applyRelARM64(Off, Rel.Type, OS, S, P);
335       break;
336     default:
337       llvm_unreachable("unknown machine type");
338     }
339   }
340 }
341 
342 void SectionChunk::addAssociative(SectionChunk *Child) {
343   AssocChildren.push_back(Child);
344 }
345 
346 static uint8_t getBaserelType(const coff_relocation &Rel) {
347   switch (Config->Machine) {
348   case AMD64:
349     if (Rel.Type == IMAGE_REL_AMD64_ADDR64)
350       return IMAGE_REL_BASED_DIR64;
351     return IMAGE_REL_BASED_ABSOLUTE;
352   case I386:
353     if (Rel.Type == IMAGE_REL_I386_DIR32)
354       return IMAGE_REL_BASED_HIGHLOW;
355     return IMAGE_REL_BASED_ABSOLUTE;
356   case ARMNT:
357     if (Rel.Type == IMAGE_REL_ARM_ADDR32)
358       return IMAGE_REL_BASED_HIGHLOW;
359     if (Rel.Type == IMAGE_REL_ARM_MOV32T)
360       return IMAGE_REL_BASED_ARM_MOV32T;
361     return IMAGE_REL_BASED_ABSOLUTE;
362   case ARM64:
363     if (Rel.Type == IMAGE_REL_ARM64_ADDR64)
364       return IMAGE_REL_BASED_DIR64;
365     return IMAGE_REL_BASED_ABSOLUTE;
366   default:
367     llvm_unreachable("unknown machine type");
368   }
369 }
370 
371 // Windows-specific.
372 // Collect all locations that contain absolute addresses, which need to be
373 // fixed by the loader if load-time relocation is needed.
374 // Only called when base relocation is enabled.
375 void SectionChunk::getBaserels(std::vector<Baserel> *Res) {
376   for (const coff_relocation &Rel : Relocs) {
377     uint8_t Ty = getBaserelType(Rel);
378     if (Ty == IMAGE_REL_BASED_ABSOLUTE)
379       continue;
380     Symbol *Target = File->getSymbol(Rel.SymbolTableIndex);
381     if (!Target || isa<DefinedAbsolute>(Target))
382       continue;
383     Res->emplace_back(RVA + Rel.VirtualAddress, Ty);
384   }
385 }
386 
387 bool SectionChunk::hasData() const {
388   return !(Header->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA);
389 }
390 
391 uint32_t SectionChunk::getPermissions() const {
392   return Header->Characteristics & PermMask;
393 }
394 
395 bool SectionChunk::isCOMDAT() const {
396   return Header->Characteristics & IMAGE_SCN_LNK_COMDAT;
397 }
398 
399 void SectionChunk::printDiscardedMessage() const {
400   // Removed by dead-stripping. If it's removed by ICF, ICF already
401   // printed out the name, so don't repeat that here.
402   if (Sym && this == Repl)
403     message("Discarded " + Sym->getName());
404 }
405 
406 StringRef SectionChunk::getDebugName() {
407   if (Sym)
408     return Sym->getName();
409   return "";
410 }
411 
412 ArrayRef<uint8_t> SectionChunk::getContents() const {
413   ArrayRef<uint8_t> A;
414   File->getCOFFObj()->getSectionContents(Header, A);
415   return A;
416 }
417 
418 void SectionChunk::replace(SectionChunk *Other) {
419   Other->Repl = Repl;
420   Other->Live = false;
421 }
422 
423 CommonChunk::CommonChunk(const COFFSymbolRef S) : Sym(S) {
424   // Common symbols are aligned on natural boundaries up to 32 bytes.
425   // This is what MSVC link.exe does.
426   Alignment = std::min(uint64_t(32), PowerOf2Ceil(Sym.getValue()));
427 }
428 
429 uint32_t CommonChunk::getPermissions() const {
430   return IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ |
431          IMAGE_SCN_MEM_WRITE;
432 }
433 
434 void StringChunk::writeTo(uint8_t *Buf) const {
435   memcpy(Buf + OutputSectionOff, Str.data(), Str.size());
436 }
437 
438 ImportThunkChunkX64::ImportThunkChunkX64(Defined *S) : ImpSymbol(S) {
439   // Intel Optimization Manual says that all branch targets
440   // should be 16-byte aligned. MSVC linker does this too.
441   Alignment = 16;
442 }
443 
444 void ImportThunkChunkX64::writeTo(uint8_t *Buf) const {
445   memcpy(Buf + OutputSectionOff, ImportThunkX86, sizeof(ImportThunkX86));
446   // The first two bytes is a JMP instruction. Fill its operand.
447   write32le(Buf + OutputSectionOff + 2, ImpSymbol->getRVA() - RVA - getSize());
448 }
449 
450 void ImportThunkChunkX86::getBaserels(std::vector<Baserel> *Res) {
451   Res->emplace_back(getRVA() + 2);
452 }
453 
454 void ImportThunkChunkX86::writeTo(uint8_t *Buf) const {
455   memcpy(Buf + OutputSectionOff, ImportThunkX86, sizeof(ImportThunkX86));
456   // The first two bytes is a JMP instruction. Fill its operand.
457   write32le(Buf + OutputSectionOff + 2,
458             ImpSymbol->getRVA() + Config->ImageBase);
459 }
460 
461 void ImportThunkChunkARM::getBaserels(std::vector<Baserel> *Res) {
462   Res->emplace_back(getRVA(), IMAGE_REL_BASED_ARM_MOV32T);
463 }
464 
465 void ImportThunkChunkARM::writeTo(uint8_t *Buf) const {
466   memcpy(Buf + OutputSectionOff, ImportThunkARM, sizeof(ImportThunkARM));
467   // Fix mov.w and mov.t operands.
468   applyMOV32T(Buf + OutputSectionOff, ImpSymbol->getRVA() + Config->ImageBase);
469 }
470 
471 void ImportThunkChunkARM64::writeTo(uint8_t *Buf) const {
472   int64_t Off = ImpSymbol->getRVA() & 0xfff;
473   memcpy(Buf + OutputSectionOff, ImportThunkARM64, sizeof(ImportThunkARM64));
474   applyArm64Addr(Buf + OutputSectionOff, ImpSymbol->getRVA(), RVA);
475   applyArm64Ldr(Buf + OutputSectionOff + 4, Off);
476 }
477 
478 void LocalImportChunk::getBaserels(std::vector<Baserel> *Res) {
479   Res->emplace_back(getRVA());
480 }
481 
482 size_t LocalImportChunk::getSize() const {
483   return Config->is64() ? 8 : 4;
484 }
485 
486 void LocalImportChunk::writeTo(uint8_t *Buf) const {
487   if (Config->is64()) {
488     write64le(Buf + OutputSectionOff, Sym->getRVA() + Config->ImageBase);
489   } else {
490     write32le(Buf + OutputSectionOff, Sym->getRVA() + Config->ImageBase);
491   }
492 }
493 
494 void RVATableChunk::writeTo(uint8_t *Buf) const {
495   ulittle32_t *Begin = reinterpret_cast<ulittle32_t *>(Buf + OutputSectionOff);
496   size_t Cnt = 0;
497   for (const ChunkAndOffset &CO : Syms)
498     Begin[Cnt++] = CO.InputChunk->getRVA() + CO.Offset;
499   std::sort(Begin, Begin + Cnt);
500   assert(std::unique(Begin, Begin + Cnt) == Begin + Cnt &&
501          "RVA tables should be de-duplicated");
502 }
503 
504 // Windows-specific. This class represents a block in .reloc section.
505 // The format is described here.
506 //
507 // On Windows, each DLL is linked against a fixed base address and
508 // usually loaded to that address. However, if there's already another
509 // DLL that overlaps, the loader has to relocate it. To do that, DLLs
510 // contain .reloc sections which contain offsets that need to be fixed
511 // up at runtime. If the loader finds that a DLL cannot be loaded to its
512 // desired base address, it loads it to somewhere else, and add <actual
513 // base address> - <desired base address> to each offset that is
514 // specified by the .reloc section. In ELF terms, .reloc sections
515 // contain relative relocations in REL format (as opposed to RELA.)
516 //
517 // This already significantly reduces the size of relocations compared
518 // to ELF .rel.dyn, but Windows does more to reduce it (probably because
519 // it was invented for PCs in the late '80s or early '90s.)  Offsets in
520 // .reloc are grouped by page where the page size is 12 bits, and
521 // offsets sharing the same page address are stored consecutively to
522 // represent them with less space. This is very similar to the page
523 // table which is grouped by (multiple stages of) pages.
524 //
525 // For example, let's say we have 0x00030, 0x00500, 0x00700, 0x00A00,
526 // 0x20004, and 0x20008 in a .reloc section for x64. The uppermost 4
527 // bits have a type IMAGE_REL_BASED_DIR64 or 0xA. In the section, they
528 // are represented like this:
529 //
530 //   0x00000  -- page address (4 bytes)
531 //   16       -- size of this block (4 bytes)
532 //     0xA030 -- entries (2 bytes each)
533 //     0xA500
534 //     0xA700
535 //     0xAA00
536 //   0x20000  -- page address (4 bytes)
537 //   12       -- size of this block (4 bytes)
538 //     0xA004 -- entries (2 bytes each)
539 //     0xA008
540 //
541 // Usually we have a lot of relocations for each page, so the number of
542 // bytes for one .reloc entry is close to 2 bytes on average.
543 BaserelChunk::BaserelChunk(uint32_t Page, Baserel *Begin, Baserel *End) {
544   // Block header consists of 4 byte page RVA and 4 byte block size.
545   // Each entry is 2 byte. Last entry may be padding.
546   Data.resize(alignTo((End - Begin) * 2 + 8, 4));
547   uint8_t *P = Data.data();
548   write32le(P, Page);
549   write32le(P + 4, Data.size());
550   P += 8;
551   for (Baserel *I = Begin; I != End; ++I) {
552     write16le(P, (I->Type << 12) | (I->RVA - Page));
553     P += 2;
554   }
555 }
556 
557 void BaserelChunk::writeTo(uint8_t *Buf) const {
558   memcpy(Buf + OutputSectionOff, Data.data(), Data.size());
559 }
560 
561 uint8_t Baserel::getDefaultType() {
562   switch (Config->Machine) {
563   case AMD64:
564   case ARM64:
565     return IMAGE_REL_BASED_DIR64;
566   case I386:
567   case ARMNT:
568     return IMAGE_REL_BASED_HIGHLOW;
569   default:
570     llvm_unreachable("unknown machine type");
571   }
572 }
573 
574 std::map<uint32_t, MergeChunk *> MergeChunk::Instances;
575 
576 MergeChunk::MergeChunk(uint32_t Alignment)
577     : Builder(StringTableBuilder::RAW, Alignment) {
578   this->Alignment = Alignment;
579 }
580 
581 void MergeChunk::addSection(SectionChunk *C) {
582   auto *&MC = Instances[C->Alignment];
583   if (!MC)
584     MC = make<MergeChunk>(C->Alignment);
585   MC->Sections.push_back(C);
586 }
587 
588 void MergeChunk::finalizeContents() {
589   for (SectionChunk *C : Sections)
590     if (C->isLive())
591       Builder.add(toStringRef(C->getContents()));
592   Builder.finalize();
593 
594   for (SectionChunk *C : Sections) {
595     if (!C->isLive())
596       continue;
597     size_t Off = Builder.getOffset(toStringRef(C->getContents()));
598     C->setOutputSection(Out);
599     C->setRVA(RVA + Off);
600     C->OutputSectionOff = OutputSectionOff + Off;
601   }
602 }
603 
604 uint32_t MergeChunk::getPermissions() const {
605   return IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA;
606 }
607 
608 size_t MergeChunk::getSize() const {
609   return Builder.getSize();
610 }
611 
612 void MergeChunk::writeTo(uint8_t *Buf) const {
613   Builder.write(Buf + OutputSectionOff);
614 }
615 
616 } // namespace coff
617 } // namespace lld
618