xref: /llvm-project-15.0.7/lld/ELF/Arch/X86_64.cpp (revision 8a5f0d88)
1 //===- X86_64.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 "InputFiles.h"
10 #include "OutputSections.h"
11 #include "Symbols.h"
12 #include "SyntheticSections.h"
13 #include "Target.h"
14 #include "lld/Common/ErrorHandler.h"
15 #include "llvm/Object/ELF.h"
16 #include "llvm/Support/Endian.h"
17 
18 using namespace llvm;
19 using namespace llvm::object;
20 using namespace llvm::support::endian;
21 using namespace llvm::ELF;
22 using namespace lld;
23 using namespace lld::elf;
24 
25 namespace {
26 class X86_64 : public TargetInfo {
27 public:
28   X86_64();
29   int getTlsGdRelaxSkip(RelType type) const override;
30   RelExpr getRelExpr(RelType type, const Symbol &s,
31                      const uint8_t *loc) const override;
32   RelType getDynRel(RelType type) const override;
33   void writeGotPltHeader(uint8_t *buf) const override;
34   void writeGotPlt(uint8_t *buf, const Symbol &s) const override;
35   void writePltHeader(uint8_t *buf) const override;
36   void writePlt(uint8_t *buf, const Symbol &sym,
37                 uint64_t pltEntryAddr) const override;
38   void relocate(uint8_t *loc, const Relocation &rel,
39                 uint64_t val) const override;
40   void applyJumpInstrMod(uint8_t *loc, JumpModType type,
41                          unsigned size) const override;
42 
43   RelExpr adjustGotPcExpr(RelType type, int64_t addend,
44                           const uint8_t *loc) const override;
45   void relaxGot(uint8_t *loc, const Relocation &rel,
46                 uint64_t val) const override;
47   void relaxTlsGdToIe(uint8_t *loc, const Relocation &rel,
48                       uint64_t val) const override;
49   void relaxTlsGdToLe(uint8_t *loc, const Relocation &rel,
50                       uint64_t val) const override;
51   void relaxTlsIeToLe(uint8_t *loc, const Relocation &rel,
52                       uint64_t val) const override;
53   void relaxTlsLdToLe(uint8_t *loc, const Relocation &rel,
54                       uint64_t val) const override;
55   bool adjustPrologueForCrossSplitStack(uint8_t *loc, uint8_t *end,
56                                         uint8_t stOther) const override;
57   bool deleteFallThruJmpInsn(InputSection &is, InputFile *file,
58                              InputSection *nextIS) const override;
59 };
60 } // namespace
61 
62 // This is vector of NOP instructions of sizes from 1 to 8 bytes.  The
63 // appropriately sized instructions are used to fill the gaps between sections
64 // which are executed during fall through.
65 static const std::vector<std::vector<uint8_t>> nopInstructions = {
66     {0x90},
67     {0x66, 0x90},
68     {0x0f, 0x1f, 0x00},
69     {0x0f, 0x1f, 0x40, 0x00},
70     {0x0f, 0x1f, 0x44, 0x00, 0x00},
71     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
72     {0x0F, 0x1F, 0x80, 0x00, 0x00, 0x00, 0x00},
73     {0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
74     {0x66, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}};
75 
76 X86_64::X86_64() {
77   copyRel = R_X86_64_COPY;
78   gotRel = R_X86_64_GLOB_DAT;
79   noneRel = R_X86_64_NONE;
80   pltRel = R_X86_64_JUMP_SLOT;
81   relativeRel = R_X86_64_RELATIVE;
82   iRelativeRel = R_X86_64_IRELATIVE;
83   symbolicRel = R_X86_64_64;
84   tlsDescRel = R_X86_64_TLSDESC;
85   tlsGotRel = R_X86_64_TPOFF64;
86   tlsModuleIndexRel = R_X86_64_DTPMOD64;
87   tlsOffsetRel = R_X86_64_DTPOFF64;
88   gotEntrySize = 8;
89   pltHeaderSize = 16;
90   pltEntrySize = 16;
91   ipltEntrySize = 16;
92   trapInstr = {0xcc, 0xcc, 0xcc, 0xcc}; // 0xcc = INT3
93   nopInstrs = nopInstructions;
94 
95   // Align to the large page size (known as a superpage or huge page).
96   // FreeBSD automatically promotes large, superpage-aligned allocations.
97   defaultImageBase = 0x200000;
98 }
99 
100 int X86_64::getTlsGdRelaxSkip(RelType type) const { return 2; }
101 
102 // Opcodes for the different X86_64 jmp instructions.
103 enum JmpInsnOpcode : uint32_t {
104   J_JMP_32,
105   J_JNE_32,
106   J_JE_32,
107   J_JG_32,
108   J_JGE_32,
109   J_JB_32,
110   J_JBE_32,
111   J_JL_32,
112   J_JLE_32,
113   J_JA_32,
114   J_JAE_32,
115   J_UNKNOWN,
116 };
117 
118 // Given the first (optional) and second byte of the insn's opcode, this
119 // returns the corresponding enum value.
120 static JmpInsnOpcode getJmpInsnType(const uint8_t *first,
121                                     const uint8_t *second) {
122   if (*second == 0xe9)
123     return J_JMP_32;
124 
125   if (first == nullptr)
126     return J_UNKNOWN;
127 
128   if (*first == 0x0f) {
129     switch (*second) {
130     case 0x84:
131       return J_JE_32;
132     case 0x85:
133       return J_JNE_32;
134     case 0x8f:
135       return J_JG_32;
136     case 0x8d:
137       return J_JGE_32;
138     case 0x82:
139       return J_JB_32;
140     case 0x86:
141       return J_JBE_32;
142     case 0x8c:
143       return J_JL_32;
144     case 0x8e:
145       return J_JLE_32;
146     case 0x87:
147       return J_JA_32;
148     case 0x83:
149       return J_JAE_32;
150     }
151   }
152   return J_UNKNOWN;
153 }
154 
155 // Return the relocation index for input section IS with a specific Offset.
156 // Returns the maximum size of the vector if no such relocation is found.
157 static unsigned getRelocationWithOffset(const InputSection &is,
158                                         uint64_t offset) {
159   unsigned size = is.relocations.size();
160   for (unsigned i = size - 1; i + 1 > 0; --i) {
161     if (is.relocations[i].offset == offset && is.relocations[i].expr != R_NONE)
162       return i;
163   }
164   return size;
165 }
166 
167 // Returns true if R corresponds to a relocation used for a jump instruction.
168 // TODO: Once special relocations for relaxable jump instructions are available,
169 // this should be modified to use those relocations.
170 static bool isRelocationForJmpInsn(Relocation &R) {
171   return R.type == R_X86_64_PLT32 || R.type == R_X86_64_PC32 ||
172          R.type == R_X86_64_PC8;
173 }
174 
175 // Return true if Relocation R points to the first instruction in the
176 // next section.
177 // TODO: Delete this once psABI reserves a new relocation type for fall thru
178 // jumps.
179 static bool isFallThruRelocation(InputSection &is, InputFile *file,
180                                  InputSection *nextIS, Relocation &r) {
181   if (!isRelocationForJmpInsn(r))
182     return false;
183 
184   uint64_t addrLoc = is.getOutputSection()->addr + is.outSecOff + r.offset;
185   uint64_t targetOffset = InputSectionBase::getRelocTargetVA(
186       file, r.type, r.addend, addrLoc, *r.sym, r.expr);
187 
188   // If this jmp is a fall thru, the target offset is the beginning of the
189   // next section.
190   uint64_t nextSectionOffset =
191       nextIS->getOutputSection()->addr + nextIS->outSecOff;
192   return (addrLoc + 4 + targetOffset) == nextSectionOffset;
193 }
194 
195 // Return the jmp instruction opcode that is the inverse of the given
196 // opcode.  For example, JE inverted is JNE.
197 static JmpInsnOpcode invertJmpOpcode(const JmpInsnOpcode opcode) {
198   switch (opcode) {
199   case J_JE_32:
200     return J_JNE_32;
201   case J_JNE_32:
202     return J_JE_32;
203   case J_JG_32:
204     return J_JLE_32;
205   case J_JGE_32:
206     return J_JL_32;
207   case J_JB_32:
208     return J_JAE_32;
209   case J_JBE_32:
210     return J_JA_32;
211   case J_JL_32:
212     return J_JGE_32;
213   case J_JLE_32:
214     return J_JG_32;
215   case J_JA_32:
216     return J_JBE_32;
217   case J_JAE_32:
218     return J_JB_32;
219   default:
220     return J_UNKNOWN;
221   }
222 }
223 
224 // Deletes direct jump instruction in input sections that jumps to the
225 // following section as it is not required.  If there are two consecutive jump
226 // instructions, it checks if they can be flipped and one can be deleted.
227 // For example:
228 // .section .text
229 // a.BB.foo:
230 //    ...
231 //    10: jne aa.BB.foo
232 //    16: jmp bar
233 // aa.BB.foo:
234 //    ...
235 //
236 // can be converted to:
237 // a.BB.foo:
238 //   ...
239 //   10: je bar  #jne flipped to je and the jmp is deleted.
240 // aa.BB.foo:
241 //   ...
242 bool X86_64::deleteFallThruJmpInsn(InputSection &is, InputFile *file,
243                                    InputSection *nextIS) const {
244   const unsigned sizeOfDirectJmpInsn = 5;
245 
246   if (nextIS == nullptr)
247     return false;
248 
249   if (is.getSize() < sizeOfDirectJmpInsn)
250     return false;
251 
252   // If this jmp insn can be removed, it is the last insn and the
253   // relocation is 4 bytes before the end.
254   unsigned rIndex = getRelocationWithOffset(is, is.getSize() - 4);
255   if (rIndex == is.relocations.size())
256     return false;
257 
258   Relocation &r = is.relocations[rIndex];
259 
260   // Check if the relocation corresponds to a direct jmp.
261   const uint8_t *secContents = is.data().data();
262   // If it is not a direct jmp instruction, there is nothing to do here.
263   if (*(secContents + r.offset - 1) != 0xe9)
264     return false;
265 
266   if (isFallThruRelocation(is, file, nextIS, r)) {
267     // This is a fall thru and can be deleted.
268     r.expr = R_NONE;
269     r.offset = 0;
270     is.drop_back(sizeOfDirectJmpInsn);
271     is.nopFiller = true;
272     return true;
273   }
274 
275   // Now, check if flip and delete is possible.
276   const unsigned sizeOfJmpCCInsn = 6;
277   // To flip, there must be atleast one JmpCC and one direct jmp.
278   if (is.getSize() < sizeOfDirectJmpInsn + sizeOfJmpCCInsn)
279     return 0;
280 
281   unsigned rbIndex =
282       getRelocationWithOffset(is, (is.getSize() - sizeOfDirectJmpInsn - 4));
283   if (rbIndex == is.relocations.size())
284     return 0;
285 
286   Relocation &rB = is.relocations[rbIndex];
287 
288   const uint8_t *jmpInsnB = secContents + rB.offset - 1;
289   JmpInsnOpcode jmpOpcodeB = getJmpInsnType(jmpInsnB - 1, jmpInsnB);
290   if (jmpOpcodeB == J_UNKNOWN)
291     return false;
292 
293   if (!isFallThruRelocation(is, file, nextIS, rB))
294     return false;
295 
296   // jmpCC jumps to the fall thru block, the branch can be flipped and the
297   // jmp can be deleted.
298   JmpInsnOpcode jInvert = invertJmpOpcode(jmpOpcodeB);
299   if (jInvert == J_UNKNOWN)
300     return false;
301   is.jumpInstrMods.push_back({jInvert, (rB.offset - 1), 4});
302   // Move R's values to rB except the offset.
303   rB = {r.expr, r.type, rB.offset, r.addend, r.sym};
304   // Cancel R
305   r.expr = R_NONE;
306   r.offset = 0;
307   is.drop_back(sizeOfDirectJmpInsn);
308   is.nopFiller = true;
309   return true;
310 }
311 
312 RelExpr X86_64::getRelExpr(RelType type, const Symbol &s,
313                            const uint8_t *loc) const {
314   if (type == R_X86_64_GOTTPOFF)
315     config->hasStaticTlsModel = true;
316 
317   switch (type) {
318   case R_X86_64_8:
319   case R_X86_64_16:
320   case R_X86_64_32:
321   case R_X86_64_32S:
322   case R_X86_64_64:
323     return R_ABS;
324   case R_X86_64_DTPOFF32:
325   case R_X86_64_DTPOFF64:
326     return R_DTPREL;
327   case R_X86_64_TPOFF32:
328     return R_TPREL;
329   case R_X86_64_TLSDESC_CALL:
330     return R_TLSDESC_CALL;
331   case R_X86_64_TLSLD:
332     return R_TLSLD_PC;
333   case R_X86_64_TLSGD:
334     return R_TLSGD_PC;
335   case R_X86_64_SIZE32:
336   case R_X86_64_SIZE64:
337     return R_SIZE;
338   case R_X86_64_PLT32:
339     return R_PLT_PC;
340   case R_X86_64_PC8:
341   case R_X86_64_PC16:
342   case R_X86_64_PC32:
343   case R_X86_64_PC64:
344     return R_PC;
345   case R_X86_64_GOT32:
346   case R_X86_64_GOT64:
347     return R_GOTPLT;
348   case R_X86_64_GOTPC32_TLSDESC:
349     return R_TLSDESC_PC;
350   case R_X86_64_GOTPCREL:
351   case R_X86_64_GOTPCRELX:
352   case R_X86_64_REX_GOTPCRELX:
353   case R_X86_64_GOTTPOFF:
354     return R_GOT_PC;
355   case R_X86_64_GOTOFF64:
356     return R_GOTPLTREL;
357   case R_X86_64_GOTPC32:
358   case R_X86_64_GOTPC64:
359     return R_GOTPLTONLY_PC;
360   case R_X86_64_NONE:
361     return R_NONE;
362   default:
363     error(getErrorLocation(loc) + "unknown relocation (" + Twine(type) +
364           ") against symbol " + toString(s));
365     return R_NONE;
366   }
367 }
368 
369 void X86_64::writeGotPltHeader(uint8_t *buf) const {
370   // The first entry holds the value of _DYNAMIC. It is not clear why that is
371   // required, but it is documented in the psabi and the glibc dynamic linker
372   // seems to use it (note that this is relevant for linking ld.so, not any
373   // other program).
374   write64le(buf, mainPart->dynamic->getVA());
375 }
376 
377 void X86_64::writeGotPlt(uint8_t *buf, const Symbol &s) const {
378   // See comments in X86::writeGotPlt.
379   write64le(buf, s.getPltVA() + 6);
380 }
381 
382 void X86_64::writePltHeader(uint8_t *buf) const {
383   const uint8_t pltData[] = {
384       0xff, 0x35, 0, 0, 0, 0, // pushq GOTPLT+8(%rip)
385       0xff, 0x25, 0, 0, 0, 0, // jmp *GOTPLT+16(%rip)
386       0x0f, 0x1f, 0x40, 0x00, // nop
387   };
388   memcpy(buf, pltData, sizeof(pltData));
389   uint64_t gotPlt = in.gotPlt->getVA();
390   uint64_t plt = in.ibtPlt ? in.ibtPlt->getVA() : in.plt->getVA();
391   write32le(buf + 2, gotPlt - plt + 2); // GOTPLT+8
392   write32le(buf + 8, gotPlt - plt + 4); // GOTPLT+16
393 }
394 
395 void X86_64::writePlt(uint8_t *buf, const Symbol &sym,
396                       uint64_t pltEntryAddr) const {
397   const uint8_t inst[] = {
398       0xff, 0x25, 0, 0, 0, 0, // jmpq *got(%rip)
399       0x68, 0, 0, 0, 0,       // pushq <relocation index>
400       0xe9, 0, 0, 0, 0,       // jmpq plt[0]
401   };
402   memcpy(buf, inst, sizeof(inst));
403 
404   write32le(buf + 2, sym.getGotPltVA() - pltEntryAddr - 6);
405   write32le(buf + 7, sym.pltIndex);
406   write32le(buf + 12, in.plt->getVA() - pltEntryAddr - 16);
407 }
408 
409 RelType X86_64::getDynRel(RelType type) const {
410   if (type == R_X86_64_64 || type == R_X86_64_PC64 || type == R_X86_64_SIZE32 ||
411       type == R_X86_64_SIZE64)
412     return type;
413   return R_X86_64_NONE;
414 }
415 
416 void X86_64::relaxTlsGdToLe(uint8_t *loc, const Relocation &rel,
417                             uint64_t val) const {
418   if (rel.type == R_X86_64_TLSGD) {
419     // Convert
420     //   .byte 0x66
421     //   leaq x@tlsgd(%rip), %rdi
422     //   .word 0x6666
423     //   rex64
424     //   call __tls_get_addr@plt
425     // to the following two instructions.
426     const uint8_t inst[] = {
427         0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00,
428         0x00, 0x00,                            // mov %fs:0x0,%rax
429         0x48, 0x8d, 0x80, 0,    0,    0,    0, // lea x@tpoff,%rax
430     };
431     memcpy(loc - 4, inst, sizeof(inst));
432 
433     // The original code used a pc relative relocation and so we have to
434     // compensate for the -4 in had in the addend.
435     write32le(loc + 8, val + 4);
436   } else {
437     // Convert
438     //   lea x@tlsgd(%rip), %rax
439     //   call *(%rax)
440     // to the following two instructions.
441     assert(rel.type == R_X86_64_GOTPC32_TLSDESC);
442     if (memcmp(loc - 3, "\x48\x8d\x05", 3)) {
443       error(getErrorLocation(loc - 3) + "R_X86_64_GOTPC32_TLSDESC must be used "
444                                         "in callq *x@tlsdesc(%rip), %rax");
445       return;
446     }
447     // movq $x@tpoff(%rip),%rax
448     loc[-2] = 0xc7;
449     loc[-1] = 0xc0;
450     write32le(loc, val + 4);
451     // xchg ax,ax
452     loc[4] = 0x66;
453     loc[5] = 0x90;
454   }
455 }
456 
457 void X86_64::relaxTlsGdToIe(uint8_t *loc, const Relocation &rel,
458                             uint64_t val) const {
459   if (rel.type == R_X86_64_TLSGD) {
460     // Convert
461     //   .byte 0x66
462     //   leaq x@tlsgd(%rip), %rdi
463     //   .word 0x6666
464     //   rex64
465     //   call __tls_get_addr@plt
466     // to the following two instructions.
467     const uint8_t inst[] = {
468         0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00,
469         0x00, 0x00,                            // mov %fs:0x0,%rax
470         0x48, 0x03, 0x05, 0,    0,    0,    0, // addq x@gottpoff(%rip),%rax
471     };
472     memcpy(loc - 4, inst, sizeof(inst));
473 
474     // Both code sequences are PC relatives, but since we are moving the
475     // constant forward by 8 bytes we have to subtract the value by 8.
476     write32le(loc + 8, val - 8);
477   } else {
478     // Convert
479     //   lea x@tlsgd(%rip), %rax
480     //   call *(%rax)
481     // to the following two instructions.
482     assert(rel.type == R_X86_64_GOTPC32_TLSDESC);
483     if (memcmp(loc - 3, "\x48\x8d\x05", 3)) {
484       error(getErrorLocation(loc - 3) + "R_X86_64_GOTPC32_TLSDESC must be used "
485                                         "in callq *x@tlsdesc(%rip), %rax");
486       return;
487     }
488     // movq x@gottpoff(%rip),%rax
489     loc[-2] = 0x8b;
490     write32le(loc, val);
491     // xchg ax,ax
492     loc[4] = 0x66;
493     loc[5] = 0x90;
494   }
495 }
496 
497 // In some conditions, R_X86_64_GOTTPOFF relocation can be optimized to
498 // R_X86_64_TPOFF32 so that it does not use GOT.
499 void X86_64::relaxTlsIeToLe(uint8_t *loc, const Relocation &,
500                             uint64_t val) const {
501   uint8_t *inst = loc - 3;
502   uint8_t reg = loc[-1] >> 3;
503   uint8_t *regSlot = loc - 1;
504 
505   // Note that ADD with RSP or R12 is converted to ADD instead of LEA
506   // because LEA with these registers needs 4 bytes to encode and thus
507   // wouldn't fit the space.
508 
509   if (memcmp(inst, "\x48\x03\x25", 3) == 0) {
510     // "addq foo@gottpoff(%rip),%rsp" -> "addq $foo,%rsp"
511     memcpy(inst, "\x48\x81\xc4", 3);
512   } else if (memcmp(inst, "\x4c\x03\x25", 3) == 0) {
513     // "addq foo@gottpoff(%rip),%r12" -> "addq $foo,%r12"
514     memcpy(inst, "\x49\x81\xc4", 3);
515   } else if (memcmp(inst, "\x4c\x03", 2) == 0) {
516     // "addq foo@gottpoff(%rip),%r[8-15]" -> "leaq foo(%r[8-15]),%r[8-15]"
517     memcpy(inst, "\x4d\x8d", 2);
518     *regSlot = 0x80 | (reg << 3) | reg;
519   } else if (memcmp(inst, "\x48\x03", 2) == 0) {
520     // "addq foo@gottpoff(%rip),%reg -> "leaq foo(%reg),%reg"
521     memcpy(inst, "\x48\x8d", 2);
522     *regSlot = 0x80 | (reg << 3) | reg;
523   } else if (memcmp(inst, "\x4c\x8b", 2) == 0) {
524     // "movq foo@gottpoff(%rip),%r[8-15]" -> "movq $foo,%r[8-15]"
525     memcpy(inst, "\x49\xc7", 2);
526     *regSlot = 0xc0 | reg;
527   } else if (memcmp(inst, "\x48\x8b", 2) == 0) {
528     // "movq foo@gottpoff(%rip),%reg" -> "movq $foo,%reg"
529     memcpy(inst, "\x48\xc7", 2);
530     *regSlot = 0xc0 | reg;
531   } else {
532     error(getErrorLocation(loc - 3) +
533           "R_X86_64_GOTTPOFF must be used in MOVQ or ADDQ instructions only");
534   }
535 
536   // The original code used a PC relative relocation.
537   // Need to compensate for the -4 it had in the addend.
538   write32le(loc, val + 4);
539 }
540 
541 void X86_64::relaxTlsLdToLe(uint8_t *loc, const Relocation &rel,
542                             uint64_t val) const {
543   if (rel.type == R_X86_64_DTPOFF64) {
544     write64le(loc, val);
545     return;
546   }
547   if (rel.type == R_X86_64_DTPOFF32) {
548     write32le(loc, val);
549     return;
550   }
551 
552   const uint8_t inst[] = {
553       0x66, 0x66,                                           // .word 0x6666
554       0x66,                                                 // .byte 0x66
555       0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, // mov %fs:0,%rax
556   };
557 
558   if (loc[4] == 0xe8) {
559     // Convert
560     //   leaq bar@tlsld(%rip), %rdi           # 48 8d 3d <Loc>
561     //   callq __tls_get_addr@PLT             # e8 <disp32>
562     //   leaq bar@dtpoff(%rax), %rcx
563     // to
564     //   .word 0x6666
565     //   .byte 0x66
566     //   mov %fs:0,%rax
567     //   leaq bar@tpoff(%rax), %rcx
568     memcpy(loc - 3, inst, sizeof(inst));
569     return;
570   }
571 
572   if (loc[4] == 0xff && loc[5] == 0x15) {
573     // Convert
574     //   leaq  x@tlsld(%rip),%rdi               # 48 8d 3d <Loc>
575     //   call *__tls_get_addr@GOTPCREL(%rip)    # ff 15 <disp32>
576     // to
577     //   .long  0x66666666
578     //   movq   %fs:0,%rax
579     // See "Table 11.9: LD -> LE Code Transition (LP64)" in
580     // https://raw.githubusercontent.com/wiki/hjl-tools/x86-psABI/x86-64-psABI-1.0.pdf
581     loc[-3] = 0x66;
582     memcpy(loc - 2, inst, sizeof(inst));
583     return;
584   }
585 
586   error(getErrorLocation(loc - 3) +
587         "expected R_X86_64_PLT32 or R_X86_64_GOTPCRELX after R_X86_64_TLSLD");
588 }
589 
590 // A JumpInstrMod at a specific offset indicates that the jump instruction
591 // opcode at that offset must be modified.  This is specifically used to relax
592 // jump instructions with basic block sections.  This function looks at the
593 // JumpMod and effects the change.
594 void X86_64::applyJumpInstrMod(uint8_t *loc, JumpModType type,
595                                unsigned size) const {
596   switch (type) {
597   case J_JMP_32:
598     if (size == 4)
599       *loc = 0xe9;
600     else
601       *loc = 0xeb;
602     break;
603   case J_JE_32:
604     if (size == 4) {
605       loc[-1] = 0x0f;
606       *loc = 0x84;
607     } else
608       *loc = 0x74;
609     break;
610   case J_JNE_32:
611     if (size == 4) {
612       loc[-1] = 0x0f;
613       *loc = 0x85;
614     } else
615       *loc = 0x75;
616     break;
617   case J_JG_32:
618     if (size == 4) {
619       loc[-1] = 0x0f;
620       *loc = 0x8f;
621     } else
622       *loc = 0x7f;
623     break;
624   case J_JGE_32:
625     if (size == 4) {
626       loc[-1] = 0x0f;
627       *loc = 0x8d;
628     } else
629       *loc = 0x7d;
630     break;
631   case J_JB_32:
632     if (size == 4) {
633       loc[-1] = 0x0f;
634       *loc = 0x82;
635     } else
636       *loc = 0x72;
637     break;
638   case J_JBE_32:
639     if (size == 4) {
640       loc[-1] = 0x0f;
641       *loc = 0x86;
642     } else
643       *loc = 0x76;
644     break;
645   case J_JL_32:
646     if (size == 4) {
647       loc[-1] = 0x0f;
648       *loc = 0x8c;
649     } else
650       *loc = 0x7c;
651     break;
652   case J_JLE_32:
653     if (size == 4) {
654       loc[-1] = 0x0f;
655       *loc = 0x8e;
656     } else
657       *loc = 0x7e;
658     break;
659   case J_JA_32:
660     if (size == 4) {
661       loc[-1] = 0x0f;
662       *loc = 0x87;
663     } else
664       *loc = 0x77;
665     break;
666   case J_JAE_32:
667     if (size == 4) {
668       loc[-1] = 0x0f;
669       *loc = 0x83;
670     } else
671       *loc = 0x73;
672     break;
673   case J_UNKNOWN:
674     llvm_unreachable("Unknown Jump Relocation");
675   }
676 }
677 
678 void X86_64::relocate(uint8_t *loc, const Relocation &rel, uint64_t val) const {
679   switch (rel.type) {
680   case R_X86_64_8:
681     checkIntUInt(loc, val, 8, rel);
682     *loc = val;
683     break;
684   case R_X86_64_PC8:
685     checkInt(loc, val, 8, rel);
686     *loc = val;
687     break;
688   case R_X86_64_16:
689     checkIntUInt(loc, val, 16, rel);
690     write16le(loc, val);
691     break;
692   case R_X86_64_PC16:
693     checkInt(loc, val, 16, rel);
694     write16le(loc, val);
695     break;
696   case R_X86_64_32:
697     checkUInt(loc, val, 32, rel);
698     write32le(loc, val);
699     break;
700   case R_X86_64_32S:
701   case R_X86_64_TPOFF32:
702   case R_X86_64_GOT32:
703   case R_X86_64_GOTPC32:
704   case R_X86_64_GOTPC32_TLSDESC:
705   case R_X86_64_GOTPCREL:
706   case R_X86_64_GOTPCRELX:
707   case R_X86_64_REX_GOTPCRELX:
708   case R_X86_64_PC32:
709   case R_X86_64_GOTTPOFF:
710   case R_X86_64_PLT32:
711   case R_X86_64_TLSGD:
712   case R_X86_64_TLSLD:
713   case R_X86_64_DTPOFF32:
714   case R_X86_64_SIZE32:
715     checkInt(loc, val, 32, rel);
716     write32le(loc, val);
717     break;
718   case R_X86_64_64:
719   case R_X86_64_DTPOFF64:
720   case R_X86_64_PC64:
721   case R_X86_64_SIZE64:
722   case R_X86_64_GOT64:
723   case R_X86_64_GOTOFF64:
724   case R_X86_64_GOTPC64:
725     write64le(loc, val);
726     break;
727   default:
728     llvm_unreachable("unknown relocation");
729   }
730 }
731 
732 RelExpr X86_64::adjustGotPcExpr(RelType type, int64_t addend,
733                                 const uint8_t *loc) const {
734   // Only R_X86_64_[REX_]GOTPCRELX can be relaxed. GNU as may emit GOTPCRELX
735   // with addend != -4. Such an instruction does not load the full GOT entry, so
736   // we cannot relax the relocation. E.g. movl x@GOTPCREL+4(%rip), %rax
737   // (addend=0) loads the high 32 bits of the GOT entry.
738   if ((type != R_X86_64_GOTPCRELX && type != R_X86_64_REX_GOTPCRELX) ||
739       addend != -4)
740     return R_GOT_PC;
741   const uint8_t op = loc[-2];
742   const uint8_t modRm = loc[-1];
743 
744   // FIXME: When PIC is disabled and foo is defined locally in the
745   // lower 32 bit address space, memory operand in mov can be converted into
746   // immediate operand. Otherwise, mov must be changed to lea. We support only
747   // latter relaxation at this moment.
748   if (op == 0x8b)
749     return R_RELAX_GOT_PC;
750 
751   // Relax call and jmp.
752   if (op == 0xff && (modRm == 0x15 || modRm == 0x25))
753     return R_RELAX_GOT_PC;
754 
755   // We don't support test/binop instructions without a REX prefix.
756   if (type == R_X86_64_GOTPCRELX)
757     return R_GOT_PC;
758 
759   // Relaxation of test, adc, add, and, cmp, or, sbb, sub, xor.
760   // If PIC then no relaxation is available.
761   return config->isPic ? R_GOT_PC : R_RELAX_GOT_PC_NOPIC;
762 }
763 
764 // A subset of relaxations can only be applied for no-PIC. This method
765 // handles such relaxations. Instructions encoding information was taken from:
766 // "Intel 64 and IA-32 Architectures Software Developer's Manual V2"
767 // (http://www.intel.com/content/dam/www/public/us/en/documents/manuals/
768 //    64-ia-32-architectures-software-developer-instruction-set-reference-manual-325383.pdf)
769 static void relaxGotNoPic(uint8_t *loc, uint64_t val, uint8_t op,
770                           uint8_t modRm) {
771   const uint8_t rex = loc[-3];
772   // Convert "test %reg, foo@GOTPCREL(%rip)" to "test $foo, %reg".
773   if (op == 0x85) {
774     // See "TEST-Logical Compare" (4-428 Vol. 2B),
775     // TEST r/m64, r64 uses "full" ModR / M byte (no opcode extension).
776 
777     // ModR/M byte has form XX YYY ZZZ, where
778     // YYY is MODRM.reg(register 2), ZZZ is MODRM.rm(register 1).
779     // XX has different meanings:
780     // 00: The operand's memory address is in reg1.
781     // 01: The operand's memory address is reg1 + a byte-sized displacement.
782     // 10: The operand's memory address is reg1 + a word-sized displacement.
783     // 11: The operand is reg1 itself.
784     // If an instruction requires only one operand, the unused reg2 field
785     // holds extra opcode bits rather than a register code
786     // 0xC0 == 11 000 000 binary.
787     // 0x38 == 00 111 000 binary.
788     // We transfer reg2 to reg1 here as operand.
789     // See "2.1.3 ModR/M and SIB Bytes" (Vol. 2A 2-3).
790     loc[-1] = 0xc0 | (modRm & 0x38) >> 3; // ModR/M byte.
791 
792     // Change opcode from TEST r/m64, r64 to TEST r/m64, imm32
793     // See "TEST-Logical Compare" (4-428 Vol. 2B).
794     loc[-2] = 0xf7;
795 
796     // Move R bit to the B bit in REX byte.
797     // REX byte is encoded as 0100WRXB, where
798     // 0100 is 4bit fixed pattern.
799     // REX.W When 1, a 64-bit operand size is used. Otherwise, when 0, the
800     //   default operand size is used (which is 32-bit for most but not all
801     //   instructions).
802     // REX.R This 1-bit value is an extension to the MODRM.reg field.
803     // REX.X This 1-bit value is an extension to the SIB.index field.
804     // REX.B This 1-bit value is an extension to the MODRM.rm field or the
805     // SIB.base field.
806     // See "2.2.1.2 More on REX Prefix Fields " (2-8 Vol. 2A).
807     loc[-3] = (rex & ~0x4) | (rex & 0x4) >> 2;
808     write32le(loc, val);
809     return;
810   }
811 
812   // If we are here then we need to relax the adc, add, and, cmp, or, sbb, sub
813   // or xor operations.
814 
815   // Convert "binop foo@GOTPCREL(%rip), %reg" to "binop $foo, %reg".
816   // Logic is close to one for test instruction above, but we also
817   // write opcode extension here, see below for details.
818   loc[-1] = 0xc0 | (modRm & 0x38) >> 3 | (op & 0x3c); // ModR/M byte.
819 
820   // Primary opcode is 0x81, opcode extension is one of:
821   // 000b = ADD, 001b is OR, 010b is ADC, 011b is SBB,
822   // 100b is AND, 101b is SUB, 110b is XOR, 111b is CMP.
823   // This value was wrote to MODRM.reg in a line above.
824   // See "3.2 INSTRUCTIONS (A-M)" (Vol. 2A 3-15),
825   // "INSTRUCTION SET REFERENCE, N-Z" (Vol. 2B 4-1) for
826   // descriptions about each operation.
827   loc[-2] = 0x81;
828   loc[-3] = (rex & ~0x4) | (rex & 0x4) >> 2;
829   write32le(loc, val);
830 }
831 
832 void X86_64::relaxGot(uint8_t *loc, const Relocation &rel, uint64_t val) const {
833   checkInt(loc, val, 32, rel);
834   const uint8_t op = loc[-2];
835   const uint8_t modRm = loc[-1];
836 
837   // Convert "mov foo@GOTPCREL(%rip),%reg" to "lea foo(%rip),%reg".
838   if (op == 0x8b) {
839     loc[-2] = 0x8d;
840     write32le(loc, val);
841     return;
842   }
843 
844   if (op != 0xff) {
845     // We are relaxing a rip relative to an absolute, so compensate
846     // for the old -4 addend.
847     assert(!config->isPic);
848     relaxGotNoPic(loc, val + 4, op, modRm);
849     return;
850   }
851 
852   // Convert call/jmp instructions.
853   if (modRm == 0x15) {
854     // ABI says we can convert "call *foo@GOTPCREL(%rip)" to "nop; call foo".
855     // Instead we convert to "addr32 call foo" where addr32 is an instruction
856     // prefix. That makes result expression to be a single instruction.
857     loc[-2] = 0x67; // addr32 prefix
858     loc[-1] = 0xe8; // call
859     write32le(loc, val);
860     return;
861   }
862 
863   // Convert "jmp *foo@GOTPCREL(%rip)" to "jmp foo; nop".
864   // jmp doesn't return, so it is fine to use nop here, it is just a stub.
865   assert(modRm == 0x25);
866   loc[-2] = 0xe9; // jmp
867   loc[3] = 0x90;  // nop
868   write32le(loc - 1, val + 1);
869 }
870 
871 // A split-stack prologue starts by checking the amount of stack remaining
872 // in one of two ways:
873 // A) Comparing of the stack pointer to a field in the tcb.
874 // B) Or a load of a stack pointer offset with an lea to r10 or r11.
875 bool X86_64::adjustPrologueForCrossSplitStack(uint8_t *loc, uint8_t *end,
876                                               uint8_t stOther) const {
877   if (!config->is64) {
878     error("Target doesn't support split stacks.");
879     return false;
880   }
881 
882   if (loc + 8 >= end)
883     return false;
884 
885   // Replace "cmp %fs:0x70,%rsp" and subsequent branch
886   // with "stc, nopl 0x0(%rax,%rax,1)"
887   if (memcmp(loc, "\x64\x48\x3b\x24\x25", 5) == 0) {
888     memcpy(loc, "\xf9\x0f\x1f\x84\x00\x00\x00\x00", 8);
889     return true;
890   }
891 
892   // Adjust "lea X(%rsp),%rYY" to lea "(X - 0x4000)(%rsp),%rYY" where rYY could
893   // be r10 or r11. The lea instruction feeds a subsequent compare which checks
894   // if there is X available stack space. Making X larger effectively reserves
895   // that much additional space. The stack grows downward so subtract the value.
896   if (memcmp(loc, "\x4c\x8d\x94\x24", 4) == 0 ||
897       memcmp(loc, "\x4c\x8d\x9c\x24", 4) == 0) {
898     // The offset bytes are encoded four bytes after the start of the
899     // instruction.
900     write32le(loc + 4, read32le(loc + 4) - 0x4000);
901     return true;
902   }
903   return false;
904 }
905 
906 // If Intel Indirect Branch Tracking is enabled, we have to emit special PLT
907 // entries containing endbr64 instructions. A PLT entry will be split into two
908 // parts, one in .plt.sec (writePlt), and the other in .plt (writeIBTPlt).
909 namespace {
910 class IntelIBT : public X86_64 {
911 public:
912   IntelIBT();
913   void writeGotPlt(uint8_t *buf, const Symbol &s) const override;
914   void writePlt(uint8_t *buf, const Symbol &sym,
915                 uint64_t pltEntryAddr) const override;
916   void writeIBTPlt(uint8_t *buf, size_t numEntries) const override;
917 
918   static const unsigned IBTPltHeaderSize = 16;
919 };
920 } // namespace
921 
922 IntelIBT::IntelIBT() { pltHeaderSize = 0; }
923 
924 void IntelIBT::writeGotPlt(uint8_t *buf, const Symbol &s) const {
925   uint64_t va =
926       in.ibtPlt->getVA() + IBTPltHeaderSize + s.pltIndex * pltEntrySize;
927   write64le(buf, va);
928 }
929 
930 void IntelIBT::writePlt(uint8_t *buf, const Symbol &sym,
931                         uint64_t pltEntryAddr) const {
932   const uint8_t Inst[] = {
933       0xf3, 0x0f, 0x1e, 0xfa,       // endbr64
934       0xff, 0x25, 0,    0,    0, 0, // jmpq *got(%rip)
935       0x66, 0x0f, 0x1f, 0x44, 0, 0, // nop
936   };
937   memcpy(buf, Inst, sizeof(Inst));
938   write32le(buf + 6, sym.getGotPltVA() - pltEntryAddr - 10);
939 }
940 
941 void IntelIBT::writeIBTPlt(uint8_t *buf, size_t numEntries) const {
942   writePltHeader(buf);
943   buf += IBTPltHeaderSize;
944 
945   const uint8_t inst[] = {
946       0xf3, 0x0f, 0x1e, 0xfa,    // endbr64
947       0x68, 0,    0,    0,    0, // pushq <relocation index>
948       0xe9, 0,    0,    0,    0, // jmpq plt[0]
949       0x66, 0x90,                // nop
950   };
951 
952   for (size_t i = 0; i < numEntries; ++i) {
953     memcpy(buf, inst, sizeof(inst));
954     write32le(buf + 5, i);
955     write32le(buf + 10, -pltHeaderSize - sizeof(inst) * i - 30);
956     buf += sizeof(inst);
957   }
958 }
959 
960 // These nonstandard PLT entries are to migtigate Spectre v2 security
961 // vulnerability. In order to mitigate Spectre v2, we want to avoid indirect
962 // branch instructions such as `jmp *GOTPLT(%rip)`. So, in the following PLT
963 // entries, we use a CALL followed by MOV and RET to do the same thing as an
964 // indirect jump. That instruction sequence is so-called "retpoline".
965 //
966 // We have two types of retpoline PLTs as a size optimization. If `-z now`
967 // is specified, all dynamic symbols are resolved at load-time. Thus, when
968 // that option is given, we can omit code for symbol lazy resolution.
969 namespace {
970 class Retpoline : public X86_64 {
971 public:
972   Retpoline();
973   void writeGotPlt(uint8_t *buf, const Symbol &s) const override;
974   void writePltHeader(uint8_t *buf) const override;
975   void writePlt(uint8_t *buf, const Symbol &sym,
976                 uint64_t pltEntryAddr) const override;
977 };
978 
979 class RetpolineZNow : public X86_64 {
980 public:
981   RetpolineZNow();
982   void writeGotPlt(uint8_t *buf, const Symbol &s) const override {}
983   void writePltHeader(uint8_t *buf) const override;
984   void writePlt(uint8_t *buf, const Symbol &sym,
985                 uint64_t pltEntryAddr) const override;
986 };
987 } // namespace
988 
989 Retpoline::Retpoline() {
990   pltHeaderSize = 48;
991   pltEntrySize = 32;
992   ipltEntrySize = 32;
993 }
994 
995 void Retpoline::writeGotPlt(uint8_t *buf, const Symbol &s) const {
996   write64le(buf, s.getPltVA() + 17);
997 }
998 
999 void Retpoline::writePltHeader(uint8_t *buf) const {
1000   const uint8_t insn[] = {
1001       0xff, 0x35, 0,    0,    0,    0,          // 0:    pushq GOTPLT+8(%rip)
1002       0x4c, 0x8b, 0x1d, 0,    0,    0,    0,    // 6:    mov GOTPLT+16(%rip), %r11
1003       0xe8, 0x0e, 0x00, 0x00, 0x00,             // d:    callq next
1004       0xf3, 0x90,                               // 12: loop: pause
1005       0x0f, 0xae, 0xe8,                         // 14:   lfence
1006       0xeb, 0xf9,                               // 17:   jmp loop
1007       0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, // 19:   int3; .align 16
1008       0x4c, 0x89, 0x1c, 0x24,                   // 20: next: mov %r11, (%rsp)
1009       0xc3,                                     // 24:   ret
1010       0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, // 25:   int3; padding
1011       0xcc, 0xcc, 0xcc, 0xcc,                   // 2c:   int3; padding
1012   };
1013   memcpy(buf, insn, sizeof(insn));
1014 
1015   uint64_t gotPlt = in.gotPlt->getVA();
1016   uint64_t plt = in.plt->getVA();
1017   write32le(buf + 2, gotPlt - plt - 6 + 8);
1018   write32le(buf + 9, gotPlt - plt - 13 + 16);
1019 }
1020 
1021 void Retpoline::writePlt(uint8_t *buf, const Symbol &sym,
1022                          uint64_t pltEntryAddr) const {
1023   const uint8_t insn[] = {
1024       0x4c, 0x8b, 0x1d, 0, 0, 0, 0, // 0:  mov foo@GOTPLT(%rip), %r11
1025       0xe8, 0,    0,    0,    0,    // 7:  callq plt+0x20
1026       0xe9, 0,    0,    0,    0,    // c:  jmp plt+0x12
1027       0x68, 0,    0,    0,    0,    // 11: pushq <relocation index>
1028       0xe9, 0,    0,    0,    0,    // 16: jmp plt+0
1029       0xcc, 0xcc, 0xcc, 0xcc, 0xcc, // 1b: int3; padding
1030   };
1031   memcpy(buf, insn, sizeof(insn));
1032 
1033   uint64_t off = pltEntryAddr - in.plt->getVA();
1034 
1035   write32le(buf + 3, sym.getGotPltVA() - pltEntryAddr - 7);
1036   write32le(buf + 8, -off - 12 + 32);
1037   write32le(buf + 13, -off - 17 + 18);
1038   write32le(buf + 18, sym.pltIndex);
1039   write32le(buf + 23, -off - 27);
1040 }
1041 
1042 RetpolineZNow::RetpolineZNow() {
1043   pltHeaderSize = 32;
1044   pltEntrySize = 16;
1045   ipltEntrySize = 16;
1046 }
1047 
1048 void RetpolineZNow::writePltHeader(uint8_t *buf) const {
1049   const uint8_t insn[] = {
1050       0xe8, 0x0b, 0x00, 0x00, 0x00, // 0:    call next
1051       0xf3, 0x90,                   // 5:  loop: pause
1052       0x0f, 0xae, 0xe8,             // 7:    lfence
1053       0xeb, 0xf9,                   // a:    jmp loop
1054       0xcc, 0xcc, 0xcc, 0xcc,       // c:    int3; .align 16
1055       0x4c, 0x89, 0x1c, 0x24,       // 10: next: mov %r11, (%rsp)
1056       0xc3,                         // 14:   ret
1057       0xcc, 0xcc, 0xcc, 0xcc, 0xcc, // 15:   int3; padding
1058       0xcc, 0xcc, 0xcc, 0xcc, 0xcc, // 1a:   int3; padding
1059       0xcc,                         // 1f:   int3; padding
1060   };
1061   memcpy(buf, insn, sizeof(insn));
1062 }
1063 
1064 void RetpolineZNow::writePlt(uint8_t *buf, const Symbol &sym,
1065                              uint64_t pltEntryAddr) const {
1066   const uint8_t insn[] = {
1067       0x4c, 0x8b, 0x1d, 0,    0, 0, 0, // mov foo@GOTPLT(%rip), %r11
1068       0xe9, 0,    0,    0,    0,       // jmp plt+0
1069       0xcc, 0xcc, 0xcc, 0xcc,          // int3; padding
1070   };
1071   memcpy(buf, insn, sizeof(insn));
1072 
1073   write32le(buf + 3, sym.getGotPltVA() - pltEntryAddr - 7);
1074   write32le(buf + 8, in.plt->getVA() - pltEntryAddr - 12);
1075 }
1076 
1077 static TargetInfo *getTargetInfo() {
1078   if (config->zRetpolineplt) {
1079     if (config->zNow) {
1080       static RetpolineZNow t;
1081       return &t;
1082     }
1083     static Retpoline t;
1084     return &t;
1085   }
1086 
1087   if (config->andFeatures & GNU_PROPERTY_X86_FEATURE_1_IBT) {
1088     static IntelIBT t;
1089     return &t;
1090   }
1091 
1092   static X86_64 t;
1093   return &t;
1094 }
1095 
1096 TargetInfo *elf::getX86_64TargetInfo() { return getTargetInfo(); }
1097