xref: /llvm-project-15.0.7/lld/ELF/Arch/X86_64.cpp (revision cfb4f8c5)
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 
23 namespace lld {
24 namespace elf {
25 
26 namespace {
27 class X86_64 : public TargetInfo {
28 public:
29   X86_64();
30   int getTlsGdRelaxSkip(RelType type) const override;
31   RelExpr getRelExpr(RelType type, const Symbol &s,
32                      const uint8_t *loc) const override;
33   RelType getDynRel(RelType type) const override;
34   void writeGotPltHeader(uint8_t *buf) const override;
35   void writeGotPlt(uint8_t *buf, const Symbol &s) const override;
36   void writePltHeader(uint8_t *buf) const override;
37   void writePlt(uint8_t *buf, const Symbol &sym,
38                 uint64_t pltEntryAddr) const override;
39   void relocate(uint8_t *loc, const Relocation &rel,
40                 uint64_t val) const override;
41   void applyJumpInstrMod(uint8_t *loc, JumpModType type,
42                          unsigned size) const override;
43 
44   RelExpr adjustRelaxExpr(RelType type, const uint8_t *data,
45                           RelExpr expr) const override;
46   void relaxGot(uint8_t *loc, const Relocation &rel,
47                 uint64_t val) const override;
48   void relaxTlsGdToIe(uint8_t *loc, const Relocation &rel,
49                       uint64_t val) const override;
50   void relaxTlsGdToLe(uint8_t *loc, const Relocation &rel,
51                       uint64_t val) const override;
52   void relaxTlsIeToLe(uint8_t *loc, const Relocation &rel,
53                       uint64_t val) const override;
54   void relaxTlsLdToLe(uint8_t *loc, const Relocation &rel,
55                       uint64_t val) const override;
56   bool adjustPrologueForCrossSplitStack(uint8_t *loc, uint8_t *end,
57                                         uint8_t stOther) const override;
58   bool deleteFallThruJmpInsn(InputSection &is, InputFile *file,
59                              InputSection *nextIS) const override;
60 };
61 } // namespace
62 
63 // This is vector of NOP instructions of sizes from 1 to 8 bytes.  The
64 // appropriately sized instructions are used to fill the gaps between sections
65 // which are executed during fall through.
66 static const std::vector<std::vector<uint8_t>> nopInstructions = {
67     {0x90},
68     {0x66, 0x90},
69     {0x0f, 0x1f, 0x00},
70     {0x0f, 0x1f, 0x40, 0x00},
71     {0x0f, 0x1f, 0x44, 0x00, 0x00},
72     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
73     {0x0F, 0x1F, 0x80, 0x00, 0x00, 0x00, 0x00},
74     {0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
75     {0x66, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}};
76 
77 X86_64::X86_64() {
78   copyRel = R_X86_64_COPY;
79   gotRel = R_X86_64_GLOB_DAT;
80   noneRel = R_X86_64_NONE;
81   pltRel = R_X86_64_JUMP_SLOT;
82   relativeRel = R_X86_64_RELATIVE;
83   iRelativeRel = R_X86_64_IRELATIVE;
84   symbolicRel = R_X86_64_64;
85   tlsDescRel = R_X86_64_TLSDESC;
86   tlsGotRel = R_X86_64_TPOFF64;
87   tlsModuleIndexRel = R_X86_64_DTPMOD64;
88   tlsOffsetRel = R_X86_64_DTPOFF64;
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_TLS;
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::adjustRelaxExpr(RelType type, const uint8_t *data,
733                                 RelExpr relExpr) const {
734   if (type != R_X86_64_GOTPCRELX && type != R_X86_64_REX_GOTPCRELX)
735     return relExpr;
736   const uint8_t op = data[-2];
737   const uint8_t modRm = data[-1];
738 
739   // FIXME: When PIC is disabled and foo is defined locally in the
740   // lower 32 bit address space, memory operand in mov can be converted into
741   // immediate operand. Otherwise, mov must be changed to lea. We support only
742   // latter relaxation at this moment.
743   if (op == 0x8b)
744     return R_RELAX_GOT_PC;
745 
746   // Relax call and jmp.
747   if (op == 0xff && (modRm == 0x15 || modRm == 0x25))
748     return R_RELAX_GOT_PC;
749 
750   // Relaxation of test, adc, add, and, cmp, or, sbb, sub, xor.
751   // If PIC then no relaxation is available.
752   // We also don't relax test/binop instructions without REX byte,
753   // they are 32bit operations and not common to have.
754   assert(type == R_X86_64_REX_GOTPCRELX);
755   return config->isPic ? relExpr : R_RELAX_GOT_PC_NOPIC;
756 }
757 
758 // A subset of relaxations can only be applied for no-PIC. This method
759 // handles such relaxations. Instructions encoding information was taken from:
760 // "Intel 64 and IA-32 Architectures Software Developer's Manual V2"
761 // (http://www.intel.com/content/dam/www/public/us/en/documents/manuals/
762 //    64-ia-32-architectures-software-developer-instruction-set-reference-manual-325383.pdf)
763 static void relaxGotNoPic(uint8_t *loc, uint64_t val, uint8_t op,
764                           uint8_t modRm) {
765   const uint8_t rex = loc[-3];
766   // Convert "test %reg, foo@GOTPCREL(%rip)" to "test $foo, %reg".
767   if (op == 0x85) {
768     // See "TEST-Logical Compare" (4-428 Vol. 2B),
769     // TEST r/m64, r64 uses "full" ModR / M byte (no opcode extension).
770 
771     // ModR/M byte has form XX YYY ZZZ, where
772     // YYY is MODRM.reg(register 2), ZZZ is MODRM.rm(register 1).
773     // XX has different meanings:
774     // 00: The operand's memory address is in reg1.
775     // 01: The operand's memory address is reg1 + a byte-sized displacement.
776     // 10: The operand's memory address is reg1 + a word-sized displacement.
777     // 11: The operand is reg1 itself.
778     // If an instruction requires only one operand, the unused reg2 field
779     // holds extra opcode bits rather than a register code
780     // 0xC0 == 11 000 000 binary.
781     // 0x38 == 00 111 000 binary.
782     // We transfer reg2 to reg1 here as operand.
783     // See "2.1.3 ModR/M and SIB Bytes" (Vol. 2A 2-3).
784     loc[-1] = 0xc0 | (modRm & 0x38) >> 3; // ModR/M byte.
785 
786     // Change opcode from TEST r/m64, r64 to TEST r/m64, imm32
787     // See "TEST-Logical Compare" (4-428 Vol. 2B).
788     loc[-2] = 0xf7;
789 
790     // Move R bit to the B bit in REX byte.
791     // REX byte is encoded as 0100WRXB, where
792     // 0100 is 4bit fixed pattern.
793     // REX.W When 1, a 64-bit operand size is used. Otherwise, when 0, the
794     //   default operand size is used (which is 32-bit for most but not all
795     //   instructions).
796     // REX.R This 1-bit value is an extension to the MODRM.reg field.
797     // REX.X This 1-bit value is an extension to the SIB.index field.
798     // REX.B This 1-bit value is an extension to the MODRM.rm field or the
799     // SIB.base field.
800     // See "2.2.1.2 More on REX Prefix Fields " (2-8 Vol. 2A).
801     loc[-3] = (rex & ~0x4) | (rex & 0x4) >> 2;
802     write32le(loc, val);
803     return;
804   }
805 
806   // If we are here then we need to relax the adc, add, and, cmp, or, sbb, sub
807   // or xor operations.
808 
809   // Convert "binop foo@GOTPCREL(%rip), %reg" to "binop $foo, %reg".
810   // Logic is close to one for test instruction above, but we also
811   // write opcode extension here, see below for details.
812   loc[-1] = 0xc0 | (modRm & 0x38) >> 3 | (op & 0x3c); // ModR/M byte.
813 
814   // Primary opcode is 0x81, opcode extension is one of:
815   // 000b = ADD, 001b is OR, 010b is ADC, 011b is SBB,
816   // 100b is AND, 101b is SUB, 110b is XOR, 111b is CMP.
817   // This value was wrote to MODRM.reg in a line above.
818   // See "3.2 INSTRUCTIONS (A-M)" (Vol. 2A 3-15),
819   // "INSTRUCTION SET REFERENCE, N-Z" (Vol. 2B 4-1) for
820   // descriptions about each operation.
821   loc[-2] = 0x81;
822   loc[-3] = (rex & ~0x4) | (rex & 0x4) >> 2;
823   write32le(loc, val);
824 }
825 
826 void X86_64::relaxGot(uint8_t *loc, const Relocation &, uint64_t val) const {
827   const uint8_t op = loc[-2];
828   const uint8_t modRm = loc[-1];
829 
830   // Convert "mov foo@GOTPCREL(%rip),%reg" to "lea foo(%rip),%reg".
831   if (op == 0x8b) {
832     loc[-2] = 0x8d;
833     write32le(loc, val);
834     return;
835   }
836 
837   if (op != 0xff) {
838     // We are relaxing a rip relative to an absolute, so compensate
839     // for the old -4 addend.
840     assert(!config->isPic);
841     relaxGotNoPic(loc, val + 4, op, modRm);
842     return;
843   }
844 
845   // Convert call/jmp instructions.
846   if (modRm == 0x15) {
847     // ABI says we can convert "call *foo@GOTPCREL(%rip)" to "nop; call foo".
848     // Instead we convert to "addr32 call foo" where addr32 is an instruction
849     // prefix. That makes result expression to be a single instruction.
850     loc[-2] = 0x67; // addr32 prefix
851     loc[-1] = 0xe8; // call
852     write32le(loc, val);
853     return;
854   }
855 
856   // Convert "jmp *foo@GOTPCREL(%rip)" to "jmp foo; nop".
857   // jmp doesn't return, so it is fine to use nop here, it is just a stub.
858   assert(modRm == 0x25);
859   loc[-2] = 0xe9; // jmp
860   loc[3] = 0x90;  // nop
861   write32le(loc - 1, val + 1);
862 }
863 
864 // A split-stack prologue starts by checking the amount of stack remaining
865 // in one of two ways:
866 // A) Comparing of the stack pointer to a field in the tcb.
867 // B) Or a load of a stack pointer offset with an lea to r10 or r11.
868 bool X86_64::adjustPrologueForCrossSplitStack(uint8_t *loc, uint8_t *end,
869                                               uint8_t stOther) const {
870   if (!config->is64) {
871     error("Target doesn't support split stacks.");
872     return false;
873   }
874 
875   if (loc + 8 >= end)
876     return false;
877 
878   // Replace "cmp %fs:0x70,%rsp" and subsequent branch
879   // with "stc, nopl 0x0(%rax,%rax,1)"
880   if (memcmp(loc, "\x64\x48\x3b\x24\x25", 5) == 0) {
881     memcpy(loc, "\xf9\x0f\x1f\x84\x00\x00\x00\x00", 8);
882     return true;
883   }
884 
885   // Adjust "lea X(%rsp),%rYY" to lea "(X - 0x4000)(%rsp),%rYY" where rYY could
886   // be r10 or r11. The lea instruction feeds a subsequent compare which checks
887   // if there is X available stack space. Making X larger effectively reserves
888   // that much additional space. The stack grows downward so subtract the value.
889   if (memcmp(loc, "\x4c\x8d\x94\x24", 4) == 0 ||
890       memcmp(loc, "\x4c\x8d\x9c\x24", 4) == 0) {
891     // The offset bytes are encoded four bytes after the start of the
892     // instruction.
893     write32le(loc + 4, read32le(loc + 4) - 0x4000);
894     return true;
895   }
896   return false;
897 }
898 
899 // If Intel Indirect Branch Tracking is enabled, we have to emit special PLT
900 // entries containing endbr64 instructions. A PLT entry will be split into two
901 // parts, one in .plt.sec (writePlt), and the other in .plt (writeIBTPlt).
902 namespace {
903 class IntelIBT : public X86_64 {
904 public:
905   IntelIBT();
906   void writeGotPlt(uint8_t *buf, const Symbol &s) const override;
907   void writePlt(uint8_t *buf, const Symbol &sym,
908                 uint64_t pltEntryAddr) const override;
909   void writeIBTPlt(uint8_t *buf, size_t numEntries) const override;
910 
911   static const unsigned IBTPltHeaderSize = 16;
912 };
913 } // namespace
914 
915 IntelIBT::IntelIBT() { pltHeaderSize = 0; }
916 
917 void IntelIBT::writeGotPlt(uint8_t *buf, const Symbol &s) const {
918   uint64_t va =
919       in.ibtPlt->getVA() + IBTPltHeaderSize + s.pltIndex * pltEntrySize;
920   write64le(buf, va);
921 }
922 
923 void IntelIBT::writePlt(uint8_t *buf, const Symbol &sym,
924                         uint64_t pltEntryAddr) const {
925   const uint8_t Inst[] = {
926       0xf3, 0x0f, 0x1e, 0xfa,       // endbr64
927       0xff, 0x25, 0,    0,    0, 0, // jmpq *got(%rip)
928       0x66, 0x0f, 0x1f, 0x44, 0, 0, // nop
929   };
930   memcpy(buf, Inst, sizeof(Inst));
931   write32le(buf + 6, sym.getGotPltVA() - pltEntryAddr - 10);
932 }
933 
934 void IntelIBT::writeIBTPlt(uint8_t *buf, size_t numEntries) const {
935   writePltHeader(buf);
936   buf += IBTPltHeaderSize;
937 
938   const uint8_t inst[] = {
939       0xf3, 0x0f, 0x1e, 0xfa,    // endbr64
940       0x68, 0,    0,    0,    0, // pushq <relocation index>
941       0xe9, 0,    0,    0,    0, // jmpq plt[0]
942       0x66, 0x90,                // nop
943   };
944 
945   for (size_t i = 0; i < numEntries; ++i) {
946     memcpy(buf, inst, sizeof(inst));
947     write32le(buf + 5, i);
948     write32le(buf + 10, -pltHeaderSize - sizeof(inst) * i - 30);
949     buf += sizeof(inst);
950   }
951 }
952 
953 // These nonstandard PLT entries are to migtigate Spectre v2 security
954 // vulnerability. In order to mitigate Spectre v2, we want to avoid indirect
955 // branch instructions such as `jmp *GOTPLT(%rip)`. So, in the following PLT
956 // entries, we use a CALL followed by MOV and RET to do the same thing as an
957 // indirect jump. That instruction sequence is so-called "retpoline".
958 //
959 // We have two types of retpoline PLTs as a size optimization. If `-z now`
960 // is specified, all dynamic symbols are resolved at load-time. Thus, when
961 // that option is given, we can omit code for symbol lazy resolution.
962 namespace {
963 class Retpoline : public X86_64 {
964 public:
965   Retpoline();
966   void writeGotPlt(uint8_t *buf, const Symbol &s) const override;
967   void writePltHeader(uint8_t *buf) const override;
968   void writePlt(uint8_t *buf, const Symbol &sym,
969                 uint64_t pltEntryAddr) const override;
970 };
971 
972 class RetpolineZNow : public X86_64 {
973 public:
974   RetpolineZNow();
975   void writeGotPlt(uint8_t *buf, const Symbol &s) const override {}
976   void writePltHeader(uint8_t *buf) const override;
977   void writePlt(uint8_t *buf, const Symbol &sym,
978                 uint64_t pltEntryAddr) const override;
979 };
980 } // namespace
981 
982 Retpoline::Retpoline() {
983   pltHeaderSize = 48;
984   pltEntrySize = 32;
985   ipltEntrySize = 32;
986 }
987 
988 void Retpoline::writeGotPlt(uint8_t *buf, const Symbol &s) const {
989   write64le(buf, s.getPltVA() + 17);
990 }
991 
992 void Retpoline::writePltHeader(uint8_t *buf) const {
993   const uint8_t insn[] = {
994       0xff, 0x35, 0,    0,    0,    0,          // 0:    pushq GOTPLT+8(%rip)
995       0x4c, 0x8b, 0x1d, 0,    0,    0,    0,    // 6:    mov GOTPLT+16(%rip), %r11
996       0xe8, 0x0e, 0x00, 0x00, 0x00,             // d:    callq next
997       0xf3, 0x90,                               // 12: loop: pause
998       0x0f, 0xae, 0xe8,                         // 14:   lfence
999       0xeb, 0xf9,                               // 17:   jmp loop
1000       0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, // 19:   int3; .align 16
1001       0x4c, 0x89, 0x1c, 0x24,                   // 20: next: mov %r11, (%rsp)
1002       0xc3,                                     // 24:   ret
1003       0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, // 25:   int3; padding
1004       0xcc, 0xcc, 0xcc, 0xcc,                   // 2c:   int3; padding
1005   };
1006   memcpy(buf, insn, sizeof(insn));
1007 
1008   uint64_t gotPlt = in.gotPlt->getVA();
1009   uint64_t plt = in.plt->getVA();
1010   write32le(buf + 2, gotPlt - plt - 6 + 8);
1011   write32le(buf + 9, gotPlt - plt - 13 + 16);
1012 }
1013 
1014 void Retpoline::writePlt(uint8_t *buf, const Symbol &sym,
1015                          uint64_t pltEntryAddr) const {
1016   const uint8_t insn[] = {
1017       0x4c, 0x8b, 0x1d, 0, 0, 0, 0, // 0:  mov foo@GOTPLT(%rip), %r11
1018       0xe8, 0,    0,    0,    0,    // 7:  callq plt+0x20
1019       0xe9, 0,    0,    0,    0,    // c:  jmp plt+0x12
1020       0x68, 0,    0,    0,    0,    // 11: pushq <relocation index>
1021       0xe9, 0,    0,    0,    0,    // 16: jmp plt+0
1022       0xcc, 0xcc, 0xcc, 0xcc, 0xcc, // 1b: int3; padding
1023   };
1024   memcpy(buf, insn, sizeof(insn));
1025 
1026   uint64_t off = pltEntryAddr - in.plt->getVA();
1027 
1028   write32le(buf + 3, sym.getGotPltVA() - pltEntryAddr - 7);
1029   write32le(buf + 8, -off - 12 + 32);
1030   write32le(buf + 13, -off - 17 + 18);
1031   write32le(buf + 18, sym.pltIndex);
1032   write32le(buf + 23, -off - 27);
1033 }
1034 
1035 RetpolineZNow::RetpolineZNow() {
1036   pltHeaderSize = 32;
1037   pltEntrySize = 16;
1038   ipltEntrySize = 16;
1039 }
1040 
1041 void RetpolineZNow::writePltHeader(uint8_t *buf) const {
1042   const uint8_t insn[] = {
1043       0xe8, 0x0b, 0x00, 0x00, 0x00, // 0:    call next
1044       0xf3, 0x90,                   // 5:  loop: pause
1045       0x0f, 0xae, 0xe8,             // 7:    lfence
1046       0xeb, 0xf9,                   // a:    jmp loop
1047       0xcc, 0xcc, 0xcc, 0xcc,       // c:    int3; .align 16
1048       0x4c, 0x89, 0x1c, 0x24,       // 10: next: mov %r11, (%rsp)
1049       0xc3,                         // 14:   ret
1050       0xcc, 0xcc, 0xcc, 0xcc, 0xcc, // 15:   int3; padding
1051       0xcc, 0xcc, 0xcc, 0xcc, 0xcc, // 1a:   int3; padding
1052       0xcc,                         // 1f:   int3; padding
1053   };
1054   memcpy(buf, insn, sizeof(insn));
1055 }
1056 
1057 void RetpolineZNow::writePlt(uint8_t *buf, const Symbol &sym,
1058                              uint64_t pltEntryAddr) const {
1059   const uint8_t insn[] = {
1060       0x4c, 0x8b, 0x1d, 0,    0, 0, 0, // mov foo@GOTPLT(%rip), %r11
1061       0xe9, 0,    0,    0,    0,       // jmp plt+0
1062       0xcc, 0xcc, 0xcc, 0xcc,          // int3; padding
1063   };
1064   memcpy(buf, insn, sizeof(insn));
1065 
1066   write32le(buf + 3, sym.getGotPltVA() - pltEntryAddr - 7);
1067   write32le(buf + 8, in.plt->getVA() - pltEntryAddr - 12);
1068 }
1069 
1070 static TargetInfo *getTargetInfo() {
1071   if (config->zRetpolineplt) {
1072     if (config->zNow) {
1073       static RetpolineZNow t;
1074       return &t;
1075     }
1076     static Retpoline t;
1077     return &t;
1078   }
1079 
1080   if (config->andFeatures & GNU_PROPERTY_X86_FEATURE_1_IBT) {
1081     static IntelIBT t;
1082     return &t;
1083   }
1084 
1085   static X86_64 t;
1086   return &t;
1087 }
1088 
1089 TargetInfo *getX86_64TargetInfo() { return getTargetInfo(); }
1090 
1091 } // namespace elf
1092 } // namespace lld
1093