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