Coverage Report

Created: 2018-08-19 21:11

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