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