xref: /llvm-project-15.0.7/lld/COFF/Chunks.cpp (revision e3748b5a)
1 //===- Chunks.cpp ---------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "Chunks.h"
10 #include "InputFiles.h"
11 #include "Symbols.h"
12 #include "Writer.h"
13 #include "SymbolTable.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), File(F), Header(H), Repl(this) {
34   // Initialize Relocs.
35   setRelocs(File->getCOFFObj()->getRelocations(Header));
36 
37   // Initialize SectionName.
38   StringRef SectionName;
39   if (Expected<StringRef> E = File->getCOFFObj()->getSectionName(Header))
40     SectionName = *E;
41   SectionNameData = SectionName.data();
42   SectionNameSize = SectionName.size();
43 
44   setAlignment(Header->getAlignment());
45 
46   // If linker GC is disabled, every chunk starts out alive.  If linker GC is
47   // enabled, treat non-comdat sections as roots. Generally optimized object
48   // files will be built with -ffunction-sections or /Gy, so most things worth
49   // stripping will be in a comdat.
50   Live = !Config->DoGC || !isCOMDAT();
51 }
52 
53 // SectionChunk is one of the most frequently allocated classes, so it is
54 // important to keep it as compact as possible. As of this writing, the number
55 // below is the size of this class on x64 platforms.
56 static_assert(sizeof(SectionChunk) <= 104, "SectionChunk grew unexpectedly");
57 
58 static void add16(uint8_t *P, int16_t V) { write16le(P, read16le(P) + V); }
59 static void add32(uint8_t *P, int32_t V) { write32le(P, read32le(P) + V); }
60 static void add64(uint8_t *P, int64_t V) { write64le(P, read64le(P) + V); }
61 static void or16(uint8_t *P, uint16_t V) { write16le(P, read16le(P) | V); }
62 static void or32(uint8_t *P, uint32_t V) { write32le(P, read32le(P) | V); }
63 
64 // Verify that given sections are appropriate targets for SECREL
65 // relocations. This check is relaxed because unfortunately debug
66 // sections have section-relative relocations against absolute symbols.
67 static bool checkSecRel(const SectionChunk *Sec, OutputSection *OS) {
68   if (OS)
69     return true;
70   if (Sec->isCodeView())
71     return false;
72   error("SECREL relocation cannot be applied to absolute symbols");
73   return false;
74 }
75 
76 static void applySecRel(const SectionChunk *Sec, uint8_t *Off,
77                         OutputSection *OS, uint64_t S) {
78   if (!checkSecRel(Sec, OS))
79     return;
80   uint64_t SecRel = S - OS->getRVA();
81   if (SecRel > UINT32_MAX) {
82     error("overflow in SECREL relocation in section: " + Sec->getSectionName());
83     return;
84   }
85   add32(Off, SecRel);
86 }
87 
88 static void applySecIdx(uint8_t *Off, OutputSection *OS) {
89   // Absolute symbol doesn't have section index, but section index relocation
90   // against absolute symbol should be resolved to one plus the last output
91   // section index. This is required for compatibility with MSVC.
92   if (OS)
93     add16(Off, OS->SectionIndex);
94   else
95     add16(Off, DefinedAbsolute::NumOutputSections + 1);
96 }
97 
98 void SectionChunk::applyRelX64(uint8_t *Off, uint16_t Type, OutputSection *OS,
99                                uint64_t S, uint64_t P) const {
100   switch (Type) {
101   case IMAGE_REL_AMD64_ADDR32:   add32(Off, S + Config->ImageBase); break;
102   case IMAGE_REL_AMD64_ADDR64:   add64(Off, S + Config->ImageBase); break;
103   case IMAGE_REL_AMD64_ADDR32NB: add32(Off, S); break;
104   case IMAGE_REL_AMD64_REL32:    add32(Off, S - P - 4); break;
105   case IMAGE_REL_AMD64_REL32_1:  add32(Off, S - P - 5); break;
106   case IMAGE_REL_AMD64_REL32_2:  add32(Off, S - P - 6); break;
107   case IMAGE_REL_AMD64_REL32_3:  add32(Off, S - P - 7); break;
108   case IMAGE_REL_AMD64_REL32_4:  add32(Off, S - P - 8); break;
109   case IMAGE_REL_AMD64_REL32_5:  add32(Off, S - P - 9); break;
110   case IMAGE_REL_AMD64_SECTION:  applySecIdx(Off, OS); break;
111   case IMAGE_REL_AMD64_SECREL:   applySecRel(this, Off, OS, S); break;
112   default:
113     error("unsupported relocation type 0x" + Twine::utohexstr(Type) + " in " +
114           toString(File));
115   }
116 }
117 
118 void SectionChunk::applyRelX86(uint8_t *Off, uint16_t Type, OutputSection *OS,
119                                uint64_t S, uint64_t P) const {
120   switch (Type) {
121   case IMAGE_REL_I386_ABSOLUTE: break;
122   case IMAGE_REL_I386_DIR32:    add32(Off, S + Config->ImageBase); break;
123   case IMAGE_REL_I386_DIR32NB:  add32(Off, S); break;
124   case IMAGE_REL_I386_REL32:    add32(Off, S - P - 4); break;
125   case IMAGE_REL_I386_SECTION:  applySecIdx(Off, OS); break;
126   case IMAGE_REL_I386_SECREL:   applySecRel(this, Off, OS, S); break;
127   default:
128     error("unsupported relocation type 0x" + Twine::utohexstr(Type) + " in " +
129           toString(File));
130   }
131 }
132 
133 static void applyMOV(uint8_t *Off, uint16_t V) {
134   write16le(Off, (read16le(Off) & 0xfbf0) | ((V & 0x800) >> 1) | ((V >> 12) & 0xf));
135   write16le(Off + 2, (read16le(Off + 2) & 0x8f00) | ((V & 0x700) << 4) | (V & 0xff));
136 }
137 
138 static uint16_t readMOV(uint8_t *Off, bool MOVT) {
139   uint16_t Op1 = read16le(Off);
140   if ((Op1 & 0xfbf0) != (MOVT ? 0xf2c0 : 0xf240))
141     error("unexpected instruction in " + Twine(MOVT ? "MOVT" : "MOVW") +
142           " instruction in MOV32T relocation");
143   uint16_t Op2 = read16le(Off + 2);
144   if ((Op2 & 0x8000) != 0)
145     error("unexpected instruction in " + Twine(MOVT ? "MOVT" : "MOVW") +
146           " instruction in MOV32T relocation");
147   return (Op2 & 0x00ff) | ((Op2 >> 4) & 0x0700) | ((Op1 << 1) & 0x0800) |
148          ((Op1 & 0x000f) << 12);
149 }
150 
151 void applyMOV32T(uint8_t *Off, uint32_t V) {
152   uint16_t ImmW = readMOV(Off, false);    // read MOVW operand
153   uint16_t ImmT = readMOV(Off + 4, true); // read MOVT operand
154   uint32_t Imm = ImmW | (ImmT << 16);
155   V += Imm;                         // add the immediate offset
156   applyMOV(Off, V);           // set MOVW operand
157   applyMOV(Off + 4, V >> 16); // set MOVT operand
158 }
159 
160 static void applyBranch20T(uint8_t *Off, int32_t V) {
161   if (!isInt<21>(V))
162     error("relocation out of range");
163   uint32_t S = V < 0 ? 1 : 0;
164   uint32_t J1 = (V >> 19) & 1;
165   uint32_t J2 = (V >> 18) & 1;
166   or16(Off, (S << 10) | ((V >> 12) & 0x3f));
167   or16(Off + 2, (J1 << 13) | (J2 << 11) | ((V >> 1) & 0x7ff));
168 }
169 
170 void applyBranch24T(uint8_t *Off, int32_t V) {
171   if (!isInt<25>(V))
172     error("relocation out of range");
173   uint32_t S = V < 0 ? 1 : 0;
174   uint32_t J1 = ((~V >> 23) & 1) ^ S;
175   uint32_t J2 = ((~V >> 22) & 1) ^ S;
176   or16(Off, (S << 10) | ((V >> 12) & 0x3ff));
177   // Clear out the J1 and J2 bits which may be set.
178   write16le(Off + 2, (read16le(Off + 2) & 0xd000) | (J1 << 13) | (J2 << 11) | ((V >> 1) & 0x7ff));
179 }
180 
181 void SectionChunk::applyRelARM(uint8_t *Off, uint16_t Type, OutputSection *OS,
182                                uint64_t S, uint64_t P) const {
183   // Pointer to thumb code must have the LSB set.
184   uint64_t SX = S;
185   if (OS && (OS->Header.Characteristics & IMAGE_SCN_MEM_EXECUTE))
186     SX |= 1;
187   switch (Type) {
188   case IMAGE_REL_ARM_ADDR32:    add32(Off, SX + Config->ImageBase); break;
189   case IMAGE_REL_ARM_ADDR32NB:  add32(Off, SX); break;
190   case IMAGE_REL_ARM_MOV32T:    applyMOV32T(Off, SX + Config->ImageBase); break;
191   case IMAGE_REL_ARM_BRANCH20T: applyBranch20T(Off, SX - P - 4); break;
192   case IMAGE_REL_ARM_BRANCH24T: applyBranch24T(Off, SX - P - 4); break;
193   case IMAGE_REL_ARM_BLX23T:    applyBranch24T(Off, SX - P - 4); break;
194   case IMAGE_REL_ARM_SECTION:   applySecIdx(Off, OS); break;
195   case IMAGE_REL_ARM_SECREL:    applySecRel(this, Off, OS, S); break;
196   case IMAGE_REL_ARM_REL32:     add32(Off, SX - P - 4); break;
197   default:
198     error("unsupported relocation type 0x" + Twine::utohexstr(Type) + " in " +
199           toString(File));
200   }
201 }
202 
203 // Interpret the existing immediate value as a byte offset to the
204 // target symbol, then update the instruction with the immediate as
205 // the page offset from the current instruction to the target.
206 void applyArm64Addr(uint8_t *Off, uint64_t S, uint64_t P, int Shift) {
207   uint32_t Orig = read32le(Off);
208   uint64_t Imm = ((Orig >> 29) & 0x3) | ((Orig >> 3) & 0x1FFFFC);
209   S += Imm;
210   Imm = (S >> Shift) - (P >> Shift);
211   uint32_t ImmLo = (Imm & 0x3) << 29;
212   uint32_t ImmHi = (Imm & 0x1FFFFC) << 3;
213   uint64_t Mask = (0x3 << 29) | (0x1FFFFC << 3);
214   write32le(Off, (Orig & ~Mask) | ImmLo | ImmHi);
215 }
216 
217 // Update the immediate field in a AARCH64 ldr, str, and add instruction.
218 // Optionally limit the range of the written immediate by one or more bits
219 // (RangeLimit).
220 void applyArm64Imm(uint8_t *Off, uint64_t Imm, uint32_t RangeLimit) {
221   uint32_t Orig = read32le(Off);
222   Imm += (Orig >> 10) & 0xFFF;
223   Orig &= ~(0xFFF << 10);
224   write32le(Off, Orig | ((Imm & (0xFFF >> RangeLimit)) << 10));
225 }
226 
227 // Add the 12 bit page offset to the existing immediate.
228 // Ldr/str instructions store the opcode immediate scaled
229 // by the load/store size (giving a larger range for larger
230 // loads/stores). The immediate is always (both before and after
231 // fixing up the relocation) stored scaled similarly.
232 // Even if larger loads/stores have a larger range, limit the
233 // effective offset to 12 bit, since it is intended to be a
234 // page offset.
235 static void applyArm64Ldr(uint8_t *Off, uint64_t Imm) {
236   uint32_t Orig = read32le(Off);
237   uint32_t Size = Orig >> 30;
238   // 0x04000000 indicates SIMD/FP registers
239   // 0x00800000 indicates 128 bit
240   if ((Orig & 0x4800000) == 0x4800000)
241     Size += 4;
242   if ((Imm & ((1 << Size) - 1)) != 0)
243     error("misaligned ldr/str offset");
244   applyArm64Imm(Off, Imm >> Size, Size);
245 }
246 
247 static void applySecRelLow12A(const SectionChunk *Sec, uint8_t *Off,
248                               OutputSection *OS, uint64_t S) {
249   if (checkSecRel(Sec, OS))
250     applyArm64Imm(Off, (S - OS->getRVA()) & 0xfff, 0);
251 }
252 
253 static void applySecRelHigh12A(const SectionChunk *Sec, uint8_t *Off,
254                                OutputSection *OS, uint64_t S) {
255   if (!checkSecRel(Sec, OS))
256     return;
257   uint64_t SecRel = (S - OS->getRVA()) >> 12;
258   if (0xfff < SecRel) {
259     error("overflow in SECREL_HIGH12A relocation in section: " +
260           Sec->getSectionName());
261     return;
262   }
263   applyArm64Imm(Off, SecRel & 0xfff, 0);
264 }
265 
266 static void applySecRelLdr(const SectionChunk *Sec, uint8_t *Off,
267                            OutputSection *OS, uint64_t S) {
268   if (checkSecRel(Sec, OS))
269     applyArm64Ldr(Off, (S - OS->getRVA()) & 0xfff);
270 }
271 
272 void applyArm64Branch26(uint8_t *Off, int64_t V) {
273   if (!isInt<28>(V))
274     error("relocation out of range");
275   or32(Off, (V & 0x0FFFFFFC) >> 2);
276 }
277 
278 static void applyArm64Branch19(uint8_t *Off, int64_t V) {
279   if (!isInt<21>(V))
280     error("relocation out of range");
281   or32(Off, (V & 0x001FFFFC) << 3);
282 }
283 
284 static void applyArm64Branch14(uint8_t *Off, int64_t V) {
285   if (!isInt<16>(V))
286     error("relocation out of range");
287   or32(Off, (V & 0x0000FFFC) << 3);
288 }
289 
290 void SectionChunk::applyRelARM64(uint8_t *Off, uint16_t Type, OutputSection *OS,
291                                  uint64_t S, uint64_t P) const {
292   switch (Type) {
293   case IMAGE_REL_ARM64_PAGEBASE_REL21: applyArm64Addr(Off, S, P, 12); break;
294   case IMAGE_REL_ARM64_REL21:          applyArm64Addr(Off, S, P, 0); break;
295   case IMAGE_REL_ARM64_PAGEOFFSET_12A: applyArm64Imm(Off, S & 0xfff, 0); break;
296   case IMAGE_REL_ARM64_PAGEOFFSET_12L: applyArm64Ldr(Off, S & 0xfff); break;
297   case IMAGE_REL_ARM64_BRANCH26:       applyArm64Branch26(Off, S - P); break;
298   case IMAGE_REL_ARM64_BRANCH19:       applyArm64Branch19(Off, S - P); break;
299   case IMAGE_REL_ARM64_BRANCH14:       applyArm64Branch14(Off, S - P); break;
300   case IMAGE_REL_ARM64_ADDR32:         add32(Off, S + Config->ImageBase); break;
301   case IMAGE_REL_ARM64_ADDR32NB:       add32(Off, S); break;
302   case IMAGE_REL_ARM64_ADDR64:         add64(Off, S + Config->ImageBase); break;
303   case IMAGE_REL_ARM64_SECREL:         applySecRel(this, Off, OS, S); break;
304   case IMAGE_REL_ARM64_SECREL_LOW12A:  applySecRelLow12A(this, Off, OS, S); break;
305   case IMAGE_REL_ARM64_SECREL_HIGH12A: applySecRelHigh12A(this, Off, OS, S); break;
306   case IMAGE_REL_ARM64_SECREL_LOW12L:  applySecRelLdr(this, Off, OS, S); break;
307   case IMAGE_REL_ARM64_SECTION:        applySecIdx(Off, OS); break;
308   case IMAGE_REL_ARM64_REL32:          add32(Off, S - P - 4); break;
309   default:
310     error("unsupported relocation type 0x" + Twine::utohexstr(Type) + " in " +
311           toString(File));
312   }
313 }
314 
315 static void maybeReportRelocationToDiscarded(const SectionChunk *FromChunk,
316                                              Defined *Sym,
317                                              const coff_relocation &Rel) {
318   // Don't report these errors when the relocation comes from a debug info
319   // section or in mingw mode. MinGW mode object files (built by GCC) can
320   // have leftover sections with relocations against discarded comdat
321   // sections. Such sections are left as is, with relocations untouched.
322   if (FromChunk->isCodeView() || FromChunk->isDWARF() || Config->MinGW)
323     return;
324 
325   // Get the name of the symbol. If it's null, it was discarded early, so we
326   // have to go back to the object file.
327   ObjFile *File = FromChunk->File;
328   StringRef Name;
329   if (Sym) {
330     Name = Sym->getName();
331   } else {
332     COFFSymbolRef COFFSym =
333         check(File->getCOFFObj()->getSymbol(Rel.SymbolTableIndex));
334     File->getCOFFObj()->getSymbolName(COFFSym, Name);
335   }
336 
337   error("relocation against symbol in discarded section: " + Name +
338         getSymbolLocations(File, Rel.SymbolTableIndex));
339 }
340 
341 void SectionChunk::writeTo(uint8_t *Buf) const {
342   if (!hasData())
343     return;
344   // Copy section contents from source object file to output file.
345   ArrayRef<uint8_t> A = getContents();
346   if (!A.empty())
347     memcpy(Buf, A.data(), A.size());
348 
349   // Apply relocations.
350   size_t InputSize = getSize();
351   for (size_t I = 0, E = RelocsSize; I < E; I++) {
352     const coff_relocation &Rel = RelocsData[I];
353 
354     // Check for an invalid relocation offset. This check isn't perfect, because
355     // we don't have the relocation size, which is only known after checking the
356     // machine and relocation type. As a result, a relocation may overwrite the
357     // beginning of the following input section.
358     if (Rel.VirtualAddress >= InputSize) {
359       error("relocation points beyond the end of its parent section");
360       continue;
361     }
362 
363     uint8_t *Off = Buf + Rel.VirtualAddress;
364 
365     auto *Sym =
366         dyn_cast_or_null<Defined>(File->getSymbol(Rel.SymbolTableIndex));
367 
368     // Get the output section of the symbol for this relocation.  The output
369     // section is needed to compute SECREL and SECTION relocations used in debug
370     // info.
371     Chunk *C = Sym ? Sym->getChunk() : nullptr;
372     OutputSection *OS = C ? C->getOutputSection() : nullptr;
373 
374     // Skip the relocation if it refers to a discarded section, and diagnose it
375     // as an error if appropriate. If a symbol was discarded early, it may be
376     // null. If it was discarded late, the output section will be null, unless
377     // it was an absolute or synthetic symbol.
378     if (!Sym ||
379         (!OS && !isa<DefinedAbsolute>(Sym) && !isa<DefinedSynthetic>(Sym))) {
380       maybeReportRelocationToDiscarded(this, Sym, Rel);
381       continue;
382     }
383 
384     uint64_t S = Sym->getRVA();
385 
386     // Compute the RVA of the relocation for relative relocations.
387     uint64_t P = RVA + Rel.VirtualAddress;
388     switch (Config->Machine) {
389     case AMD64:
390       applyRelX64(Off, Rel.Type, OS, S, P);
391       break;
392     case I386:
393       applyRelX86(Off, Rel.Type, OS, S, P);
394       break;
395     case ARMNT:
396       applyRelARM(Off, Rel.Type, OS, S, P);
397       break;
398     case ARM64:
399       applyRelARM64(Off, Rel.Type, OS, S, P);
400       break;
401     default:
402       llvm_unreachable("unknown machine type");
403     }
404   }
405 }
406 
407 void SectionChunk::addAssociative(SectionChunk *Child) {
408   // Insert this child at the head of the list.
409   assert(Child->AssocChildren == nullptr &&
410          "associated sections cannot have their own associated children");
411   Child->AssocChildren = AssocChildren;
412   AssocChildren = Child;
413 }
414 
415 static uint8_t getBaserelType(const coff_relocation &Rel) {
416   switch (Config->Machine) {
417   case AMD64:
418     if (Rel.Type == IMAGE_REL_AMD64_ADDR64)
419       return IMAGE_REL_BASED_DIR64;
420     return IMAGE_REL_BASED_ABSOLUTE;
421   case I386:
422     if (Rel.Type == IMAGE_REL_I386_DIR32)
423       return IMAGE_REL_BASED_HIGHLOW;
424     return IMAGE_REL_BASED_ABSOLUTE;
425   case ARMNT:
426     if (Rel.Type == IMAGE_REL_ARM_ADDR32)
427       return IMAGE_REL_BASED_HIGHLOW;
428     if (Rel.Type == IMAGE_REL_ARM_MOV32T)
429       return IMAGE_REL_BASED_ARM_MOV32T;
430     return IMAGE_REL_BASED_ABSOLUTE;
431   case ARM64:
432     if (Rel.Type == IMAGE_REL_ARM64_ADDR64)
433       return IMAGE_REL_BASED_DIR64;
434     return IMAGE_REL_BASED_ABSOLUTE;
435   default:
436     llvm_unreachable("unknown machine type");
437   }
438 }
439 
440 // Windows-specific.
441 // Collect all locations that contain absolute addresses, which need to be
442 // fixed by the loader if load-time relocation is needed.
443 // Only called when base relocation is enabled.
444 void SectionChunk::getBaserels(std::vector<Baserel> *Res) {
445   for (size_t I = 0, E = RelocsSize; I < E; I++) {
446     const coff_relocation &Rel = RelocsData[I];
447     uint8_t Ty = getBaserelType(Rel);
448     if (Ty == IMAGE_REL_BASED_ABSOLUTE)
449       continue;
450     Symbol *Target = File->getSymbol(Rel.SymbolTableIndex);
451     if (!Target || isa<DefinedAbsolute>(Target))
452       continue;
453     Res->emplace_back(RVA + Rel.VirtualAddress, Ty);
454   }
455 }
456 
457 // MinGW specific.
458 // Check whether a static relocation of type Type can be deferred and
459 // handled at runtime as a pseudo relocation (for references to a module
460 // local variable, which turned out to actually need to be imported from
461 // another DLL) This returns the size the relocation is supposed to update,
462 // in bits, or 0 if the relocation cannot be handled as a runtime pseudo
463 // relocation.
464 static int getRuntimePseudoRelocSize(uint16_t Type) {
465   // Relocations that either contain an absolute address, or a plain
466   // relative offset, since the runtime pseudo reloc implementation
467   // adds 8/16/32/64 bit values to a memory address.
468   //
469   // Given a pseudo relocation entry,
470   //
471   // typedef struct {
472   //   DWORD sym;
473   //   DWORD target;
474   //   DWORD flags;
475   // } runtime_pseudo_reloc_item_v2;
476   //
477   // the runtime relocation performs this adjustment:
478   //     *(base + .target) += *(base + .sym) - (base + .sym)
479   //
480   // This works for both absolute addresses (IMAGE_REL_*_ADDR32/64,
481   // IMAGE_REL_I386_DIR32, where the memory location initially contains
482   // the address of the IAT slot, and for relative addresses (IMAGE_REL*_REL32),
483   // where the memory location originally contains the relative offset to the
484   // IAT slot.
485   //
486   // This requires the target address to be writable, either directly out of
487   // the image, or temporarily changed at runtime with VirtualProtect.
488   // Since this only operates on direct address values, it doesn't work for
489   // ARM/ARM64 relocations, other than the plain ADDR32/ADDR64 relocations.
490   switch (Config->Machine) {
491   case AMD64:
492     switch (Type) {
493     case IMAGE_REL_AMD64_ADDR64:
494       return 64;
495     case IMAGE_REL_AMD64_ADDR32:
496     case IMAGE_REL_AMD64_REL32:
497     case IMAGE_REL_AMD64_REL32_1:
498     case IMAGE_REL_AMD64_REL32_2:
499     case IMAGE_REL_AMD64_REL32_3:
500     case IMAGE_REL_AMD64_REL32_4:
501     case IMAGE_REL_AMD64_REL32_5:
502       return 32;
503     default:
504       return 0;
505     }
506   case I386:
507     switch (Type) {
508     case IMAGE_REL_I386_DIR32:
509     case IMAGE_REL_I386_REL32:
510       return 32;
511     default:
512       return 0;
513     }
514   case ARMNT:
515     switch (Type) {
516     case IMAGE_REL_ARM_ADDR32:
517       return 32;
518     default:
519       return 0;
520     }
521   case ARM64:
522     switch (Type) {
523     case IMAGE_REL_ARM64_ADDR64:
524       return 64;
525     case IMAGE_REL_ARM64_ADDR32:
526       return 32;
527     default:
528       return 0;
529     }
530   default:
531     llvm_unreachable("unknown machine type");
532   }
533 }
534 
535 // MinGW specific.
536 // Append information to the provided vector about all relocations that
537 // need to be handled at runtime as runtime pseudo relocations (references
538 // to a module local variable, which turned out to actually need to be
539 // imported from another DLL).
540 void SectionChunk::getRuntimePseudoRelocs(
541     std::vector<RuntimePseudoReloc> &Res) {
542   for (const coff_relocation &Rel : getRelocs()) {
543     auto *Target =
544         dyn_cast_or_null<Defined>(File->getSymbol(Rel.SymbolTableIndex));
545     if (!Target || !Target->IsRuntimePseudoReloc)
546       continue;
547     int SizeInBits = getRuntimePseudoRelocSize(Rel.Type);
548     if (SizeInBits == 0) {
549       error("unable to automatically import from " + Target->getName() +
550             " with relocation type " +
551             File->getCOFFObj()->getRelocationTypeName(Rel.Type) + " in " +
552             toString(File));
553       continue;
554     }
555     // SizeInBits is used to initialize the Flags field; currently no
556     // other flags are defined.
557     Res.emplace_back(
558         RuntimePseudoReloc(Target, this, Rel.VirtualAddress, SizeInBits));
559   }
560 }
561 
562 bool SectionChunk::hasData() const {
563   return !(Header->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA);
564 }
565 
566 uint32_t SectionChunk::getOutputCharacteristics() const {
567   return Header->Characteristics & (PermMask | TypeMask);
568 }
569 
570 bool SectionChunk::isCOMDAT() const {
571   return Header->Characteristics & IMAGE_SCN_LNK_COMDAT;
572 }
573 
574 void SectionChunk::printDiscardedMessage() const {
575   // Removed by dead-stripping. If it's removed by ICF, ICF already
576   // printed out the name, so don't repeat that here.
577   if (Sym && this == Repl)
578     message("Discarded " + Sym->getName());
579 }
580 
581 StringRef SectionChunk::getDebugName() {
582   if (Sym)
583     return Sym->getName();
584   return "";
585 }
586 
587 ArrayRef<uint8_t> SectionChunk::getContents() const {
588   ArrayRef<uint8_t> A;
589   cantFail(File->getCOFFObj()->getSectionContents(Header, A));
590   return A;
591 }
592 
593 ArrayRef<uint8_t> SectionChunk::consumeDebugMagic() {
594   assert(isCodeView());
595   return consumeDebugMagic(getContents(), getSectionName());
596 }
597 
598 ArrayRef<uint8_t> SectionChunk::consumeDebugMagic(ArrayRef<uint8_t> Data,
599                                                   StringRef SectionName) {
600   if (Data.empty())
601     return {};
602 
603   // First 4 bytes are section magic.
604   if (Data.size() < 4)
605     fatal("the section is too short: " + SectionName);
606 
607   if (!SectionName.startswith(".debug$"))
608     fatal("invalid section: " + SectionName);
609 
610   unsigned Magic = support::endian::read32le(Data.data());
611   unsigned ExpectedMagic = SectionName == ".debug$H"
612                                ? DEBUG_HASHES_SECTION_MAGIC
613                                : DEBUG_SECTION_MAGIC;
614   if (Magic != ExpectedMagic)
615     fatal("section: " + SectionName + " has an invalid magic: " + Twine(Magic));
616   return Data.slice(4);
617 }
618 
619 SectionChunk *SectionChunk::findByName(ArrayRef<SectionChunk *> Sections,
620                                        StringRef Name) {
621   for (SectionChunk *C : Sections)
622     if (C->getSectionName() == Name)
623       return C;
624   return nullptr;
625 }
626 
627 void SectionChunk::replace(SectionChunk *Other) {
628   P2Align = std::max(P2Align, Other->P2Align);
629   Other->Repl = Repl;
630   Other->Live = false;
631 }
632 
633 uint32_t SectionChunk::getSectionNumber() const {
634   DataRefImpl R;
635   R.p = reinterpret_cast<uintptr_t>(Header);
636   SectionRef S(R, File->getCOFFObj());
637   return S.getIndex() + 1;
638 }
639 
640 CommonChunk::CommonChunk(const COFFSymbolRef S) : Sym(S) {
641   // The value of a common symbol is its size. Align all common symbols smaller
642   // than 32 bytes naturally, i.e. round the size up to the next power of two.
643   // This is what MSVC link.exe does.
644   setAlignment(std::min(32U, uint32_t(PowerOf2Ceil(Sym.getValue()))));
645 }
646 
647 uint32_t CommonChunk::getOutputCharacteristics() const {
648   return IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ |
649          IMAGE_SCN_MEM_WRITE;
650 }
651 
652 void StringChunk::writeTo(uint8_t *Buf) const {
653   memcpy(Buf, Str.data(), Str.size());
654   Buf[Str.size()] = '\0';
655 }
656 
657 ImportThunkChunkX64::ImportThunkChunkX64(Defined *S) : ImpSymbol(S) {
658   // Intel Optimization Manual says that all branch targets
659   // should be 16-byte aligned. MSVC linker does this too.
660   setAlignment(16);
661 }
662 
663 void ImportThunkChunkX64::writeTo(uint8_t *Buf) const {
664   memcpy(Buf, ImportThunkX86, sizeof(ImportThunkX86));
665   // The first two bytes is a JMP instruction. Fill its operand.
666   write32le(Buf + 2, ImpSymbol->getRVA() - RVA - getSize());
667 }
668 
669 void ImportThunkChunkX86::getBaserels(std::vector<Baserel> *Res) {
670   Res->emplace_back(getRVA() + 2);
671 }
672 
673 void ImportThunkChunkX86::writeTo(uint8_t *Buf) const {
674   memcpy(Buf, ImportThunkX86, sizeof(ImportThunkX86));
675   // The first two bytes is a JMP instruction. Fill its operand.
676   write32le(Buf + 2,
677             ImpSymbol->getRVA() + Config->ImageBase);
678 }
679 
680 void ImportThunkChunkARM::getBaserels(std::vector<Baserel> *Res) {
681   Res->emplace_back(getRVA(), IMAGE_REL_BASED_ARM_MOV32T);
682 }
683 
684 void ImportThunkChunkARM::writeTo(uint8_t *Buf) const {
685   memcpy(Buf, ImportThunkARM, sizeof(ImportThunkARM));
686   // Fix mov.w and mov.t operands.
687   applyMOV32T(Buf, ImpSymbol->getRVA() + Config->ImageBase);
688 }
689 
690 void ImportThunkChunkARM64::writeTo(uint8_t *Buf) const {
691   int64_t Off = ImpSymbol->getRVA() & 0xfff;
692   memcpy(Buf, ImportThunkARM64, sizeof(ImportThunkARM64));
693   applyArm64Addr(Buf, ImpSymbol->getRVA(), RVA, 12);
694   applyArm64Ldr(Buf + 4, Off);
695 }
696 
697 // A Thumb2, PIC, non-interworking range extension thunk.
698 const uint8_t ArmThunk[] = {
699     0x40, 0xf2, 0x00, 0x0c, // P:  movw ip,:lower16:S - (P + (L1-P) + 4)
700     0xc0, 0xf2, 0x00, 0x0c, //     movt ip,:upper16:S - (P + (L1-P) + 4)
701     0xe7, 0x44,             // L1: add  pc, ip
702 };
703 
704 size_t RangeExtensionThunkARM::getSize() const {
705   assert(Config->Machine == ARMNT);
706   return sizeof(ArmThunk);
707 }
708 
709 void RangeExtensionThunkARM::writeTo(uint8_t *Buf) const {
710   assert(Config->Machine == ARMNT);
711   uint64_t Offset = Target->getRVA() - RVA - 12;
712   memcpy(Buf, ArmThunk, sizeof(ArmThunk));
713   applyMOV32T(Buf, uint32_t(Offset));
714 }
715 
716 // A position independent ARM64 adrp+add thunk, with a maximum range of
717 // +/- 4 GB, which is enough for any PE-COFF.
718 const uint8_t Arm64Thunk[] = {
719     0x10, 0x00, 0x00, 0x90, // adrp x16, Dest
720     0x10, 0x02, 0x00, 0x91, // add  x16, x16, :lo12:Dest
721     0x00, 0x02, 0x1f, 0xd6, // br   x16
722 };
723 
724 size_t RangeExtensionThunkARM64::getSize() const {
725   assert(Config->Machine == ARM64);
726   return sizeof(Arm64Thunk);
727 }
728 
729 void RangeExtensionThunkARM64::writeTo(uint8_t *Buf) const {
730   assert(Config->Machine == ARM64);
731   memcpy(Buf, Arm64Thunk, sizeof(Arm64Thunk));
732   applyArm64Addr(Buf + 0, Target->getRVA(), RVA, 12);
733   applyArm64Imm(Buf + 4, Target->getRVA() & 0xfff, 0);
734 }
735 
736 void LocalImportChunk::getBaserels(std::vector<Baserel> *Res) {
737   Res->emplace_back(getRVA());
738 }
739 
740 size_t LocalImportChunk::getSize() const { return Config->Wordsize; }
741 
742 void LocalImportChunk::writeTo(uint8_t *Buf) const {
743   if (Config->is64()) {
744     write64le(Buf, Sym->getRVA() + Config->ImageBase);
745   } else {
746     write32le(Buf, Sym->getRVA() + Config->ImageBase);
747   }
748 }
749 
750 void RVATableChunk::writeTo(uint8_t *Buf) const {
751   ulittle32_t *Begin = reinterpret_cast<ulittle32_t *>(Buf);
752   size_t Cnt = 0;
753   for (const ChunkAndOffset &CO : Syms)
754     Begin[Cnt++] = CO.InputChunk->getRVA() + CO.Offset;
755   std::sort(Begin, Begin + Cnt);
756   assert(std::unique(Begin, Begin + Cnt) == Begin + Cnt &&
757          "RVA tables should be de-duplicated");
758 }
759 
760 // MinGW specific, for the "automatic import of variables from DLLs" feature.
761 size_t PseudoRelocTableChunk::getSize() const {
762   if (Relocs.empty())
763     return 0;
764   return 12 + 12 * Relocs.size();
765 }
766 
767 // MinGW specific.
768 void PseudoRelocTableChunk::writeTo(uint8_t *Buf) const {
769   if (Relocs.empty())
770     return;
771 
772   ulittle32_t *Table = reinterpret_cast<ulittle32_t *>(Buf);
773   // This is the list header, to signal the runtime pseudo relocation v2
774   // format.
775   Table[0] = 0;
776   Table[1] = 0;
777   Table[2] = 1;
778 
779   size_t Idx = 3;
780   for (const RuntimePseudoReloc &RPR : Relocs) {
781     Table[Idx + 0] = RPR.Sym->getRVA();
782     Table[Idx + 1] = RPR.Target->getRVA() + RPR.TargetOffset;
783     Table[Idx + 2] = RPR.Flags;
784     Idx += 3;
785   }
786 }
787 
788 // Windows-specific. This class represents a block in .reloc section.
789 // The format is described here.
790 //
791 // On Windows, each DLL is linked against a fixed base address and
792 // usually loaded to that address. However, if there's already another
793 // DLL that overlaps, the loader has to relocate it. To do that, DLLs
794 // contain .reloc sections which contain offsets that need to be fixed
795 // up at runtime. If the loader finds that a DLL cannot be loaded to its
796 // desired base address, it loads it to somewhere else, and add <actual
797 // base address> - <desired base address> to each offset that is
798 // specified by the .reloc section. In ELF terms, .reloc sections
799 // contain relative relocations in REL format (as opposed to RELA.)
800 //
801 // This already significantly reduces the size of relocations compared
802 // to ELF .rel.dyn, but Windows does more to reduce it (probably because
803 // it was invented for PCs in the late '80s or early '90s.)  Offsets in
804 // .reloc are grouped by page where the page size is 12 bits, and
805 // offsets sharing the same page address are stored consecutively to
806 // represent them with less space. This is very similar to the page
807 // table which is grouped by (multiple stages of) pages.
808 //
809 // For example, let's say we have 0x00030, 0x00500, 0x00700, 0x00A00,
810 // 0x20004, and 0x20008 in a .reloc section for x64. The uppermost 4
811 // bits have a type IMAGE_REL_BASED_DIR64 or 0xA. In the section, they
812 // are represented like this:
813 //
814 //   0x00000  -- page address (4 bytes)
815 //   16       -- size of this block (4 bytes)
816 //     0xA030 -- entries (2 bytes each)
817 //     0xA500
818 //     0xA700
819 //     0xAA00
820 //   0x20000  -- page address (4 bytes)
821 //   12       -- size of this block (4 bytes)
822 //     0xA004 -- entries (2 bytes each)
823 //     0xA008
824 //
825 // Usually we have a lot of relocations for each page, so the number of
826 // bytes for one .reloc entry is close to 2 bytes on average.
827 BaserelChunk::BaserelChunk(uint32_t Page, Baserel *Begin, Baserel *End) {
828   // Block header consists of 4 byte page RVA and 4 byte block size.
829   // Each entry is 2 byte. Last entry may be padding.
830   Data.resize(alignTo((End - Begin) * 2 + 8, 4));
831   uint8_t *P = Data.data();
832   write32le(P, Page);
833   write32le(P + 4, Data.size());
834   P += 8;
835   for (Baserel *I = Begin; I != End; ++I) {
836     write16le(P, (I->Type << 12) | (I->RVA - Page));
837     P += 2;
838   }
839 }
840 
841 void BaserelChunk::writeTo(uint8_t *Buf) const {
842   memcpy(Buf, Data.data(), Data.size());
843 }
844 
845 uint8_t Baserel::getDefaultType() {
846   switch (Config->Machine) {
847   case AMD64:
848   case ARM64:
849     return IMAGE_REL_BASED_DIR64;
850   case I386:
851   case ARMNT:
852     return IMAGE_REL_BASED_HIGHLOW;
853   default:
854     llvm_unreachable("unknown machine type");
855   }
856 }
857 
858 MergeChunk *MergeChunk::Instances[Log2MaxSectionAlignment + 1] = {};
859 
860 MergeChunk::MergeChunk(uint32_t Alignment)
861     : Builder(StringTableBuilder::RAW, Alignment) {
862   setAlignment(Alignment);
863 }
864 
865 void MergeChunk::addSection(SectionChunk *C) {
866   assert(isPowerOf2_32(C->getAlignment()));
867   uint8_t P2Align = llvm::Log2_32(C->getAlignment());
868   assert(P2Align >= 0 && P2Align < array_lengthof(Instances));
869   auto *&MC = Instances[P2Align];
870   if (!MC)
871     MC = make<MergeChunk>(C->getAlignment());
872   MC->Sections.push_back(C);
873 }
874 
875 void MergeChunk::finalizeContents() {
876   if (!Finalized) {
877     for (SectionChunk *C : Sections)
878       if (C->Live)
879         Builder.add(toStringRef(C->getContents()));
880     Builder.finalize();
881     Finalized = true;
882   }
883 
884   for (SectionChunk *C : Sections) {
885     if (!C->Live)
886       continue;
887     size_t Off = Builder.getOffset(toStringRef(C->getContents()));
888     C->setOutputSection(Out);
889     C->setRVA(RVA + Off);
890   }
891 }
892 
893 uint32_t MergeChunk::getOutputCharacteristics() const {
894   return IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA;
895 }
896 
897 size_t MergeChunk::getSize() const {
898   return Builder.getSize();
899 }
900 
901 void MergeChunk::writeTo(uint8_t *Buf) const {
902   Builder.write(Buf);
903 }
904 
905 // MinGW specific.
906 size_t AbsolutePointerChunk::getSize() const { return Config->Wordsize; }
907 
908 void AbsolutePointerChunk::writeTo(uint8_t *Buf) const {
909   if (Config->is64()) {
910     write64le(Buf, Value);
911   } else {
912     write32le(Buf, Value);
913   }
914 }
915 
916 } // namespace coff
917 } // namespace lld
918