xref: /freebsd/contrib/llvm-project/lld/ELF/Arch/ARM.cpp (revision 62987288060ff68c817b7056815aa9fb8ba8ecd7)
10b57cec5SDimitry Andric //===- ARM.cpp ------------------------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
906c3fb27SDimitry Andric #include "InputFiles.h"
1006c3fb27SDimitry Andric #include "OutputSections.h"
1106c3fb27SDimitry Andric #include "SymbolTable.h"
120b57cec5SDimitry Andric #include "Symbols.h"
130b57cec5SDimitry Andric #include "SyntheticSections.h"
140b57cec5SDimitry Andric #include "Target.h"
150b57cec5SDimitry Andric #include "lld/Common/ErrorHandler.h"
1606c3fb27SDimitry Andric #include "lld/Common/Filesystem.h"
1781ad6265SDimitry Andric #include "llvm/BinaryFormat/ELF.h"
180b57cec5SDimitry Andric #include "llvm/Support/Endian.h"
190b57cec5SDimitry Andric 
200b57cec5SDimitry Andric using namespace llvm;
210b57cec5SDimitry Andric using namespace llvm::support::endian;
2206c3fb27SDimitry Andric using namespace llvm::support;
230b57cec5SDimitry Andric using namespace llvm::ELF;
245ffd83dbSDimitry Andric using namespace lld;
255ffd83dbSDimitry Andric using namespace lld::elf;
2606c3fb27SDimitry Andric using namespace llvm::object;
270b57cec5SDimitry Andric 
280b57cec5SDimitry Andric namespace {
290b57cec5SDimitry Andric class ARM final : public TargetInfo {
300b57cec5SDimitry Andric public:
310b57cec5SDimitry Andric   ARM();
320b57cec5SDimitry Andric   uint32_t calcEFlags() const override;
330b57cec5SDimitry Andric   RelExpr getRelExpr(RelType type, const Symbol &s,
340b57cec5SDimitry Andric                      const uint8_t *loc) const override;
350b57cec5SDimitry Andric   RelType getDynRel(RelType type) const override;
360b57cec5SDimitry Andric   int64_t getImplicitAddend(const uint8_t *buf, RelType type) const override;
370b57cec5SDimitry Andric   void writeGotPlt(uint8_t *buf, const Symbol &s) const override;
380b57cec5SDimitry Andric   void writeIgotPlt(uint8_t *buf, const Symbol &s) const override;
390b57cec5SDimitry Andric   void writePltHeader(uint8_t *buf) const override;
40480093f4SDimitry Andric   void writePlt(uint8_t *buf, const Symbol &sym,
41480093f4SDimitry Andric                 uint64_t pltEntryAddr) const override;
420b57cec5SDimitry Andric   void addPltSymbols(InputSection &isec, uint64_t off) const override;
430b57cec5SDimitry Andric   void addPltHeaderSymbols(InputSection &isd) const override;
440b57cec5SDimitry Andric   bool needsThunk(RelExpr expr, RelType type, const InputFile *file,
45480093f4SDimitry Andric                   uint64_t branchAddr, const Symbol &s,
46480093f4SDimitry Andric                   int64_t a) const override;
470b57cec5SDimitry Andric   uint32_t getThunkSectionSpacing() const override;
480b57cec5SDimitry Andric   bool inBranchRange(RelType type, uint64_t src, uint64_t dst) const override;
495ffd83dbSDimitry Andric   void relocate(uint8_t *loc, const Relocation &rel,
505ffd83dbSDimitry Andric                 uint64_t val) const override;
510b57cec5SDimitry Andric };
5206c3fb27SDimitry Andric enum class CodeState { Data = 0, Thumb = 2, Arm = 4 };
530b57cec5SDimitry Andric } // namespace
540b57cec5SDimitry Andric 
5506c3fb27SDimitry Andric static DenseMap<InputSection *, SmallVector<const Defined *, 0>> sectionMap{};
5606c3fb27SDimitry Andric 
ARM()570b57cec5SDimitry Andric ARM::ARM() {
580b57cec5SDimitry Andric   copyRel = R_ARM_COPY;
590b57cec5SDimitry Andric   relativeRel = R_ARM_RELATIVE;
600b57cec5SDimitry Andric   iRelativeRel = R_ARM_IRELATIVE;
610b57cec5SDimitry Andric   gotRel = R_ARM_GLOB_DAT;
620b57cec5SDimitry Andric   pltRel = R_ARM_JUMP_SLOT;
630b57cec5SDimitry Andric   symbolicRel = R_ARM_ABS32;
640b57cec5SDimitry Andric   tlsGotRel = R_ARM_TLS_TPOFF32;
650b57cec5SDimitry Andric   tlsModuleIndexRel = R_ARM_TLS_DTPMOD32;
660b57cec5SDimitry Andric   tlsOffsetRel = R_ARM_TLS_DTPOFF32;
670b57cec5SDimitry Andric   pltHeaderSize = 32;
68480093f4SDimitry Andric   pltEntrySize = 16;
69480093f4SDimitry Andric   ipltEntrySize = 16;
700b57cec5SDimitry Andric   trapInstr = {0xd4, 0xd4, 0xd4, 0xd4};
710b57cec5SDimitry Andric   needsThunks = true;
725ffd83dbSDimitry Andric   defaultMaxPageSize = 65536;
730b57cec5SDimitry Andric }
740b57cec5SDimitry Andric 
calcEFlags() const750b57cec5SDimitry Andric uint32_t ARM::calcEFlags() const {
760b57cec5SDimitry Andric   // The ABIFloatType is used by loaders to detect the floating point calling
770b57cec5SDimitry Andric   // convention.
780b57cec5SDimitry Andric   uint32_t abiFloatType = 0;
7906c3fb27SDimitry Andric 
8006c3fb27SDimitry Andric   // Set the EF_ARM_BE8 flag in the ELF header, if ELF file is big-endian
8106c3fb27SDimitry Andric   // with BE-8 code.
8206c3fb27SDimitry Andric   uint32_t armBE8 = 0;
8306c3fb27SDimitry Andric 
840b57cec5SDimitry Andric   if (config->armVFPArgs == ARMVFPArgKind::Base ||
850b57cec5SDimitry Andric       config->armVFPArgs == ARMVFPArgKind::Default)
860b57cec5SDimitry Andric     abiFloatType = EF_ARM_ABI_FLOAT_SOFT;
870b57cec5SDimitry Andric   else if (config->armVFPArgs == ARMVFPArgKind::VFP)
880b57cec5SDimitry Andric     abiFloatType = EF_ARM_ABI_FLOAT_HARD;
890b57cec5SDimitry Andric 
9006c3fb27SDimitry Andric   if (!config->isLE && config->armBe8)
9106c3fb27SDimitry Andric     armBE8 = EF_ARM_BE8;
9206c3fb27SDimitry Andric 
930b57cec5SDimitry Andric   // We don't currently use any features incompatible with EF_ARM_EABI_VER5,
940b57cec5SDimitry Andric   // but we don't have any firm guarantees of conformance. Linux AArch64
950b57cec5SDimitry Andric   // kernels (as of 2016) require an EABI version to be set.
9606c3fb27SDimitry Andric   return EF_ARM_EABI_VER5 | abiFloatType | armBE8;
970b57cec5SDimitry Andric }
980b57cec5SDimitry Andric 
getRelExpr(RelType type,const Symbol & s,const uint8_t * loc) const990b57cec5SDimitry Andric RelExpr ARM::getRelExpr(RelType type, const Symbol &s,
1000b57cec5SDimitry Andric                         const uint8_t *loc) const {
1010b57cec5SDimitry Andric   switch (type) {
102349cc55cSDimitry Andric   case R_ARM_ABS32:
103349cc55cSDimitry Andric   case R_ARM_MOVW_ABS_NC:
104349cc55cSDimitry Andric   case R_ARM_MOVT_ABS:
105349cc55cSDimitry Andric   case R_ARM_THM_MOVW_ABS_NC:
106349cc55cSDimitry Andric   case R_ARM_THM_MOVT_ABS:
10706c3fb27SDimitry Andric   case R_ARM_THM_ALU_ABS_G0_NC:
10806c3fb27SDimitry Andric   case R_ARM_THM_ALU_ABS_G1_NC:
10906c3fb27SDimitry Andric   case R_ARM_THM_ALU_ABS_G2_NC:
11006c3fb27SDimitry Andric   case R_ARM_THM_ALU_ABS_G3:
111349cc55cSDimitry Andric     return R_ABS;
112349cc55cSDimitry Andric   case R_ARM_THM_JUMP8:
1130b57cec5SDimitry Andric   case R_ARM_THM_JUMP11:
1140b57cec5SDimitry Andric     return R_PC;
1150b57cec5SDimitry Andric   case R_ARM_CALL:
1160b57cec5SDimitry Andric   case R_ARM_JUMP24:
1170b57cec5SDimitry Andric   case R_ARM_PC24:
1180b57cec5SDimitry Andric   case R_ARM_PLT32:
1190b57cec5SDimitry Andric   case R_ARM_PREL31:
1200b57cec5SDimitry Andric   case R_ARM_THM_JUMP19:
1210b57cec5SDimitry Andric   case R_ARM_THM_JUMP24:
1220b57cec5SDimitry Andric   case R_ARM_THM_CALL:
1230b57cec5SDimitry Andric     return R_PLT_PC;
1240b57cec5SDimitry Andric   case R_ARM_GOTOFF32:
1250b57cec5SDimitry Andric     // (S + A) - GOT_ORG
1260b57cec5SDimitry Andric     return R_GOTREL;
1270b57cec5SDimitry Andric   case R_ARM_GOT_BREL:
1280b57cec5SDimitry Andric     // GOT(S) + A - GOT_ORG
1290b57cec5SDimitry Andric     return R_GOT_OFF;
1300b57cec5SDimitry Andric   case R_ARM_GOT_PREL:
1310b57cec5SDimitry Andric   case R_ARM_TLS_IE32:
1320b57cec5SDimitry Andric     // GOT(S) + A - P
1330b57cec5SDimitry Andric     return R_GOT_PC;
1340b57cec5SDimitry Andric   case R_ARM_SBREL32:
1350b57cec5SDimitry Andric     return R_ARM_SBREL;
1360b57cec5SDimitry Andric   case R_ARM_TARGET1:
1370b57cec5SDimitry Andric     return config->target1Rel ? R_PC : R_ABS;
1380b57cec5SDimitry Andric   case R_ARM_TARGET2:
1390b57cec5SDimitry Andric     if (config->target2 == Target2Policy::Rel)
1400b57cec5SDimitry Andric       return R_PC;
1410b57cec5SDimitry Andric     if (config->target2 == Target2Policy::Abs)
1420b57cec5SDimitry Andric       return R_ABS;
1430b57cec5SDimitry Andric     return R_GOT_PC;
1440b57cec5SDimitry Andric   case R_ARM_TLS_GD32:
1450b57cec5SDimitry Andric     return R_TLSGD_PC;
1460b57cec5SDimitry Andric   case R_ARM_TLS_LDM32:
1470b57cec5SDimitry Andric     return R_TLSLD_PC;
1485ffd83dbSDimitry Andric   case R_ARM_TLS_LDO32:
1495ffd83dbSDimitry Andric     return R_DTPREL;
1500b57cec5SDimitry Andric   case R_ARM_BASE_PREL:
1510b57cec5SDimitry Andric     // B(S) + A - P
1520b57cec5SDimitry Andric     // FIXME: currently B(S) assumed to be .got, this may not hold for all
1530b57cec5SDimitry Andric     // platforms.
1540b57cec5SDimitry Andric     return R_GOTONLY_PC;
1550b57cec5SDimitry Andric   case R_ARM_MOVW_PREL_NC:
1560b57cec5SDimitry Andric   case R_ARM_MOVT_PREL:
1570b57cec5SDimitry Andric   case R_ARM_REL32:
1580b57cec5SDimitry Andric   case R_ARM_THM_MOVW_PREL_NC:
1590b57cec5SDimitry Andric   case R_ARM_THM_MOVT_PREL:
1600b57cec5SDimitry Andric     return R_PC;
1615ffd83dbSDimitry Andric   case R_ARM_ALU_PC_G0:
1624824e7fdSDimitry Andric   case R_ARM_ALU_PC_G0_NC:
1634824e7fdSDimitry Andric   case R_ARM_ALU_PC_G1:
1644824e7fdSDimitry Andric   case R_ARM_ALU_PC_G1_NC:
1654824e7fdSDimitry Andric   case R_ARM_ALU_PC_G2:
1665ffd83dbSDimitry Andric   case R_ARM_LDR_PC_G0:
1674824e7fdSDimitry Andric   case R_ARM_LDR_PC_G1:
1684824e7fdSDimitry Andric   case R_ARM_LDR_PC_G2:
1694824e7fdSDimitry Andric   case R_ARM_LDRS_PC_G0:
1704824e7fdSDimitry Andric   case R_ARM_LDRS_PC_G1:
1714824e7fdSDimitry Andric   case R_ARM_LDRS_PC_G2:
1725ffd83dbSDimitry Andric   case R_ARM_THM_ALU_PREL_11_0:
1735ffd83dbSDimitry Andric   case R_ARM_THM_PC8:
1745ffd83dbSDimitry Andric   case R_ARM_THM_PC12:
1755ffd83dbSDimitry Andric     return R_ARM_PCA;
1765ffd83dbSDimitry Andric   case R_ARM_MOVW_BREL_NC:
1775ffd83dbSDimitry Andric   case R_ARM_MOVW_BREL:
1785ffd83dbSDimitry Andric   case R_ARM_MOVT_BREL:
1795ffd83dbSDimitry Andric   case R_ARM_THM_MOVW_BREL_NC:
1805ffd83dbSDimitry Andric   case R_ARM_THM_MOVW_BREL:
1815ffd83dbSDimitry Andric   case R_ARM_THM_MOVT_BREL:
1825ffd83dbSDimitry Andric     return R_ARM_SBREL;
1830b57cec5SDimitry Andric   case R_ARM_NONE:
1840b57cec5SDimitry Andric     return R_NONE;
1850b57cec5SDimitry Andric   case R_ARM_TLS_LE32:
186e8d8bef9SDimitry Andric     return R_TPREL;
1870b57cec5SDimitry Andric   case R_ARM_V4BX:
1880b57cec5SDimitry Andric     // V4BX is just a marker to indicate there's a "bx rN" instruction at the
1890b57cec5SDimitry Andric     // given address. It can be used to implement a special linker mode which
1900b57cec5SDimitry Andric     // rewrites ARMv4T inputs to ARMv4. Since we support only ARMv4 input and
1910b57cec5SDimitry Andric     // not ARMv4 output, we can just ignore it.
192480093f4SDimitry Andric     return R_NONE;
1930b57cec5SDimitry Andric   default:
194349cc55cSDimitry Andric     error(getErrorLocation(loc) + "unknown relocation (" + Twine(type) +
195349cc55cSDimitry Andric           ") against symbol " + toString(s));
196349cc55cSDimitry Andric     return R_NONE;
1970b57cec5SDimitry Andric   }
1980b57cec5SDimitry Andric }
1990b57cec5SDimitry Andric 
getDynRel(RelType type) const2000b57cec5SDimitry Andric RelType ARM::getDynRel(RelType type) const {
2010b57cec5SDimitry Andric   if ((type == R_ARM_ABS32) || (type == R_ARM_TARGET1 && !config->target1Rel))
2020b57cec5SDimitry Andric     return R_ARM_ABS32;
2030b57cec5SDimitry Andric   return R_ARM_NONE;
2040b57cec5SDimitry Andric }
2050b57cec5SDimitry Andric 
writeGotPlt(uint8_t * buf,const Symbol &) const2060b57cec5SDimitry Andric void ARM::writeGotPlt(uint8_t *buf, const Symbol &) const {
20706c3fb27SDimitry Andric   write32(buf, in.plt->getVA());
2080b57cec5SDimitry Andric }
2090b57cec5SDimitry Andric 
writeIgotPlt(uint8_t * buf,const Symbol & s) const2100b57cec5SDimitry Andric void ARM::writeIgotPlt(uint8_t *buf, const Symbol &s) const {
2110b57cec5SDimitry Andric   // An ARM entry is the address of the ifunc resolver function.
21206c3fb27SDimitry Andric   write32(buf, s.getVA());
2130b57cec5SDimitry Andric }
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric // Long form PLT Header that does not have any restrictions on the displacement
216bdd1243dSDimitry Andric // of the .plt from the .got.plt.
writePltHeaderLong(uint8_t * buf)2170b57cec5SDimitry Andric static void writePltHeaderLong(uint8_t *buf) {
21806c3fb27SDimitry Andric   write32(buf + 0, 0xe52de004);   //     str lr, [sp,#-4]!
21906c3fb27SDimitry Andric   write32(buf + 4, 0xe59fe004);   //     ldr lr, L2
22006c3fb27SDimitry Andric   write32(buf + 8, 0xe08fe00e);   // L1: add lr, pc, lr
22106c3fb27SDimitry Andric   write32(buf + 12, 0xe5bef008);  //     ldr pc, [lr, #8]
22206c3fb27SDimitry Andric   write32(buf + 16, 0x00000000);  // L2: .word   &(.got.plt) - L1 - 8
22306c3fb27SDimitry Andric   write32(buf + 20, 0xd4d4d4d4);  //     Pad to 32-byte boundary
22406c3fb27SDimitry Andric   write32(buf + 24, 0xd4d4d4d4);  //     Pad to 32-byte boundary
22506c3fb27SDimitry Andric   write32(buf + 28, 0xd4d4d4d4);
2260b57cec5SDimitry Andric   uint64_t gotPlt = in.gotPlt->getVA();
2270b57cec5SDimitry Andric   uint64_t l1 = in.plt->getVA() + 8;
22806c3fb27SDimitry Andric   write32(buf + 16, gotPlt - l1 - 8);
2290b57cec5SDimitry Andric }
2300b57cec5SDimitry Andric 
231*62987288SDimitry Andric // True if we should use Thumb PLTs, which currently require Thumb2, and are
232*62987288SDimitry Andric // only used if the target does not have the ARM ISA.
useThumbPLTs()233*62987288SDimitry Andric static bool useThumbPLTs() {
234*62987288SDimitry Andric   return config->armHasThumb2ISA && !config->armHasArmISA;
235*62987288SDimitry Andric }
236*62987288SDimitry Andric 
237bdd1243dSDimitry Andric // The default PLT header requires the .got.plt to be within 128 Mb of the
2380b57cec5SDimitry Andric // .plt in the positive direction.
writePltHeader(uint8_t * buf) const2390b57cec5SDimitry Andric void ARM::writePltHeader(uint8_t *buf) const {
240*62987288SDimitry Andric   if (useThumbPLTs()) {
2410fca6ea1SDimitry Andric     // The instruction sequence for thumb:
2420fca6ea1SDimitry Andric     //
2430fca6ea1SDimitry Andric     // 0: b500          push    {lr}
2440fca6ea1SDimitry Andric     // 2: f8df e008     ldr.w   lr, [pc, #0x8]          @ 0xe <func+0xe>
2450fca6ea1SDimitry Andric     // 6: 44fe          add     lr, pc
2460fca6ea1SDimitry Andric     // 8: f85e ff08     ldr     pc, [lr, #8]!
2470fca6ea1SDimitry Andric     // e:               .word   .got.plt - .plt - 16
2480fca6ea1SDimitry Andric     //
2490fca6ea1SDimitry Andric     // At 0x8, we want to jump to .got.plt, the -16 accounts for 8 bytes from
2500fca6ea1SDimitry Andric     // `pc` in the add instruction and 8 bytes for the `lr` adjustment.
2510fca6ea1SDimitry Andric     //
2520fca6ea1SDimitry Andric     uint64_t offset = in.gotPlt->getVA() - in.plt->getVA() - 16;
2530fca6ea1SDimitry Andric     assert(llvm::isUInt<32>(offset) && "This should always fit into a 32-bit offset");
2540fca6ea1SDimitry Andric     write16(buf + 0, 0xb500);
2550fca6ea1SDimitry Andric     // Split into two halves to support endianness correctly.
2560fca6ea1SDimitry Andric     write16(buf + 2, 0xf8df);
2570fca6ea1SDimitry Andric     write16(buf + 4, 0xe008);
2580fca6ea1SDimitry Andric     write16(buf + 6, 0x44fe);
2590fca6ea1SDimitry Andric     // Split into two halves to support endianness correctly.
2600fca6ea1SDimitry Andric     write16(buf + 8, 0xf85e);
2610fca6ea1SDimitry Andric     write16(buf + 10, 0xff08);
2620fca6ea1SDimitry Andric     write32(buf + 12, offset);
2630fca6ea1SDimitry Andric 
2640fca6ea1SDimitry Andric     memcpy(buf + 16, trapInstr.data(), 4);  // Pad to 32-byte boundary
2650fca6ea1SDimitry Andric     memcpy(buf + 20, trapInstr.data(), 4);
2660fca6ea1SDimitry Andric     memcpy(buf + 24, trapInstr.data(), 4);
2670fca6ea1SDimitry Andric     memcpy(buf + 28, trapInstr.data(), 4);
2680fca6ea1SDimitry Andric   } else {
2690fca6ea1SDimitry Andric     // Use a similar sequence to that in writePlt(), the difference is the
2700fca6ea1SDimitry Andric     // calling conventions mean we use lr instead of ip. The PLT entry is
2710fca6ea1SDimitry Andric     // responsible for saving lr on the stack, the dynamic loader is responsible
2720fca6ea1SDimitry Andric     // for reloading it.
2730b57cec5SDimitry Andric     const uint32_t pltData[] = {
2740b57cec5SDimitry Andric         0xe52de004, // L1: str lr, [sp,#-4]!
2750b57cec5SDimitry Andric         0xe28fe600, //     add lr, pc,  #0x0NN00000 &(.got.plt - L1 - 4)
2760b57cec5SDimitry Andric         0xe28eea00, //     add lr, lr,  #0x000NN000 &(.got.plt - L1 - 4)
2770b57cec5SDimitry Andric         0xe5bef000, //     ldr pc, [lr, #0x00000NNN] &(.got.plt -L1 - 4)
2780b57cec5SDimitry Andric     };
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric     uint64_t offset = in.gotPlt->getVA() - in.plt->getVA() - 4;
2810b57cec5SDimitry Andric     if (!llvm::isUInt<27>(offset)) {
2820b57cec5SDimitry Andric       // We cannot encode the Offset, use the long form.
2830b57cec5SDimitry Andric       writePltHeaderLong(buf);
2840b57cec5SDimitry Andric       return;
2850b57cec5SDimitry Andric     }
28606c3fb27SDimitry Andric     write32(buf + 0, pltData[0]);
28706c3fb27SDimitry Andric     write32(buf + 4, pltData[1] | ((offset >> 20) & 0xff));
28806c3fb27SDimitry Andric     write32(buf + 8, pltData[2] | ((offset >> 12) & 0xff));
28906c3fb27SDimitry Andric     write32(buf + 12, pltData[3] | (offset & 0xfff));
2900b57cec5SDimitry Andric     memcpy(buf + 16, trapInstr.data(), 4); // Pad to 32-byte boundary
2910b57cec5SDimitry Andric     memcpy(buf + 20, trapInstr.data(), 4);
2920b57cec5SDimitry Andric     memcpy(buf + 24, trapInstr.data(), 4);
2930b57cec5SDimitry Andric     memcpy(buf + 28, trapInstr.data(), 4);
2940b57cec5SDimitry Andric   }
2950fca6ea1SDimitry Andric }
2960b57cec5SDimitry Andric 
addPltHeaderSymbols(InputSection & isec) const2970b57cec5SDimitry Andric void ARM::addPltHeaderSymbols(InputSection &isec) const {
298*62987288SDimitry Andric   if (useThumbPLTs()) {
2990fca6ea1SDimitry Andric     addSyntheticLocal("$t", STT_NOTYPE, 0, 0, isec);
3000fca6ea1SDimitry Andric     addSyntheticLocal("$d", STT_NOTYPE, 12, 0, isec);
3010fca6ea1SDimitry Andric   } else {
3020b57cec5SDimitry Andric     addSyntheticLocal("$a", STT_NOTYPE, 0, 0, isec);
3030b57cec5SDimitry Andric     addSyntheticLocal("$d", STT_NOTYPE, 16, 0, isec);
3040b57cec5SDimitry Andric   }
3050fca6ea1SDimitry Andric }
3060b57cec5SDimitry Andric 
3070b57cec5SDimitry Andric // Long form PLT entries that do not have any restrictions on the displacement
308bdd1243dSDimitry Andric // of the .plt from the .got.plt.
writePltLong(uint8_t * buf,uint64_t gotPltEntryAddr,uint64_t pltEntryAddr)3090b57cec5SDimitry Andric static void writePltLong(uint8_t *buf, uint64_t gotPltEntryAddr,
310480093f4SDimitry Andric                          uint64_t pltEntryAddr) {
31106c3fb27SDimitry Andric   write32(buf + 0, 0xe59fc004);   //     ldr ip, L2
31206c3fb27SDimitry Andric   write32(buf + 4, 0xe08cc00f);   // L1: add ip, ip, pc
31306c3fb27SDimitry Andric   write32(buf + 8, 0xe59cf000);   //     ldr pc, [ip]
31406c3fb27SDimitry Andric   write32(buf + 12, 0x00000000);  // L2: .word   Offset(&(.got.plt) - L1 - 8
3150b57cec5SDimitry Andric   uint64_t l1 = pltEntryAddr + 4;
31606c3fb27SDimitry Andric   write32(buf + 12, gotPltEntryAddr - l1 - 8);
3170b57cec5SDimitry Andric }
3180b57cec5SDimitry Andric 
319bdd1243dSDimitry Andric // The default PLT entries require the .got.plt to be within 128 Mb of the
3200b57cec5SDimitry Andric // .plt in the positive direction.
writePlt(uint8_t * buf,const Symbol & sym,uint64_t pltEntryAddr) const321480093f4SDimitry Andric void ARM::writePlt(uint8_t *buf, const Symbol &sym,
322480093f4SDimitry Andric                    uint64_t pltEntryAddr) const {
3230fca6ea1SDimitry Andric 
324*62987288SDimitry Andric   if (!useThumbPLTs()) {
3250fca6ea1SDimitry Andric     uint64_t offset = sym.getGotPltVA() - pltEntryAddr - 8;
3260fca6ea1SDimitry Andric 
3270b57cec5SDimitry Andric     // The PLT entry is similar to the example given in Appendix A of ELF for
3280b57cec5SDimitry Andric     // the Arm Architecture. Instead of using the Group Relocations to find the
3290b57cec5SDimitry Andric     // optimal rotation for the 8-bit immediate used in the add instructions we
3300b57cec5SDimitry Andric     // hard code the most compact rotations for simplicity. This saves a load
3310b57cec5SDimitry Andric     // instruction over the long plt sequences.
3320b57cec5SDimitry Andric     const uint32_t pltData[] = {
333bdd1243dSDimitry Andric         0xe28fc600, // L1: add ip, pc,  #0x0NN00000  Offset(&(.got.plt) - L1 - 8
334bdd1243dSDimitry Andric         0xe28cca00, //     add ip, ip,  #0x000NN000  Offset(&(.got.plt) - L1 - 8
335bdd1243dSDimitry Andric         0xe5bcf000, //     ldr pc, [ip, #0x00000NNN] Offset(&(.got.plt) - L1 - 8
3360b57cec5SDimitry Andric     };
3370b57cec5SDimitry Andric     if (!llvm::isUInt<27>(offset)) {
3380b57cec5SDimitry Andric       // We cannot encode the Offset, use the long form.
339480093f4SDimitry Andric       writePltLong(buf, sym.getGotPltVA(), pltEntryAddr);
3400b57cec5SDimitry Andric       return;
3410b57cec5SDimitry Andric     }
34206c3fb27SDimitry Andric     write32(buf + 0, pltData[0] | ((offset >> 20) & 0xff));
34306c3fb27SDimitry Andric     write32(buf + 4, pltData[1] | ((offset >> 12) & 0xff));
34406c3fb27SDimitry Andric     write32(buf + 8, pltData[2] | (offset & 0xfff));
3450b57cec5SDimitry Andric     memcpy(buf + 12, trapInstr.data(), 4); // Pad to 16-byte boundary
3460fca6ea1SDimitry Andric   } else {
3470fca6ea1SDimitry Andric     uint64_t offset = sym.getGotPltVA() - pltEntryAddr - 12;
3480fca6ea1SDimitry Andric     assert(llvm::isUInt<32>(offset) && "This should always fit into a 32-bit offset");
3490fca6ea1SDimitry Andric 
3500fca6ea1SDimitry Andric     // A PLT entry will be:
3510fca6ea1SDimitry Andric     //
3520fca6ea1SDimitry Andric     //       movw ip, #<lower 16 bits>
3530fca6ea1SDimitry Andric     //       movt ip, #<upper 16 bits>
3540fca6ea1SDimitry Andric     //       add ip, pc
3550fca6ea1SDimitry Andric     //   L1: ldr.w pc, [ip]
3560fca6ea1SDimitry Andric     //       b L1
3570fca6ea1SDimitry Andric     //
3580fca6ea1SDimitry Andric     // where ip = r12 = 0xc
3590fca6ea1SDimitry Andric 
3600fca6ea1SDimitry Andric     // movw ip, #<lower 16 bits>
3610fca6ea1SDimitry Andric     write16(buf + 2, 0x0c00); // use `ip`
3620fca6ea1SDimitry Andric     relocateNoSym(buf, R_ARM_THM_MOVW_ABS_NC, offset);
3630fca6ea1SDimitry Andric 
3640fca6ea1SDimitry Andric     // movt ip, #<upper 16 bits>
3650fca6ea1SDimitry Andric     write16(buf + 6, 0x0c00); // use `ip`
3660fca6ea1SDimitry Andric     relocateNoSym(buf + 4, R_ARM_THM_MOVT_ABS, offset);
3670fca6ea1SDimitry Andric 
3680fca6ea1SDimitry Andric     write16(buf + 8, 0x44fc);       // add ip, pc
3690fca6ea1SDimitry Andric     write16(buf + 10, 0xf8dc);      // ldr.w   pc, [ip] (bottom half)
3700fca6ea1SDimitry Andric     write16(buf + 12, 0xf000);      // ldr.w   pc, [ip] (upper half)
3710fca6ea1SDimitry Andric     write16(buf + 14, 0xe7fc);      // Branch to previous instruction
3720fca6ea1SDimitry Andric   }
3730b57cec5SDimitry Andric }
3740b57cec5SDimitry Andric 
addPltSymbols(InputSection & isec,uint64_t off) const3750b57cec5SDimitry Andric void ARM::addPltSymbols(InputSection &isec, uint64_t off) const {
376*62987288SDimitry Andric   if (useThumbPLTs()) {
3770fca6ea1SDimitry Andric     addSyntheticLocal("$t", STT_NOTYPE, off, 0, isec);
3780fca6ea1SDimitry Andric   } else {
3790b57cec5SDimitry Andric     addSyntheticLocal("$a", STT_NOTYPE, off, 0, isec);
3800b57cec5SDimitry Andric     addSyntheticLocal("$d", STT_NOTYPE, off + 12, 0, isec);
3810b57cec5SDimitry Andric   }
3820fca6ea1SDimitry Andric }
3830b57cec5SDimitry Andric 
needsThunk(RelExpr expr,RelType type,const InputFile * file,uint64_t branchAddr,const Symbol & s,int64_t a) const3840b57cec5SDimitry Andric bool ARM::needsThunk(RelExpr expr, RelType type, const InputFile *file,
3855ffd83dbSDimitry Andric                      uint64_t branchAddr, const Symbol &s,
386fe6060f1SDimitry Andric                      int64_t a) const {
3872a66634dSDimitry Andric   // If s is an undefined weak symbol and does not have a PLT entry then it will
3882a66634dSDimitry Andric   // be resolved as a branch to the next instruction. If it is hidden, its
3892a66634dSDimitry Andric   // binding has been converted to local, so we just check isUndefined() here. A
3902a66634dSDimitry Andric   // undefined non-weak symbol will have been errored.
3912a66634dSDimitry Andric   if (s.isUndefined() && !s.isInPlt())
3920b57cec5SDimitry Andric     return false;
3930b57cec5SDimitry Andric   // A state change from ARM to Thumb and vice versa must go through an
3940b57cec5SDimitry Andric   // interworking thunk if the relocation type is not R_ARM_CALL or
3950b57cec5SDimitry Andric   // R_ARM_THM_CALL.
3960b57cec5SDimitry Andric   switch (type) {
3970b57cec5SDimitry Andric   case R_ARM_PC24:
3980b57cec5SDimitry Andric   case R_ARM_PLT32:
3990b57cec5SDimitry Andric   case R_ARM_JUMP24:
4000b57cec5SDimitry Andric     // Source is ARM, all PLT entries are ARM so no interworking required.
40113138422SDimitry Andric     // Otherwise we need to interwork if STT_FUNC Symbol has bit 0 set (Thumb).
402*62987288SDimitry Andric     assert(!useThumbPLTs() &&
4030fca6ea1SDimitry Andric            "If the source is ARM, we should not need Thumb PLTs");
40413138422SDimitry Andric     if (s.isFunc() && expr == R_PC && (s.getVA() & 1))
4050b57cec5SDimitry Andric       return true;
406bdd1243dSDimitry Andric     [[fallthrough]];
4070b57cec5SDimitry Andric   case R_ARM_CALL: {
4080b57cec5SDimitry Andric     uint64_t dst = (expr == R_PLT_PC) ? s.getPltVA() : s.getVA();
409bdd1243dSDimitry Andric     return !inBranchRange(type, branchAddr, dst + a) ||
410bdd1243dSDimitry Andric         (!config->armHasBlx && (s.getVA() & 1));
4110b57cec5SDimitry Andric   }
4120b57cec5SDimitry Andric   case R_ARM_THM_JUMP19:
4130b57cec5SDimitry Andric   case R_ARM_THM_JUMP24:
4140fca6ea1SDimitry Andric     // Source is Thumb, when all PLT entries are ARM interworking is required.
41513138422SDimitry Andric     // Otherwise we need to interwork if STT_FUNC Symbol has bit 0 clear (ARM).
416*62987288SDimitry Andric     if ((expr == R_PLT_PC && !useThumbPLTs()) ||
417*62987288SDimitry Andric         (s.isFunc() && (s.getVA() & 1) == 0))
4180b57cec5SDimitry Andric       return true;
419bdd1243dSDimitry Andric     [[fallthrough]];
4200b57cec5SDimitry Andric   case R_ARM_THM_CALL: {
4210b57cec5SDimitry Andric     uint64_t dst = (expr == R_PLT_PC) ? s.getPltVA() : s.getVA();
422bdd1243dSDimitry Andric     return !inBranchRange(type, branchAddr, dst + a) ||
423bdd1243dSDimitry Andric         (!config->armHasBlx && (s.getVA() & 1) == 0);;
4240b57cec5SDimitry Andric   }
4250b57cec5SDimitry Andric   }
4260b57cec5SDimitry Andric   return false;
4270b57cec5SDimitry Andric }
4280b57cec5SDimitry Andric 
getThunkSectionSpacing() const4290b57cec5SDimitry Andric uint32_t ARM::getThunkSectionSpacing() const {
4300b57cec5SDimitry Andric   // The placing of pre-created ThunkSections is controlled by the value
4310b57cec5SDimitry Andric   // thunkSectionSpacing returned by getThunkSectionSpacing(). The aim is to
4320b57cec5SDimitry Andric   // place the ThunkSection such that all branches from the InputSections
4330b57cec5SDimitry Andric   // prior to the ThunkSection can reach a Thunk placed at the end of the
4340b57cec5SDimitry Andric   // ThunkSection. Graphically:
4350b57cec5SDimitry Andric   // | up to thunkSectionSpacing .text input sections |
4360b57cec5SDimitry Andric   // | ThunkSection                                   |
4370b57cec5SDimitry Andric   // | up to thunkSectionSpacing .text input sections |
4380b57cec5SDimitry Andric   // | ThunkSection                                   |
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric   // Pre-created ThunkSections are spaced roughly 16MiB apart on ARMv7. This
4410b57cec5SDimitry Andric   // is to match the most common expected case of a Thumb 2 encoded BL, BLX or
4420b57cec5SDimitry Andric   // B.W:
4430b57cec5SDimitry Andric   // ARM B, BL, BLX range +/- 32MiB
4440b57cec5SDimitry Andric   // Thumb B.W, BL, BLX range +/- 16MiB
4450b57cec5SDimitry Andric   // Thumb B<cc>.W range +/- 1MiB
4460b57cec5SDimitry Andric   // If a branch cannot reach a pre-created ThunkSection a new one will be
4470b57cec5SDimitry Andric   // created so we can handle the rare cases of a Thumb 2 conditional branch.
4480b57cec5SDimitry Andric   // We intentionally use a lower size for thunkSectionSpacing than the maximum
4490b57cec5SDimitry Andric   // branch range so the end of the ThunkSection is more likely to be within
4500b57cec5SDimitry Andric   // range of the branch instruction that is furthest away. The value we shorten
4510b57cec5SDimitry Andric   // thunkSectionSpacing by is set conservatively to allow us to create 16,384
4520b57cec5SDimitry Andric   // 12 byte Thunks at any offset in a ThunkSection without risk of a branch to
4530b57cec5SDimitry Andric   // one of the Thunks going out of range.
4540b57cec5SDimitry Andric 
4550b57cec5SDimitry Andric   // On Arm the thunkSectionSpacing depends on the range of the Thumb Branch
4560b57cec5SDimitry Andric   // range. On earlier Architectures such as ARMv4, ARMv5 and ARMv6 (except
4570b57cec5SDimitry Andric   // ARMv6T2) the range is +/- 4MiB.
4580b57cec5SDimitry Andric 
4590b57cec5SDimitry Andric   return (config->armJ1J2BranchEncoding) ? 0x1000000 - 0x30000
4600b57cec5SDimitry Andric                                          : 0x400000 - 0x7500;
4610b57cec5SDimitry Andric }
4620b57cec5SDimitry Andric 
inBranchRange(RelType type,uint64_t src,uint64_t dst) const4630b57cec5SDimitry Andric bool ARM::inBranchRange(RelType type, uint64_t src, uint64_t dst) const {
4640b57cec5SDimitry Andric   if ((dst & 0x1) == 0)
4650b57cec5SDimitry Andric     // Destination is ARM, if ARM caller then Src is already 4-byte aligned.
4660b57cec5SDimitry Andric     // If Thumb Caller (BLX) the Src address has bottom 2 bits cleared to ensure
4670b57cec5SDimitry Andric     // destination will be 4 byte aligned.
4680b57cec5SDimitry Andric     src &= ~0x3;
4690b57cec5SDimitry Andric   else
470fe6060f1SDimitry Andric     // Bit 0 == 1 denotes Thumb state, it is not part of the range.
4710b57cec5SDimitry Andric     dst &= ~0x1;
4720b57cec5SDimitry Andric 
473fe6060f1SDimitry Andric   int64_t offset = dst - src;
474fe6060f1SDimitry Andric   switch (type) {
475fe6060f1SDimitry Andric   case R_ARM_PC24:
476fe6060f1SDimitry Andric   case R_ARM_PLT32:
477fe6060f1SDimitry Andric   case R_ARM_JUMP24:
478fe6060f1SDimitry Andric   case R_ARM_CALL:
479fe6060f1SDimitry Andric     return llvm::isInt<26>(offset);
480fe6060f1SDimitry Andric   case R_ARM_THM_JUMP19:
481fe6060f1SDimitry Andric     return llvm::isInt<21>(offset);
482fe6060f1SDimitry Andric   case R_ARM_THM_JUMP24:
483fe6060f1SDimitry Andric   case R_ARM_THM_CALL:
484fe6060f1SDimitry Andric     return config->armJ1J2BranchEncoding ? llvm::isInt<25>(offset)
485fe6060f1SDimitry Andric                                          : llvm::isInt<23>(offset);
486fe6060f1SDimitry Andric   default:
487fe6060f1SDimitry Andric     return true;
488fe6060f1SDimitry Andric   }
4890b57cec5SDimitry Andric }
4900b57cec5SDimitry Andric 
4915ffd83dbSDimitry Andric // Helper to produce message text when LLD detects that a CALL relocation to
4925ffd83dbSDimitry Andric // a non STT_FUNC symbol that may result in incorrect interworking between ARM
4935ffd83dbSDimitry Andric // or Thumb.
stateChangeWarning(uint8_t * loc,RelType relt,const Symbol & s)4945ffd83dbSDimitry Andric static void stateChangeWarning(uint8_t *loc, RelType relt, const Symbol &s) {
4955ffd83dbSDimitry Andric   assert(!s.isFunc());
496349cc55cSDimitry Andric   const ErrorPlace place = getErrorPlace(loc);
497349cc55cSDimitry Andric   std::string hint;
498349cc55cSDimitry Andric   if (!place.srcLoc.empty())
499349cc55cSDimitry Andric     hint = "; " + place.srcLoc;
5005ffd83dbSDimitry Andric   if (s.isSection()) {
5015ffd83dbSDimitry Andric     // Section symbols must be defined and in a section. Users cannot change
5025ffd83dbSDimitry Andric     // the type. Use the section name as getName() returns an empty string.
503349cc55cSDimitry Andric     warn(place.loc + "branch and link relocation: " + toString(relt) +
504349cc55cSDimitry Andric          " to STT_SECTION symbol " + cast<Defined>(s).section->name +
505349cc55cSDimitry Andric          " ; interworking not performed" + hint);
5065ffd83dbSDimitry Andric   } else {
5075ffd83dbSDimitry Andric     // Warn with hint on how to alter the symbol type.
5085ffd83dbSDimitry Andric     warn(getErrorLocation(loc) + "branch and link relocation: " +
5095ffd83dbSDimitry Andric          toString(relt) + " to non STT_FUNC symbol: " + s.getName() +
5105ffd83dbSDimitry Andric          " interworking not performed; consider using directive '.type " +
5115ffd83dbSDimitry Andric          s.getName() +
512349cc55cSDimitry Andric          ", %function' to give symbol type STT_FUNC if interworking between "
513349cc55cSDimitry Andric          "ARM and Thumb is required" +
514349cc55cSDimitry Andric          hint);
5155ffd83dbSDimitry Andric   }
5165ffd83dbSDimitry Andric }
5175ffd83dbSDimitry Andric 
5185ffd83dbSDimitry Andric // Rotate a 32-bit unsigned value right by a specified amt of bits.
rotr32(uint32_t val,uint32_t amt)5195ffd83dbSDimitry Andric static uint32_t rotr32(uint32_t val, uint32_t amt) {
5205ffd83dbSDimitry Andric   assert(amt < 32 && "Invalid rotate amount");
5215ffd83dbSDimitry Andric   return (val >> amt) | (val << ((32 - amt) & 31));
5225ffd83dbSDimitry Andric }
5235ffd83dbSDimitry Andric 
getRemAndLZForGroup(unsigned group,uint32_t val)5244824e7fdSDimitry Andric static std::pair<uint32_t, uint32_t> getRemAndLZForGroup(unsigned group,
5254824e7fdSDimitry Andric                                                          uint32_t val) {
5264824e7fdSDimitry Andric   uint32_t rem, lz;
5274824e7fdSDimitry Andric   do {
52806c3fb27SDimitry Andric     lz = llvm::countl_zero(val) & ~1;
5294824e7fdSDimitry Andric     rem = val;
5304824e7fdSDimitry Andric     if (lz == 32) // implies rem == 0
5314824e7fdSDimitry Andric       break;
5324824e7fdSDimitry Andric     val &= 0xffffff >> lz;
5334824e7fdSDimitry Andric   } while (group--);
5344824e7fdSDimitry Andric   return {rem, lz};
5355ffd83dbSDimitry Andric }
5365ffd83dbSDimitry Andric 
encodeAluGroup(uint8_t * loc,const Relocation & rel,uint64_t val,int group,bool check)5374824e7fdSDimitry Andric static void encodeAluGroup(uint8_t *loc, const Relocation &rel, uint64_t val,
5384824e7fdSDimitry Andric                            int group, bool check) {
5394824e7fdSDimitry Andric   // ADD/SUB (immediate) add = bit23, sub = bit22
5404824e7fdSDimitry Andric   // immediate field carries is a 12-bit modified immediate, made up of a 4-bit
5414824e7fdSDimitry Andric   // even rotate right and an 8-bit immediate.
5424824e7fdSDimitry Andric   uint32_t opcode = 0x00800000;
5434824e7fdSDimitry Andric   if (val >> 63) {
5444824e7fdSDimitry Andric     opcode = 0x00400000;
5454824e7fdSDimitry Andric     val = -val;
5464824e7fdSDimitry Andric   }
5474824e7fdSDimitry Andric   uint32_t imm, lz;
5484824e7fdSDimitry Andric   std::tie(imm, lz) = getRemAndLZForGroup(group, val);
5494824e7fdSDimitry Andric   uint32_t rot = 0;
5504824e7fdSDimitry Andric   if (lz < 24) {
5514824e7fdSDimitry Andric     imm = rotr32(imm, 24 - lz);
5524824e7fdSDimitry Andric     rot = (lz + 8) << 7;
5534824e7fdSDimitry Andric   }
5544824e7fdSDimitry Andric   if (check && imm > 0xff)
5554824e7fdSDimitry Andric     error(getErrorLocation(loc) + "unencodeable immediate " + Twine(val).str() +
5564824e7fdSDimitry Andric           " for relocation " + toString(rel.type));
55706c3fb27SDimitry Andric   write32(loc, (read32(loc) & 0xff3ff000) | opcode | rot | (imm & 0xff));
5585ffd83dbSDimitry Andric }
5595ffd83dbSDimitry Andric 
encodeLdrGroup(uint8_t * loc,const Relocation & rel,uint64_t val,int group)5604824e7fdSDimitry Andric static void encodeLdrGroup(uint8_t *loc, const Relocation &rel, uint64_t val,
5614824e7fdSDimitry Andric                            int group) {
5624824e7fdSDimitry Andric   // R_ARM_LDR_PC_Gn is S + A - P, we have ((S + A) | T) - P, if S is a
5634824e7fdSDimitry Andric   // function then addr is 0 (modulo 2) and Pa is 0 (modulo 4) so we can clear
5644824e7fdSDimitry Andric   // bottom bit to recover S + A - P.
5654824e7fdSDimitry Andric   if (rel.sym->isFunc())
5664824e7fdSDimitry Andric     val &= ~0x1;
5674824e7fdSDimitry Andric   // LDR (literal) u = bit23
5684824e7fdSDimitry Andric   uint32_t opcode = 0x00800000;
5694824e7fdSDimitry Andric   if (val >> 63) {
5704824e7fdSDimitry Andric     opcode = 0x0;
5714824e7fdSDimitry Andric     val = -val;
5724824e7fdSDimitry Andric   }
5734824e7fdSDimitry Andric   uint32_t imm = getRemAndLZForGroup(group, val).first;
5744824e7fdSDimitry Andric   checkUInt(loc, imm, 12, rel);
57506c3fb27SDimitry Andric   write32(loc, (read32(loc) & 0xff7ff000) | opcode | imm);
5764824e7fdSDimitry Andric }
5774824e7fdSDimitry Andric 
encodeLdrsGroup(uint8_t * loc,const Relocation & rel,uint64_t val,int group)5784824e7fdSDimitry Andric static void encodeLdrsGroup(uint8_t *loc, const Relocation &rel, uint64_t val,
5794824e7fdSDimitry Andric                             int group) {
5804824e7fdSDimitry Andric   // R_ARM_LDRS_PC_Gn is S + A - P, we have ((S + A) | T) - P, if S is a
5814824e7fdSDimitry Andric   // function then addr is 0 (modulo 2) and Pa is 0 (modulo 4) so we can clear
5824824e7fdSDimitry Andric   // bottom bit to recover S + A - P.
5834824e7fdSDimitry Andric   if (rel.sym->isFunc())
5844824e7fdSDimitry Andric     val &= ~0x1;
5854824e7fdSDimitry Andric   // LDRD/LDRH/LDRSB/LDRSH (literal) u = bit23
5864824e7fdSDimitry Andric   uint32_t opcode = 0x00800000;
5874824e7fdSDimitry Andric   if (val >> 63) {
5884824e7fdSDimitry Andric     opcode = 0x0;
5894824e7fdSDimitry Andric     val = -val;
5904824e7fdSDimitry Andric   }
5914824e7fdSDimitry Andric   uint32_t imm = getRemAndLZForGroup(group, val).first;
5924824e7fdSDimitry Andric   checkUInt(loc, imm, 8, rel);
59306c3fb27SDimitry Andric   write32(loc, (read32(loc) & 0xff7ff0f0) | opcode | ((imm & 0xf0) << 4) |
5944824e7fdSDimitry Andric                      (imm & 0xf));
5955ffd83dbSDimitry Andric }
5965ffd83dbSDimitry Andric 
relocate(uint8_t * loc,const Relocation & rel,uint64_t val) const5975ffd83dbSDimitry Andric void ARM::relocate(uint8_t *loc, const Relocation &rel, uint64_t val) const {
5985ffd83dbSDimitry Andric   switch (rel.type) {
5990b57cec5SDimitry Andric   case R_ARM_ABS32:
6000b57cec5SDimitry Andric   case R_ARM_BASE_PREL:
6010b57cec5SDimitry Andric   case R_ARM_GOTOFF32:
6020b57cec5SDimitry Andric   case R_ARM_GOT_BREL:
6030b57cec5SDimitry Andric   case R_ARM_GOT_PREL:
6040b57cec5SDimitry Andric   case R_ARM_REL32:
6050b57cec5SDimitry Andric   case R_ARM_RELATIVE:
6060b57cec5SDimitry Andric   case R_ARM_SBREL32:
6070b57cec5SDimitry Andric   case R_ARM_TARGET1:
6080b57cec5SDimitry Andric   case R_ARM_TARGET2:
6090b57cec5SDimitry Andric   case R_ARM_TLS_GD32:
6100b57cec5SDimitry Andric   case R_ARM_TLS_IE32:
6110b57cec5SDimitry Andric   case R_ARM_TLS_LDM32:
6120b57cec5SDimitry Andric   case R_ARM_TLS_LDO32:
6130b57cec5SDimitry Andric   case R_ARM_TLS_LE32:
6140b57cec5SDimitry Andric   case R_ARM_TLS_TPOFF32:
6150b57cec5SDimitry Andric   case R_ARM_TLS_DTPOFF32:
61606c3fb27SDimitry Andric     write32(loc, val);
6170b57cec5SDimitry Andric     break;
6180b57cec5SDimitry Andric   case R_ARM_PREL31:
6195ffd83dbSDimitry Andric     checkInt(loc, val, 31, rel);
62006c3fb27SDimitry Andric     write32(loc, (read32(loc) & 0x80000000) | (val & ~0x80000000));
6210b57cec5SDimitry Andric     break;
6225ffd83dbSDimitry Andric   case R_ARM_CALL: {
6235ffd83dbSDimitry Andric     // R_ARM_CALL is used for BL and BLX instructions, for symbols of type
6245ffd83dbSDimitry Andric     // STT_FUNC we choose whether to write a BL or BLX depending on the
6255ffd83dbSDimitry Andric     // value of bit 0 of Val. With bit 0 == 1 denoting Thumb. If the symbol is
6265ffd83dbSDimitry Andric     // not of type STT_FUNC then we must preserve the original instruction.
6275ffd83dbSDimitry Andric     assert(rel.sym); // R_ARM_CALL is always reached via relocate().
6285ffd83dbSDimitry Andric     bool bit0Thumb = val & 1;
62906c3fb27SDimitry Andric     bool isBlx = (read32(loc) & 0xfe000000) == 0xfa000000;
6305ffd83dbSDimitry Andric     // lld 10.0 and before always used bit0Thumb when deciding to write a BLX
6315ffd83dbSDimitry Andric     // even when type not STT_FUNC.
6325ffd83dbSDimitry Andric     if (!rel.sym->isFunc() && isBlx != bit0Thumb)
6335ffd83dbSDimitry Andric       stateChangeWarning(loc, rel.type, *rel.sym);
6345ffd83dbSDimitry Andric     if (rel.sym->isFunc() ? bit0Thumb : isBlx) {
6350b57cec5SDimitry Andric       // The BLX encoding is 0xfa:H:imm24 where Val = imm24:H:'1'
6365ffd83dbSDimitry Andric       checkInt(loc, val, 26, rel);
63706c3fb27SDimitry Andric       write32(loc, 0xfa000000 |                    // opcode
6380b57cec5SDimitry Andric                          ((val & 2) << 23) |         // H
6390b57cec5SDimitry Andric                          ((val >> 2) & 0x00ffffff)); // imm24
6400b57cec5SDimitry Andric       break;
6410b57cec5SDimitry Andric     }
6420b57cec5SDimitry Andric     // BLX (always unconditional) instruction to an ARM Target, select an
6430b57cec5SDimitry Andric     // unconditional BL.
64406c3fb27SDimitry Andric     write32(loc, 0xeb000000 | (read32(loc) & 0x00ffffff));
6450b57cec5SDimitry Andric     // fall through as BL encoding is shared with B
6465ffd83dbSDimitry Andric   }
647bdd1243dSDimitry Andric     [[fallthrough]];
6480b57cec5SDimitry Andric   case R_ARM_JUMP24:
6490b57cec5SDimitry Andric   case R_ARM_PC24:
6500b57cec5SDimitry Andric   case R_ARM_PLT32:
6515ffd83dbSDimitry Andric     checkInt(loc, val, 26, rel);
65206c3fb27SDimitry Andric     write32(loc, (read32(loc) & ~0x00ffffff) | ((val >> 2) & 0x00ffffff));
6530b57cec5SDimitry Andric     break;
654349cc55cSDimitry Andric   case R_ARM_THM_JUMP8:
655349cc55cSDimitry Andric     // We do a 9 bit check because val is right-shifted by 1 bit.
656349cc55cSDimitry Andric     checkInt(loc, val, 9, rel);
65706c3fb27SDimitry Andric     write16(loc, (read32(loc) & 0xff00) | ((val >> 1) & 0x00ff));
658349cc55cSDimitry Andric     break;
6590b57cec5SDimitry Andric   case R_ARM_THM_JUMP11:
660349cc55cSDimitry Andric     // We do a 12 bit check because val is right-shifted by 1 bit.
6615ffd83dbSDimitry Andric     checkInt(loc, val, 12, rel);
66206c3fb27SDimitry Andric     write16(loc, (read32(loc) & 0xf800) | ((val >> 1) & 0x07ff));
6630b57cec5SDimitry Andric     break;
6640b57cec5SDimitry Andric   case R_ARM_THM_JUMP19:
6650b57cec5SDimitry Andric     // Encoding T3: Val = S:J2:J1:imm6:imm11:0
6665ffd83dbSDimitry Andric     checkInt(loc, val, 21, rel);
66706c3fb27SDimitry Andric     write16(loc,
66806c3fb27SDimitry Andric               (read16(loc) & 0xfbc0) |   // opcode cond
6690b57cec5SDimitry Andric                   ((val >> 10) & 0x0400) | // S
6700b57cec5SDimitry Andric                   ((val >> 12) & 0x003f)); // imm6
67106c3fb27SDimitry Andric     write16(loc + 2,
6720b57cec5SDimitry Andric               0x8000 |                    // opcode
6730b57cec5SDimitry Andric                   ((val >> 8) & 0x0800) | // J2
6740b57cec5SDimitry Andric                   ((val >> 5) & 0x2000) | // J1
6750b57cec5SDimitry Andric                   ((val >> 1) & 0x07ff)); // imm11
6760b57cec5SDimitry Andric     break;
6775ffd83dbSDimitry Andric   case R_ARM_THM_CALL: {
6785ffd83dbSDimitry Andric     // R_ARM_THM_CALL is used for BL and BLX instructions, for symbols of type
6795ffd83dbSDimitry Andric     // STT_FUNC we choose whether to write a BL or BLX depending on the
6805ffd83dbSDimitry Andric     // value of bit 0 of Val. With bit 0 == 0 denoting ARM, if the symbol is
6815ffd83dbSDimitry Andric     // not of type STT_FUNC then we must preserve the original instruction.
6825ffd83dbSDimitry Andric     // PLT entries are always ARM state so we know we need to interwork.
6835ffd83dbSDimitry Andric     assert(rel.sym); // R_ARM_THM_CALL is always reached via relocate().
6845ffd83dbSDimitry Andric     bool bit0Thumb = val & 1;
685*62987288SDimitry Andric     bool useThumb = bit0Thumb || useThumbPLTs();
68606c3fb27SDimitry Andric     bool isBlx = (read16(loc + 2) & 0x1000) == 0;
6875ffd83dbSDimitry Andric     // lld 10.0 and before always used bit0Thumb when deciding to write a BLX
6880fca6ea1SDimitry Andric     // even when type not STT_FUNC.
6890fca6ea1SDimitry Andric     if (!rel.sym->isFunc() && !rel.sym->isInPlt() && isBlx == useThumb)
6905ffd83dbSDimitry Andric       stateChangeWarning(loc, rel.type, *rel.sym);
6910fca6ea1SDimitry Andric     if ((rel.sym->isFunc() || rel.sym->isInPlt()) ? !useThumb : isBlx) {
6925ffd83dbSDimitry Andric       // We are writing a BLX. Ensure BLX destination is 4-byte aligned. As
6935ffd83dbSDimitry Andric       // the BLX instruction may only be two byte aligned. This must be done
6945ffd83dbSDimitry Andric       // before overflow check.
6950b57cec5SDimitry Andric       val = alignTo(val, 4);
69606c3fb27SDimitry Andric       write16(loc + 2, read16(loc + 2) & ~0x1000);
6975ffd83dbSDimitry Andric     } else {
69806c3fb27SDimitry Andric       write16(loc + 2, (read16(loc + 2) & ~0x1000) | 1 << 12);
6990b57cec5SDimitry Andric     }
7000b57cec5SDimitry Andric     if (!config->armJ1J2BranchEncoding) {
7010b57cec5SDimitry Andric       // Older Arm architectures do not support R_ARM_THM_JUMP24 and have
7020b57cec5SDimitry Andric       // different encoding rules and range due to J1 and J2 always being 1.
7035ffd83dbSDimitry Andric       checkInt(loc, val, 23, rel);
70406c3fb27SDimitry Andric       write16(loc,
7050b57cec5SDimitry Andric                 0xf000 |                     // opcode
7060b57cec5SDimitry Andric                     ((val >> 12) & 0x07ff)); // imm11
70706c3fb27SDimitry Andric       write16(loc + 2,
70806c3fb27SDimitry Andric                 (read16(loc + 2) & 0xd000) | // opcode
7090b57cec5SDimitry Andric                     0x2800 |                   // J1 == J2 == 1
7100b57cec5SDimitry Andric                     ((val >> 1) & 0x07ff));    // imm11
7110b57cec5SDimitry Andric       break;
7120b57cec5SDimitry Andric     }
7135ffd83dbSDimitry Andric   }
7140b57cec5SDimitry Andric     // Fall through as rest of encoding is the same as B.W
715bdd1243dSDimitry Andric     [[fallthrough]];
7160b57cec5SDimitry Andric   case R_ARM_THM_JUMP24:
7170b57cec5SDimitry Andric     // Encoding B  T4, BL T1, BLX T2: Val = S:I1:I2:imm10:imm11:0
7185ffd83dbSDimitry Andric     checkInt(loc, val, 25, rel);
71906c3fb27SDimitry Andric     write16(loc,
7200b57cec5SDimitry Andric               0xf000 |                     // opcode
7210b57cec5SDimitry Andric                   ((val >> 14) & 0x0400) | // S
7220b57cec5SDimitry Andric                   ((val >> 12) & 0x03ff)); // imm10
72306c3fb27SDimitry Andric     write16(loc + 2,
72406c3fb27SDimitry Andric               (read16(loc + 2) & 0xd000) |                  // opcode
7250b57cec5SDimitry Andric                   (((~(val >> 10)) ^ (val >> 11)) & 0x2000) | // J1
7260b57cec5SDimitry Andric                   (((~(val >> 11)) ^ (val >> 13)) & 0x0800) | // J2
7270b57cec5SDimitry Andric                   ((val >> 1) & 0x07ff));                     // imm11
7280b57cec5SDimitry Andric     break;
7290b57cec5SDimitry Andric   case R_ARM_MOVW_ABS_NC:
7300b57cec5SDimitry Andric   case R_ARM_MOVW_PREL_NC:
7315ffd83dbSDimitry Andric   case R_ARM_MOVW_BREL_NC:
73206c3fb27SDimitry Andric     write32(loc, (read32(loc) & ~0x000f0fff) | ((val & 0xf000) << 4) |
7330b57cec5SDimitry Andric                        (val & 0x0fff));
7340b57cec5SDimitry Andric     break;
7350b57cec5SDimitry Andric   case R_ARM_MOVT_ABS:
7360b57cec5SDimitry Andric   case R_ARM_MOVT_PREL:
7375ffd83dbSDimitry Andric   case R_ARM_MOVT_BREL:
73806c3fb27SDimitry Andric     write32(loc, (read32(loc) & ~0x000f0fff) |
7390b57cec5SDimitry Andric                        (((val >> 16) & 0xf000) << 4) | ((val >> 16) & 0xfff));
7400b57cec5SDimitry Andric     break;
7410b57cec5SDimitry Andric   case R_ARM_THM_MOVT_ABS:
7420b57cec5SDimitry Andric   case R_ARM_THM_MOVT_PREL:
7435ffd83dbSDimitry Andric   case R_ARM_THM_MOVT_BREL:
7440b57cec5SDimitry Andric     // Encoding T1: A = imm4:i:imm3:imm8
74506c3fb27SDimitry Andric 
74606c3fb27SDimitry Andric     write16(loc,
7470b57cec5SDimitry Andric             0xf2c0 |                     // opcode
7480b57cec5SDimitry Andric                 ((val >> 17) & 0x0400) | // i
7490b57cec5SDimitry Andric                 ((val >> 28) & 0x000f)); // imm4
75006c3fb27SDimitry Andric 
75106c3fb27SDimitry Andric     write16(loc + 2,
75206c3fb27SDimitry Andric               (read16(loc + 2) & 0x8f00) | // opcode
7530b57cec5SDimitry Andric                   ((val >> 12) & 0x7000) |   // imm3
7540b57cec5SDimitry Andric                   ((val >> 16) & 0x00ff));   // imm8
7550b57cec5SDimitry Andric     break;
7560b57cec5SDimitry Andric   case R_ARM_THM_MOVW_ABS_NC:
7570b57cec5SDimitry Andric   case R_ARM_THM_MOVW_PREL_NC:
7585ffd83dbSDimitry Andric   case R_ARM_THM_MOVW_BREL_NC:
7590b57cec5SDimitry Andric     // Encoding T3: A = imm4:i:imm3:imm8
76006c3fb27SDimitry Andric     write16(loc,
7610b57cec5SDimitry Andric               0xf240 |                     // opcode
7620b57cec5SDimitry Andric                   ((val >> 1) & 0x0400) |  // i
7630b57cec5SDimitry Andric                   ((val >> 12) & 0x000f)); // imm4
76406c3fb27SDimitry Andric     write16(loc + 2,
76506c3fb27SDimitry Andric               (read16(loc + 2) & 0x8f00) | // opcode
7660b57cec5SDimitry Andric                   ((val << 4) & 0x7000) |    // imm3
7670b57cec5SDimitry Andric                   (val & 0x00ff));           // imm8
7680b57cec5SDimitry Andric     break;
76906c3fb27SDimitry Andric   case R_ARM_THM_ALU_ABS_G3:
77006c3fb27SDimitry Andric     write16(loc, (read16(loc) &~ 0x00ff) | ((val >> 24) & 0x00ff));
77106c3fb27SDimitry Andric     break;
77206c3fb27SDimitry Andric   case R_ARM_THM_ALU_ABS_G2_NC:
77306c3fb27SDimitry Andric     write16(loc, (read16(loc) &~ 0x00ff) | ((val >> 16) & 0x00ff));
77406c3fb27SDimitry Andric     break;
77506c3fb27SDimitry Andric   case R_ARM_THM_ALU_ABS_G1_NC:
77606c3fb27SDimitry Andric     write16(loc, (read16(loc) &~ 0x00ff) | ((val >> 8) & 0x00ff));
77706c3fb27SDimitry Andric     break;
77806c3fb27SDimitry Andric   case R_ARM_THM_ALU_ABS_G0_NC:
77906c3fb27SDimitry Andric     write16(loc, (read16(loc) &~ 0x00ff) | (val & 0x00ff));
78006c3fb27SDimitry Andric     break;
7814824e7fdSDimitry Andric   case R_ARM_ALU_PC_G0:
7824824e7fdSDimitry Andric     encodeAluGroup(loc, rel, val, 0, true);
7835ffd83dbSDimitry Andric     break;
7844824e7fdSDimitry Andric   case R_ARM_ALU_PC_G0_NC:
7854824e7fdSDimitry Andric     encodeAluGroup(loc, rel, val, 0, false);
7865ffd83dbSDimitry Andric     break;
7874824e7fdSDimitry Andric   case R_ARM_ALU_PC_G1:
7884824e7fdSDimitry Andric     encodeAluGroup(loc, rel, val, 1, true);
7894824e7fdSDimitry Andric     break;
7904824e7fdSDimitry Andric   case R_ARM_ALU_PC_G1_NC:
7914824e7fdSDimitry Andric     encodeAluGroup(loc, rel, val, 1, false);
7924824e7fdSDimitry Andric     break;
7934824e7fdSDimitry Andric   case R_ARM_ALU_PC_G2:
7944824e7fdSDimitry Andric     encodeAluGroup(loc, rel, val, 2, true);
7954824e7fdSDimitry Andric     break;
7964824e7fdSDimitry Andric   case R_ARM_LDR_PC_G0:
7974824e7fdSDimitry Andric     encodeLdrGroup(loc, rel, val, 0);
7984824e7fdSDimitry Andric     break;
7994824e7fdSDimitry Andric   case R_ARM_LDR_PC_G1:
8004824e7fdSDimitry Andric     encodeLdrGroup(loc, rel, val, 1);
8014824e7fdSDimitry Andric     break;
8024824e7fdSDimitry Andric   case R_ARM_LDR_PC_G2:
8034824e7fdSDimitry Andric     encodeLdrGroup(loc, rel, val, 2);
8044824e7fdSDimitry Andric     break;
8054824e7fdSDimitry Andric   case R_ARM_LDRS_PC_G0:
8064824e7fdSDimitry Andric     encodeLdrsGroup(loc, rel, val, 0);
8074824e7fdSDimitry Andric     break;
8084824e7fdSDimitry Andric   case R_ARM_LDRS_PC_G1:
8094824e7fdSDimitry Andric     encodeLdrsGroup(loc, rel, val, 1);
8104824e7fdSDimitry Andric     break;
8114824e7fdSDimitry Andric   case R_ARM_LDRS_PC_G2:
8124824e7fdSDimitry Andric     encodeLdrsGroup(loc, rel, val, 2);
8134824e7fdSDimitry Andric     break;
8145ffd83dbSDimitry Andric   case R_ARM_THM_ALU_PREL_11_0: {
8155ffd83dbSDimitry Andric     // ADR encoding T2 (sub), T3 (add) i:imm3:imm8
8165ffd83dbSDimitry Andric     int64_t imm = val;
8175ffd83dbSDimitry Andric     uint16_t sub = 0;
8185ffd83dbSDimitry Andric     if (imm < 0) {
8195ffd83dbSDimitry Andric       imm = -imm;
8205ffd83dbSDimitry Andric       sub = 0x00a0;
8215ffd83dbSDimitry Andric     }
8225ffd83dbSDimitry Andric     checkUInt(loc, imm, 12, rel);
82306c3fb27SDimitry Andric     write16(loc, (read16(loc) & 0xfb0f) | sub | (imm & 0x800) >> 1);
82406c3fb27SDimitry Andric     write16(loc + 2,
82506c3fb27SDimitry Andric               (read16(loc + 2) & 0x8f00) | (imm & 0x700) << 4 | (imm & 0xff));
8265ffd83dbSDimitry Andric     break;
8275ffd83dbSDimitry Andric   }
8285ffd83dbSDimitry Andric   case R_ARM_THM_PC8:
8295ffd83dbSDimitry Andric     // ADR and LDR literal encoding T1 positive offset only imm8:00
8305ffd83dbSDimitry Andric     // R_ARM_THM_PC8 is S + A - Pa, we have ((S + A) | T) - Pa, if S is a
8315ffd83dbSDimitry Andric     // function then addr is 0 (modulo 2) and Pa is 0 (modulo 4) so we can clear
8325ffd83dbSDimitry Andric     // bottom bit to recover S + A - Pa.
8335ffd83dbSDimitry Andric     if (rel.sym->isFunc())
8345ffd83dbSDimitry Andric       val &= ~0x1;
8355ffd83dbSDimitry Andric     checkUInt(loc, val, 10, rel);
8365ffd83dbSDimitry Andric     checkAlignment(loc, val, 4, rel);
83706c3fb27SDimitry Andric     write16(loc, (read16(loc) & 0xff00) | (val & 0x3fc) >> 2);
8385ffd83dbSDimitry Andric     break;
8395ffd83dbSDimitry Andric   case R_ARM_THM_PC12: {
8405ffd83dbSDimitry Andric     // LDR (literal) encoding T2, add = (U == '1') imm12
8415ffd83dbSDimitry Andric     // imm12 is unsigned
8425ffd83dbSDimitry Andric     // R_ARM_THM_PC12 is S + A - Pa, we have ((S + A) | T) - Pa, if S is a
8435ffd83dbSDimitry Andric     // function then addr is 0 (modulo 2) and Pa is 0 (modulo 4) so we can clear
8445ffd83dbSDimitry Andric     // bottom bit to recover S + A - Pa.
8455ffd83dbSDimitry Andric     if (rel.sym->isFunc())
8465ffd83dbSDimitry Andric       val &= ~0x1;
8475ffd83dbSDimitry Andric     int64_t imm12 = val;
8485ffd83dbSDimitry Andric     uint16_t u = 0x0080;
8495ffd83dbSDimitry Andric     if (imm12 < 0) {
8505ffd83dbSDimitry Andric       imm12 = -imm12;
8515ffd83dbSDimitry Andric       u = 0;
8525ffd83dbSDimitry Andric     }
8535ffd83dbSDimitry Andric     checkUInt(loc, imm12, 12, rel);
85406c3fb27SDimitry Andric     write16(loc, read16(loc) | u);
85506c3fb27SDimitry Andric     write16(loc + 2, (read16(loc + 2) & 0xf000) | imm12);
8565ffd83dbSDimitry Andric     break;
8575ffd83dbSDimitry Andric   }
8580b57cec5SDimitry Andric   default:
859349cc55cSDimitry Andric     llvm_unreachable("unknown relocation");
8600b57cec5SDimitry Andric   }
8610b57cec5SDimitry Andric }
8620b57cec5SDimitry Andric 
getImplicitAddend(const uint8_t * buf,RelType type) const8630b57cec5SDimitry Andric int64_t ARM::getImplicitAddend(const uint8_t *buf, RelType type) const {
8640b57cec5SDimitry Andric   switch (type) {
8650b57cec5SDimitry Andric   default:
866fe6060f1SDimitry Andric     internalLinkerError(getErrorLocation(buf),
867fe6060f1SDimitry Andric                         "cannot read addend for relocation " + toString(type));
8680b57cec5SDimitry Andric     return 0;
8690b57cec5SDimitry Andric   case R_ARM_ABS32:
8700b57cec5SDimitry Andric   case R_ARM_BASE_PREL:
871fe6060f1SDimitry Andric   case R_ARM_GLOB_DAT:
8720b57cec5SDimitry Andric   case R_ARM_GOTOFF32:
8730b57cec5SDimitry Andric   case R_ARM_GOT_BREL:
8740b57cec5SDimitry Andric   case R_ARM_GOT_PREL:
875fe6060f1SDimitry Andric   case R_ARM_IRELATIVE:
8760b57cec5SDimitry Andric   case R_ARM_REL32:
877fe6060f1SDimitry Andric   case R_ARM_RELATIVE:
878fe6060f1SDimitry Andric   case R_ARM_SBREL32:
8790b57cec5SDimitry Andric   case R_ARM_TARGET1:
8800b57cec5SDimitry Andric   case R_ARM_TARGET2:
881fe6060f1SDimitry Andric   case R_ARM_TLS_DTPMOD32:
882fe6060f1SDimitry Andric   case R_ARM_TLS_DTPOFF32:
8830b57cec5SDimitry Andric   case R_ARM_TLS_GD32:
8840b57cec5SDimitry Andric   case R_ARM_TLS_IE32:
885fe6060f1SDimitry Andric   case R_ARM_TLS_LDM32:
8860b57cec5SDimitry Andric   case R_ARM_TLS_LE32:
887fe6060f1SDimitry Andric   case R_ARM_TLS_LDO32:
888fe6060f1SDimitry Andric   case R_ARM_TLS_TPOFF32:
88906c3fb27SDimitry Andric     return SignExtend64<32>(read32(buf));
8900b57cec5SDimitry Andric   case R_ARM_PREL31:
89106c3fb27SDimitry Andric     return SignExtend64<31>(read32(buf));
8920b57cec5SDimitry Andric   case R_ARM_CALL:
8930b57cec5SDimitry Andric   case R_ARM_JUMP24:
8940b57cec5SDimitry Andric   case R_ARM_PC24:
8950b57cec5SDimitry Andric   case R_ARM_PLT32:
89606c3fb27SDimitry Andric     return SignExtend64<26>(read32(buf) << 2);
897349cc55cSDimitry Andric   case R_ARM_THM_JUMP8:
89806c3fb27SDimitry Andric     return SignExtend64<9>(read16(buf) << 1);
8990b57cec5SDimitry Andric   case R_ARM_THM_JUMP11:
90006c3fb27SDimitry Andric     return SignExtend64<12>(read16(buf) << 1);
9010b57cec5SDimitry Andric   case R_ARM_THM_JUMP19: {
9020b57cec5SDimitry Andric     // Encoding T3: A = S:J2:J1:imm10:imm6:0
90306c3fb27SDimitry Andric     uint16_t hi = read16(buf);
90406c3fb27SDimitry Andric     uint16_t lo = read16(buf + 2);
9050b57cec5SDimitry Andric     return SignExtend64<20>(((hi & 0x0400) << 10) | // S
9060b57cec5SDimitry Andric                             ((lo & 0x0800) << 8) |  // J2
9070b57cec5SDimitry Andric                             ((lo & 0x2000) << 5) |  // J1
9080b57cec5SDimitry Andric                             ((hi & 0x003f) << 12) | // imm6
9090b57cec5SDimitry Andric                             ((lo & 0x07ff) << 1));  // imm11:0
9100b57cec5SDimitry Andric   }
9110b57cec5SDimitry Andric   case R_ARM_THM_CALL:
9120b57cec5SDimitry Andric     if (!config->armJ1J2BranchEncoding) {
9130b57cec5SDimitry Andric       // Older Arm architectures do not support R_ARM_THM_JUMP24 and have
9140b57cec5SDimitry Andric       // different encoding rules and range due to J1 and J2 always being 1.
91506c3fb27SDimitry Andric       uint16_t hi = read16(buf);
91606c3fb27SDimitry Andric       uint16_t lo = read16(buf + 2);
9170b57cec5SDimitry Andric       return SignExtend64<22>(((hi & 0x7ff) << 12) | // imm11
9180b57cec5SDimitry Andric                               ((lo & 0x7ff) << 1));  // imm11:0
9190b57cec5SDimitry Andric       break;
9200b57cec5SDimitry Andric     }
921bdd1243dSDimitry Andric     [[fallthrough]];
9220b57cec5SDimitry Andric   case R_ARM_THM_JUMP24: {
9230b57cec5SDimitry Andric     // Encoding B T4, BL T1, BLX T2: A = S:I1:I2:imm10:imm11:0
9240b57cec5SDimitry Andric     // I1 = NOT(J1 EOR S), I2 = NOT(J2 EOR S)
92506c3fb27SDimitry Andric     uint16_t hi = read16(buf);
92606c3fb27SDimitry Andric     uint16_t lo = read16(buf + 2);
9270b57cec5SDimitry Andric     return SignExtend64<24>(((hi & 0x0400) << 14) |                    // S
9280b57cec5SDimitry Andric                             (~((lo ^ (hi << 3)) << 10) & 0x00800000) | // I1
9290b57cec5SDimitry Andric                             (~((lo ^ (hi << 1)) << 11) & 0x00400000) | // I2
9300b57cec5SDimitry Andric                             ((hi & 0x003ff) << 12) |                   // imm0
9310b57cec5SDimitry Andric                             ((lo & 0x007ff) << 1)); // imm11:0
9320b57cec5SDimitry Andric   }
9330b57cec5SDimitry Andric   // ELF for the ARM Architecture 4.6.1.1 the implicit addend for MOVW and
9340b57cec5SDimitry Andric   // MOVT is in the range -32768 <= A < 32768
9350b57cec5SDimitry Andric   case R_ARM_MOVW_ABS_NC:
9360b57cec5SDimitry Andric   case R_ARM_MOVT_ABS:
9370b57cec5SDimitry Andric   case R_ARM_MOVW_PREL_NC:
9385ffd83dbSDimitry Andric   case R_ARM_MOVT_PREL:
9395ffd83dbSDimitry Andric   case R_ARM_MOVW_BREL_NC:
9405ffd83dbSDimitry Andric   case R_ARM_MOVT_BREL: {
94106c3fb27SDimitry Andric     uint64_t val = read32(buf) & 0x000f0fff;
9420b57cec5SDimitry Andric     return SignExtend64<16>(((val & 0x000f0000) >> 4) | (val & 0x00fff));
9430b57cec5SDimitry Andric   }
9440b57cec5SDimitry Andric   case R_ARM_THM_MOVW_ABS_NC:
9450b57cec5SDimitry Andric   case R_ARM_THM_MOVT_ABS:
9460b57cec5SDimitry Andric   case R_ARM_THM_MOVW_PREL_NC:
9475ffd83dbSDimitry Andric   case R_ARM_THM_MOVT_PREL:
9485ffd83dbSDimitry Andric   case R_ARM_THM_MOVW_BREL_NC:
9495ffd83dbSDimitry Andric   case R_ARM_THM_MOVT_BREL: {
9500b57cec5SDimitry Andric     // Encoding T3: A = imm4:i:imm3:imm8
95106c3fb27SDimitry Andric     uint16_t hi = read16(buf);
95206c3fb27SDimitry Andric     uint16_t lo = read16(buf + 2);
9530b57cec5SDimitry Andric     return SignExtend64<16>(((hi & 0x000f) << 12) | // imm4
9540b57cec5SDimitry Andric                             ((hi & 0x0400) << 1) |  // i
9550b57cec5SDimitry Andric                             ((lo & 0x7000) >> 4) |  // imm3
9560b57cec5SDimitry Andric                             (lo & 0x00ff));         // imm8
9570b57cec5SDimitry Andric   }
95806c3fb27SDimitry Andric   case R_ARM_THM_ALU_ABS_G0_NC:
95906c3fb27SDimitry Andric   case R_ARM_THM_ALU_ABS_G1_NC:
96006c3fb27SDimitry Andric   case R_ARM_THM_ALU_ABS_G2_NC:
96106c3fb27SDimitry Andric   case R_ARM_THM_ALU_ABS_G3:
96206c3fb27SDimitry Andric     return read16(buf) & 0xff;
9634824e7fdSDimitry Andric   case R_ARM_ALU_PC_G0:
9644824e7fdSDimitry Andric   case R_ARM_ALU_PC_G0_NC:
9654824e7fdSDimitry Andric   case R_ARM_ALU_PC_G1:
9664824e7fdSDimitry Andric   case R_ARM_ALU_PC_G1_NC:
9674824e7fdSDimitry Andric   case R_ARM_ALU_PC_G2: {
9685ffd83dbSDimitry Andric     // 12-bit immediate is a modified immediate made up of a 4-bit even
9695ffd83dbSDimitry Andric     // right rotation and 8-bit constant. After the rotation the value
9705ffd83dbSDimitry Andric     // is zero-extended. When bit 23 is set the instruction is an add, when
9715ffd83dbSDimitry Andric     // bit 22 is set it is a sub.
97206c3fb27SDimitry Andric     uint32_t instr = read32(buf);
9735ffd83dbSDimitry Andric     uint32_t val = rotr32(instr & 0xff, ((instr & 0xf00) >> 8) * 2);
9745ffd83dbSDimitry Andric     return (instr & 0x00400000) ? -val : val;
9755ffd83dbSDimitry Andric   }
9764824e7fdSDimitry Andric   case R_ARM_LDR_PC_G0:
9774824e7fdSDimitry Andric   case R_ARM_LDR_PC_G1:
9784824e7fdSDimitry Andric   case R_ARM_LDR_PC_G2: {
9795ffd83dbSDimitry Andric     // ADR (literal) add = bit23, sub = bit22
9805ffd83dbSDimitry Andric     // LDR (literal) u = bit23 unsigned imm12
98106c3fb27SDimitry Andric     bool u = read32(buf) & 0x00800000;
98206c3fb27SDimitry Andric     uint32_t imm12 = read32(buf) & 0xfff;
9835ffd83dbSDimitry Andric     return u ? imm12 : -imm12;
9845ffd83dbSDimitry Andric   }
9854824e7fdSDimitry Andric   case R_ARM_LDRS_PC_G0:
9864824e7fdSDimitry Andric   case R_ARM_LDRS_PC_G1:
9874824e7fdSDimitry Andric   case R_ARM_LDRS_PC_G2: {
9884824e7fdSDimitry Andric     // LDRD/LDRH/LDRSB/LDRSH (literal) u = bit23 unsigned imm8
98906c3fb27SDimitry Andric     uint32_t opcode = read32(buf);
9904824e7fdSDimitry Andric     bool u = opcode & 0x00800000;
9914824e7fdSDimitry Andric     uint32_t imm4l = opcode & 0xf;
9924824e7fdSDimitry Andric     uint32_t imm4h = (opcode & 0xf00) >> 4;
9934824e7fdSDimitry Andric     return u ? (imm4h | imm4l) : -(imm4h | imm4l);
9944824e7fdSDimitry Andric   }
9955ffd83dbSDimitry Andric   case R_ARM_THM_ALU_PREL_11_0: {
9965ffd83dbSDimitry Andric     // Thumb2 ADR, which is an alias for a sub or add instruction with an
9975ffd83dbSDimitry Andric     // unsigned immediate.
9985ffd83dbSDimitry Andric     // ADR encoding T2 (sub), T3 (add) i:imm3:imm8
99906c3fb27SDimitry Andric     uint16_t hi = read16(buf);
100006c3fb27SDimitry Andric     uint16_t lo = read16(buf + 2);
10015ffd83dbSDimitry Andric     uint64_t imm = (hi & 0x0400) << 1 | // i
10025ffd83dbSDimitry Andric                    (lo & 0x7000) >> 4 | // imm3
10035ffd83dbSDimitry Andric                    (lo & 0x00ff);       // imm8
10045ffd83dbSDimitry Andric     // For sub, addend is negative, add is positive.
10055ffd83dbSDimitry Andric     return (hi & 0x00f0) ? -imm : imm;
10065ffd83dbSDimitry Andric   }
10075ffd83dbSDimitry Andric   case R_ARM_THM_PC8:
10085ffd83dbSDimitry Andric     // ADR and LDR (literal) encoding T1
10095ffd83dbSDimitry Andric     // From ELF for the ARM Architecture the initial signed addend is formed
10105ffd83dbSDimitry Andric     // from an unsigned field using expression (((imm8:00 + 4) & 0x3ff) – 4)
10115ffd83dbSDimitry Andric     // this trick permits the PC bias of -4 to be encoded using imm8 = 0xff
101206c3fb27SDimitry Andric     return ((((read16(buf) & 0xff) << 2) + 4) & 0x3ff) - 4;
10135ffd83dbSDimitry Andric   case R_ARM_THM_PC12: {
10145ffd83dbSDimitry Andric     // LDR (literal) encoding T2, add = (U == '1') imm12
101506c3fb27SDimitry Andric     bool u = read16(buf) & 0x0080;
101606c3fb27SDimitry Andric     uint64_t imm12 = read16(buf + 2) & 0x0fff;
10175ffd83dbSDimitry Andric     return u ? imm12 : -imm12;
10185ffd83dbSDimitry Andric   }
1019fe6060f1SDimitry Andric   case R_ARM_NONE:
1020349cc55cSDimitry Andric   case R_ARM_V4BX:
1021fe6060f1SDimitry Andric   case R_ARM_JUMP_SLOT:
1022fe6060f1SDimitry Andric     // These relocations are defined as not having an implicit addend.
1023fe6060f1SDimitry Andric     return 0;
10240b57cec5SDimitry Andric   }
10250b57cec5SDimitry Andric }
10260b57cec5SDimitry Andric 
isArmMapSymbol(const Symbol * b)102706c3fb27SDimitry Andric static bool isArmMapSymbol(const Symbol *b) {
10285f757f3fSDimitry Andric   return b->getName() == "$a" || b->getName().starts_with("$a.");
102906c3fb27SDimitry Andric }
103006c3fb27SDimitry Andric 
isThumbMapSymbol(const Symbol * s)103106c3fb27SDimitry Andric static bool isThumbMapSymbol(const Symbol *s) {
10325f757f3fSDimitry Andric   return s->getName() == "$t" || s->getName().starts_with("$t.");
103306c3fb27SDimitry Andric }
103406c3fb27SDimitry Andric 
isDataMapSymbol(const Symbol * b)103506c3fb27SDimitry Andric static bool isDataMapSymbol(const Symbol *b) {
10365f757f3fSDimitry Andric   return b->getName() == "$d" || b->getName().starts_with("$d.");
103706c3fb27SDimitry Andric }
103806c3fb27SDimitry Andric 
sortArmMappingSymbols()103906c3fb27SDimitry Andric void elf::sortArmMappingSymbols() {
104006c3fb27SDimitry Andric   // For each input section make sure the mapping symbols are sorted in
104106c3fb27SDimitry Andric   // ascending order.
104206c3fb27SDimitry Andric   for (auto &kv : sectionMap) {
104306c3fb27SDimitry Andric     SmallVector<const Defined *, 0> &mapSyms = kv.second;
104406c3fb27SDimitry Andric     llvm::stable_sort(mapSyms, [](const Defined *a, const Defined *b) {
104506c3fb27SDimitry Andric       return a->value < b->value;
104606c3fb27SDimitry Andric     });
104706c3fb27SDimitry Andric   }
104806c3fb27SDimitry Andric }
104906c3fb27SDimitry Andric 
addArmInputSectionMappingSymbols()105006c3fb27SDimitry Andric void elf::addArmInputSectionMappingSymbols() {
105106c3fb27SDimitry Andric   // Collect mapping symbols for every executable input sections.
105206c3fb27SDimitry Andric   // The linker generated mapping symbols for all the synthetic
105306c3fb27SDimitry Andric   // sections are adding into the sectionmap through the function
105406c3fb27SDimitry Andric   // addArmSyntheitcSectionMappingSymbol.
105506c3fb27SDimitry Andric   for (ELFFileBase *file : ctx.objectFiles) {
105606c3fb27SDimitry Andric     for (Symbol *sym : file->getLocalSymbols()) {
105706c3fb27SDimitry Andric       auto *def = dyn_cast<Defined>(sym);
105806c3fb27SDimitry Andric       if (!def)
105906c3fb27SDimitry Andric         continue;
106006c3fb27SDimitry Andric       if (!isArmMapSymbol(def) && !isDataMapSymbol(def) &&
106106c3fb27SDimitry Andric           !isThumbMapSymbol(def))
106206c3fb27SDimitry Andric         continue;
106306c3fb27SDimitry Andric       if (auto *sec = cast_if_present<InputSection>(def->section))
106406c3fb27SDimitry Andric         if (sec->flags & SHF_EXECINSTR)
106506c3fb27SDimitry Andric           sectionMap[sec].push_back(def);
106606c3fb27SDimitry Andric     }
106706c3fb27SDimitry Andric   }
106806c3fb27SDimitry Andric }
106906c3fb27SDimitry Andric 
107006c3fb27SDimitry Andric // Synthetic sections are not backed by an ELF file where we can access the
107106c3fb27SDimitry Andric // symbol table, instead mapping symbols added to synthetic sections are stored
107206c3fb27SDimitry Andric // in the synthetic symbol table. Due to the presence of strip (--strip-all),
107306c3fb27SDimitry Andric // we can not rely on the synthetic symbol table retaining the mapping symbols.
107406c3fb27SDimitry Andric // Instead we record the mapping symbols locally.
addArmSyntheticSectionMappingSymbol(Defined * sym)107506c3fb27SDimitry Andric void elf::addArmSyntheticSectionMappingSymbol(Defined *sym) {
107606c3fb27SDimitry Andric   if (!isArmMapSymbol(sym) && !isDataMapSymbol(sym) && !isThumbMapSymbol(sym))
107706c3fb27SDimitry Andric     return;
107806c3fb27SDimitry Andric   if (auto *sec = cast_if_present<InputSection>(sym->section))
107906c3fb27SDimitry Andric     if (sec->flags & SHF_EXECINSTR)
108006c3fb27SDimitry Andric       sectionMap[sec].push_back(sym);
108106c3fb27SDimitry Andric }
108206c3fb27SDimitry Andric 
toLittleEndianInstructions(uint8_t * buf,uint64_t start,uint64_t end,uint64_t width)108306c3fb27SDimitry Andric static void toLittleEndianInstructions(uint8_t *buf, uint64_t start,
108406c3fb27SDimitry Andric                                        uint64_t end, uint64_t width) {
108506c3fb27SDimitry Andric   CodeState curState = static_cast<CodeState>(width);
108606c3fb27SDimitry Andric   if (curState == CodeState::Arm)
108706c3fb27SDimitry Andric     for (uint64_t i = start; i < end; i += width)
108806c3fb27SDimitry Andric       write32le(buf + i, read32(buf + i));
108906c3fb27SDimitry Andric 
109006c3fb27SDimitry Andric   if (curState == CodeState::Thumb)
109106c3fb27SDimitry Andric     for (uint64_t i = start; i < end; i += width)
109206c3fb27SDimitry Andric       write16le(buf + i, read16(buf + i));
109306c3fb27SDimitry Andric }
109406c3fb27SDimitry Andric 
109506c3fb27SDimitry Andric // Arm BE8 big endian format requires instructions to be little endian, with
109606c3fb27SDimitry Andric // the initial contents big-endian. Convert the big-endian instructions to
109706c3fb27SDimitry Andric // little endian leaving literal data untouched. We use mapping symbols to
109806c3fb27SDimitry Andric // identify half open intervals of Arm code [$a, non $a) and Thumb code
109906c3fb27SDimitry Andric // [$t, non $t) and convert these to little endian a word or half word at a
110006c3fb27SDimitry Andric // time respectively.
convertArmInstructionstoBE8(InputSection * sec,uint8_t * buf)110106c3fb27SDimitry Andric void elf::convertArmInstructionstoBE8(InputSection *sec, uint8_t *buf) {
110206c3fb27SDimitry Andric   if (!sectionMap.contains(sec))
110306c3fb27SDimitry Andric     return;
110406c3fb27SDimitry Andric 
110506c3fb27SDimitry Andric   SmallVector<const Defined *, 0> &mapSyms = sectionMap[sec];
110606c3fb27SDimitry Andric 
110706c3fb27SDimitry Andric   if (mapSyms.empty())
110806c3fb27SDimitry Andric     return;
110906c3fb27SDimitry Andric 
111006c3fb27SDimitry Andric   CodeState curState = CodeState::Data;
111106c3fb27SDimitry Andric   uint64_t start = 0, width = 0, size = sec->getSize();
111206c3fb27SDimitry Andric   for (auto &msym : mapSyms) {
111306c3fb27SDimitry Andric     CodeState newState = CodeState::Data;
111406c3fb27SDimitry Andric     if (isThumbMapSymbol(msym))
111506c3fb27SDimitry Andric       newState = CodeState::Thumb;
111606c3fb27SDimitry Andric     else if (isArmMapSymbol(msym))
111706c3fb27SDimitry Andric       newState = CodeState::Arm;
111806c3fb27SDimitry Andric 
111906c3fb27SDimitry Andric     if (newState == curState)
112006c3fb27SDimitry Andric       continue;
112106c3fb27SDimitry Andric 
112206c3fb27SDimitry Andric     if (curState != CodeState::Data) {
112306c3fb27SDimitry Andric       width = static_cast<uint64_t>(curState);
112406c3fb27SDimitry Andric       toLittleEndianInstructions(buf, start, msym->value, width);
112506c3fb27SDimitry Andric     }
112606c3fb27SDimitry Andric     start = msym->value;
112706c3fb27SDimitry Andric     curState = newState;
112806c3fb27SDimitry Andric   }
112906c3fb27SDimitry Andric 
113006c3fb27SDimitry Andric   // Passed last mapping symbol, may need to reverse
113106c3fb27SDimitry Andric   // up to end of section.
113206c3fb27SDimitry Andric   if (curState != CodeState::Data) {
113306c3fb27SDimitry Andric     width = static_cast<uint64_t>(curState);
113406c3fb27SDimitry Andric     toLittleEndianInstructions(buf, start, size, width);
113506c3fb27SDimitry Andric   }
113606c3fb27SDimitry Andric }
113706c3fb27SDimitry Andric 
113806c3fb27SDimitry Andric // The Arm Cortex-M Security Extensions (CMSE) splits a system into two parts;
113906c3fb27SDimitry Andric // the non-secure and secure states with the secure state inaccessible from the
114006c3fb27SDimitry Andric // non-secure state, apart from an area of memory in secure state called the
114106c3fb27SDimitry Andric // secure gateway which is accessible from non-secure state. The secure gateway
114206c3fb27SDimitry Andric // contains one or more entry points which must start with a landing pad
114306c3fb27SDimitry Andric // instruction SG. Arm recommends that the secure gateway consists only of
114406c3fb27SDimitry Andric // secure gateway veneers, which are made up of a SG instruction followed by a
114506c3fb27SDimitry Andric // branch to the destination in secure state. Full details can be found in Arm
114606c3fb27SDimitry Andric // v8-M Security Extensions Requirements on Development Tools.
114706c3fb27SDimitry Andric //
114806c3fb27SDimitry Andric // The CMSE model of software development requires the non-secure and secure
114906c3fb27SDimitry Andric // states to be developed as two separate programs. The non-secure developer is
115006c3fb27SDimitry Andric // provided with an import library defining symbols describing the entry points
115106c3fb27SDimitry Andric // in the secure gateway. No additional linker support is required for the
115206c3fb27SDimitry Andric // non-secure state.
115306c3fb27SDimitry Andric //
115406c3fb27SDimitry Andric // Development of the secure state requires linker support to manage the secure
115506c3fb27SDimitry Andric // gateway veneers. The management consists of:
115606c3fb27SDimitry Andric // - Creation of new secure gateway veneers based on symbol conventions.
115706c3fb27SDimitry Andric // - Checking the address of existing secure gateway veneers.
115806c3fb27SDimitry Andric // - Warning when existing secure gateway veneers removed.
115906c3fb27SDimitry Andric //
116006c3fb27SDimitry Andric // The secure gateway veneers are created in an import library, which is just an
116106c3fb27SDimitry Andric // ELF object with a symbol table. The import library is controlled by two
116206c3fb27SDimitry Andric // command line options:
116306c3fb27SDimitry Andric // --in-implib (specify an input import library from a previous revision of the
116406c3fb27SDimitry Andric // program).
116506c3fb27SDimitry Andric // --out-implib (specify an output import library to be created by the linker).
116606c3fb27SDimitry Andric //
116706c3fb27SDimitry Andric // The input import library is used to manage consistency of the secure entry
116806c3fb27SDimitry Andric // points. The output import library is for new and updated secure entry points.
116906c3fb27SDimitry Andric //
117006c3fb27SDimitry Andric // The symbol convention that identifies secure entry functions is the prefix
117106c3fb27SDimitry Andric // __acle_se_ for a symbol called name the linker is expected to create a secure
117206c3fb27SDimitry Andric // gateway veneer if symbols __acle_se_name and name have the same address.
117306c3fb27SDimitry Andric // After creating a secure gateway veneer the symbol name labels the secure
117406c3fb27SDimitry Andric // gateway veneer and the __acle_se_name labels the function definition.
117506c3fb27SDimitry Andric //
117606c3fb27SDimitry Andric // The LLD implementation:
117706c3fb27SDimitry Andric // - Reads an existing import library with importCmseSymbols().
117806c3fb27SDimitry Andric // - Determines which new secure gateway veneers to create and redirects calls
117906c3fb27SDimitry Andric //   within the secure state to the __acle_se_ prefixed symbol with
118006c3fb27SDimitry Andric //   processArmCmseSymbols().
118106c3fb27SDimitry Andric // - Models the SG veneers as a synthetic section.
118206c3fb27SDimitry Andric 
118306c3fb27SDimitry Andric // Initialize symbols. symbols is a parallel array to the corresponding ELF
118406c3fb27SDimitry Andric // symbol table.
importCmseSymbols()118506c3fb27SDimitry Andric template <class ELFT> void ObjFile<ELFT>::importCmseSymbols() {
118606c3fb27SDimitry Andric   ArrayRef<Elf_Sym> eSyms = getELFSyms<ELFT>();
118706c3fb27SDimitry Andric   // Error for local symbols. The symbol at index 0 is LOCAL. So skip it.
118806c3fb27SDimitry Andric   for (size_t i = 1, end = firstGlobal; i != end; ++i) {
118906c3fb27SDimitry Andric     errorOrWarn("CMSE symbol '" + CHECK(eSyms[i].getName(stringTable), this) +
119006c3fb27SDimitry Andric                 "' in import library '" + toString(this) + "' is not global");
119106c3fb27SDimitry Andric   }
119206c3fb27SDimitry Andric 
119306c3fb27SDimitry Andric   for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) {
119406c3fb27SDimitry Andric     const Elf_Sym &eSym = eSyms[i];
119506c3fb27SDimitry Andric     Defined *sym = reinterpret_cast<Defined *>(make<SymbolUnion>());
119606c3fb27SDimitry Andric 
119706c3fb27SDimitry Andric     // Initialize symbol fields.
119806c3fb27SDimitry Andric     memset(sym, 0, sizeof(Symbol));
119906c3fb27SDimitry Andric     sym->setName(CHECK(eSyms[i].getName(stringTable), this));
120006c3fb27SDimitry Andric     sym->value = eSym.st_value;
120106c3fb27SDimitry Andric     sym->size = eSym.st_size;
120206c3fb27SDimitry Andric     sym->type = eSym.getType();
120306c3fb27SDimitry Andric     sym->binding = eSym.getBinding();
120406c3fb27SDimitry Andric     sym->stOther = eSym.st_other;
120506c3fb27SDimitry Andric 
120606c3fb27SDimitry Andric     if (eSym.st_shndx != SHN_ABS) {
120706c3fb27SDimitry Andric       error("CMSE symbol '" + sym->getName() + "' in import library '" +
120806c3fb27SDimitry Andric             toString(this) + "' is not absolute");
120906c3fb27SDimitry Andric       continue;
121006c3fb27SDimitry Andric     }
121106c3fb27SDimitry Andric 
121206c3fb27SDimitry Andric     if (!(eSym.st_value & 1) || (eSym.getType() != STT_FUNC)) {
121306c3fb27SDimitry Andric       error("CMSE symbol '" + sym->getName() + "' in import library '" +
121406c3fb27SDimitry Andric             toString(this) + "' is not a Thumb function definition");
121506c3fb27SDimitry Andric       continue;
121606c3fb27SDimitry Andric     }
121706c3fb27SDimitry Andric 
121806c3fb27SDimitry Andric     if (symtab.cmseImportLib.count(sym->getName())) {
121906c3fb27SDimitry Andric       error("CMSE symbol '" + sym->getName() +
122006c3fb27SDimitry Andric             "' is multiply defined in import library '" + toString(this) + "'");
122106c3fb27SDimitry Andric       continue;
122206c3fb27SDimitry Andric     }
122306c3fb27SDimitry Andric 
122406c3fb27SDimitry Andric     if (eSym.st_size != ACLESESYM_SIZE) {
122506c3fb27SDimitry Andric       warn("CMSE symbol '" + sym->getName() + "' in import library '" +
122606c3fb27SDimitry Andric            toString(this) + "' does not have correct size of " +
122706c3fb27SDimitry Andric            Twine(ACLESESYM_SIZE) + " bytes");
122806c3fb27SDimitry Andric     }
122906c3fb27SDimitry Andric 
123006c3fb27SDimitry Andric     symtab.cmseImportLib[sym->getName()] = sym;
123106c3fb27SDimitry Andric   }
123206c3fb27SDimitry Andric }
123306c3fb27SDimitry Andric 
123406c3fb27SDimitry Andric // Check symbol attributes of the acleSeSym, sym pair.
123506c3fb27SDimitry Andric // Both symbols should be global/weak Thumb code symbol definitions.
checkCmseSymAttributes(Symbol * acleSeSym,Symbol * sym)123606c3fb27SDimitry Andric static std::string checkCmseSymAttributes(Symbol *acleSeSym, Symbol *sym) {
123706c3fb27SDimitry Andric   auto check = [](Symbol *s, StringRef type) -> std::optional<std::string> {
123806c3fb27SDimitry Andric     auto d = dyn_cast_or_null<Defined>(s);
123906c3fb27SDimitry Andric     if (!(d && d->isFunc() && (d->value & 1)))
124006c3fb27SDimitry Andric       return (Twine(toString(s->file)) + ": cmse " + type + " symbol '" +
124106c3fb27SDimitry Andric               s->getName() + "' is not a Thumb function definition")
124206c3fb27SDimitry Andric           .str();
124306c3fb27SDimitry Andric     if (!d->section)
124406c3fb27SDimitry Andric       return (Twine(toString(s->file)) + ": cmse " + type + " symbol '" +
124506c3fb27SDimitry Andric               s->getName() + "' cannot be an absolute symbol")
124606c3fb27SDimitry Andric           .str();
124706c3fb27SDimitry Andric     return std::nullopt;
124806c3fb27SDimitry Andric   };
124906c3fb27SDimitry Andric   for (auto [sym, type] :
125006c3fb27SDimitry Andric        {std::make_pair(acleSeSym, "special"), std::make_pair(sym, "entry")})
125106c3fb27SDimitry Andric     if (auto err = check(sym, type))
125206c3fb27SDimitry Andric       return *err;
125306c3fb27SDimitry Andric   return "";
125406c3fb27SDimitry Andric }
125506c3fb27SDimitry Andric 
125606c3fb27SDimitry Andric // Look for [__acle_se_<sym>, <sym>] pairs, as specified in the Cortex-M
125706c3fb27SDimitry Andric // Security Extensions specification.
125806c3fb27SDimitry Andric // 1) <sym> : A standard function name.
125906c3fb27SDimitry Andric // 2) __acle_se_<sym> : A special symbol that prefixes the standard function
126006c3fb27SDimitry Andric // name with __acle_se_.
126106c3fb27SDimitry Andric // Both these symbols are Thumb function symbols with external linkage.
126206c3fb27SDimitry Andric // <sym> may be redefined in .gnu.sgstubs.
processArmCmseSymbols()126306c3fb27SDimitry Andric void elf::processArmCmseSymbols() {
126406c3fb27SDimitry Andric   if (!config->cmseImplib)
126506c3fb27SDimitry Andric     return;
126606c3fb27SDimitry Andric   // Only symbols with external linkage end up in symtab, so no need to do
126706c3fb27SDimitry Andric   // linkage checks. Only check symbol type.
126806c3fb27SDimitry Andric   for (Symbol *acleSeSym : symtab.getSymbols()) {
12695f757f3fSDimitry Andric     if (!acleSeSym->getName().starts_with(ACLESESYM_PREFIX))
127006c3fb27SDimitry Andric       continue;
127106c3fb27SDimitry Andric     // If input object build attributes do not support CMSE, error and disable
127206c3fb27SDimitry Andric     // further scanning for <sym>, __acle_se_<sym> pairs.
127306c3fb27SDimitry Andric     if (!config->armCMSESupport) {
127406c3fb27SDimitry Andric       error("CMSE is only supported by ARMv8-M architecture or later");
127506c3fb27SDimitry Andric       config->cmseImplib = false;
127606c3fb27SDimitry Andric       break;
127706c3fb27SDimitry Andric     }
127806c3fb27SDimitry Andric 
127906c3fb27SDimitry Andric     // Try to find the associated symbol definition.
128006c3fb27SDimitry Andric     // Symbol must have external linkage.
128106c3fb27SDimitry Andric     StringRef name = acleSeSym->getName().substr(std::strlen(ACLESESYM_PREFIX));
128206c3fb27SDimitry Andric     Symbol *sym = symtab.find(name);
128306c3fb27SDimitry Andric     if (!sym) {
128406c3fb27SDimitry Andric       error(toString(acleSeSym->file) + ": cmse special symbol '" +
128506c3fb27SDimitry Andric             acleSeSym->getName() +
128606c3fb27SDimitry Andric             "' detected, but no associated entry function definition '" + name +
128706c3fb27SDimitry Andric             "' with external linkage found");
128806c3fb27SDimitry Andric       continue;
128906c3fb27SDimitry Andric     }
129006c3fb27SDimitry Andric 
129106c3fb27SDimitry Andric     std::string errMsg = checkCmseSymAttributes(acleSeSym, sym);
129206c3fb27SDimitry Andric     if (!errMsg.empty()) {
129306c3fb27SDimitry Andric       error(errMsg);
129406c3fb27SDimitry Andric       continue;
129506c3fb27SDimitry Andric     }
129606c3fb27SDimitry Andric 
129706c3fb27SDimitry Andric     // <sym> may be redefined later in the link in .gnu.sgstubs
129806c3fb27SDimitry Andric     symtab.cmseSymMap[name] = {acleSeSym, sym};
129906c3fb27SDimitry Andric   }
130006c3fb27SDimitry Andric 
130106c3fb27SDimitry Andric   // If this is an Arm CMSE secure app, replace references to entry symbol <sym>
130206c3fb27SDimitry Andric   // with its corresponding special symbol __acle_se_<sym>.
130306c3fb27SDimitry Andric   parallelForEach(ctx.objectFiles, [&](InputFile *file) {
130406c3fb27SDimitry Andric     MutableArrayRef<Symbol *> syms = file->getMutableSymbols();
130506c3fb27SDimitry Andric     for (size_t i = 0, e = syms.size(); i != e; ++i) {
130606c3fb27SDimitry Andric       StringRef symName = syms[i]->getName();
130706c3fb27SDimitry Andric       if (symtab.cmseSymMap.count(symName))
130806c3fb27SDimitry Andric         syms[i] = symtab.cmseSymMap[symName].acleSeSym;
130906c3fb27SDimitry Andric     }
131006c3fb27SDimitry Andric   });
131106c3fb27SDimitry Andric }
131206c3fb27SDimitry Andric 
131306c3fb27SDimitry Andric class elf::ArmCmseSGVeneer {
131406c3fb27SDimitry Andric public:
ArmCmseSGVeneer(Symbol * sym,Symbol * acleSeSym,std::optional<uint64_t> addr=std::nullopt)131506c3fb27SDimitry Andric   ArmCmseSGVeneer(Symbol *sym, Symbol *acleSeSym,
131606c3fb27SDimitry Andric                   std::optional<uint64_t> addr = std::nullopt)
131706c3fb27SDimitry Andric       : sym(sym), acleSeSym(acleSeSym), entAddr{addr} {}
131806c3fb27SDimitry Andric   static const size_t size{ACLESESYM_SIZE};
getAddr() const131906c3fb27SDimitry Andric   const std::optional<uint64_t> getAddr() const { return entAddr; };
132006c3fb27SDimitry Andric 
132106c3fb27SDimitry Andric   Symbol *sym;
132206c3fb27SDimitry Andric   Symbol *acleSeSym;
132306c3fb27SDimitry Andric   uint64_t offset = 0;
132406c3fb27SDimitry Andric 
132506c3fb27SDimitry Andric private:
132606c3fb27SDimitry Andric   const std::optional<uint64_t> entAddr;
132706c3fb27SDimitry Andric };
132806c3fb27SDimitry Andric 
ArmCmseSGSection()132906c3fb27SDimitry Andric ArmCmseSGSection::ArmCmseSGSection()
133006c3fb27SDimitry Andric     : SyntheticSection(llvm::ELF::SHF_ALLOC | llvm::ELF::SHF_EXECINSTR,
133106c3fb27SDimitry Andric                        llvm::ELF::SHT_PROGBITS,
133206c3fb27SDimitry Andric                        /*alignment=*/32, ".gnu.sgstubs") {
133306c3fb27SDimitry Andric   entsize = ACLESESYM_SIZE;
133406c3fb27SDimitry Andric   // The range of addresses used in the CMSE import library should be fixed.
133506c3fb27SDimitry Andric   for (auto &[_, sym] : symtab.cmseImportLib) {
133606c3fb27SDimitry Andric     if (impLibMaxAddr <= sym->value)
133706c3fb27SDimitry Andric       impLibMaxAddr = sym->value + sym->size;
133806c3fb27SDimitry Andric   }
133906c3fb27SDimitry Andric   if (symtab.cmseSymMap.empty())
134006c3fb27SDimitry Andric     return;
134106c3fb27SDimitry Andric   addMappingSymbol();
134206c3fb27SDimitry Andric   for (auto &[_, entryFunc] : symtab.cmseSymMap)
134306c3fb27SDimitry Andric     addSGVeneer(cast<Defined>(entryFunc.acleSeSym),
134406c3fb27SDimitry Andric                 cast<Defined>(entryFunc.sym));
134506c3fb27SDimitry Andric   for (auto &[_, sym] : symtab.cmseImportLib) {
134606c3fb27SDimitry Andric     if (!symtab.inCMSEOutImpLib.count(sym->getName()))
134706c3fb27SDimitry Andric       warn("entry function '" + sym->getName() +
134806c3fb27SDimitry Andric            "' from CMSE import library is not present in secure application");
134906c3fb27SDimitry Andric   }
135006c3fb27SDimitry Andric 
135106c3fb27SDimitry Andric   if (!symtab.cmseImportLib.empty() && config->cmseOutputLib.empty()) {
135206c3fb27SDimitry Andric     for (auto &[_, entryFunc] : symtab.cmseSymMap) {
135306c3fb27SDimitry Andric       Symbol *sym = entryFunc.sym;
135406c3fb27SDimitry Andric       if (!symtab.inCMSEOutImpLib.count(sym->getName()))
135506c3fb27SDimitry Andric         warn("new entry function '" + sym->getName() +
135606c3fb27SDimitry Andric              "' introduced but no output import library specified");
135706c3fb27SDimitry Andric     }
135806c3fb27SDimitry Andric   }
135906c3fb27SDimitry Andric }
136006c3fb27SDimitry Andric 
addSGVeneer(Symbol * acleSeSym,Symbol * sym)136106c3fb27SDimitry Andric void ArmCmseSGSection::addSGVeneer(Symbol *acleSeSym, Symbol *sym) {
136206c3fb27SDimitry Andric   entries.emplace_back(acleSeSym, sym);
136306c3fb27SDimitry Andric   if (symtab.cmseImportLib.count(sym->getName()))
136406c3fb27SDimitry Andric     symtab.inCMSEOutImpLib[sym->getName()] = true;
136506c3fb27SDimitry Andric   // Symbol addresses different, nothing to do.
136606c3fb27SDimitry Andric   if (acleSeSym->file != sym->file ||
136706c3fb27SDimitry Andric       cast<Defined>(*acleSeSym).value != cast<Defined>(*sym).value)
136806c3fb27SDimitry Andric     return;
136906c3fb27SDimitry Andric   // Only secure symbols with values equal to that of it's non-secure
137006c3fb27SDimitry Andric   // counterpart needs to be in the .gnu.sgstubs section.
137106c3fb27SDimitry Andric   ArmCmseSGVeneer *ss = nullptr;
137206c3fb27SDimitry Andric   if (symtab.cmseImportLib.count(sym->getName())) {
137306c3fb27SDimitry Andric     Defined *impSym = symtab.cmseImportLib[sym->getName()];
137406c3fb27SDimitry Andric     ss = make<ArmCmseSGVeneer>(sym, acleSeSym, impSym->value);
137506c3fb27SDimitry Andric   } else {
137606c3fb27SDimitry Andric     ss = make<ArmCmseSGVeneer>(sym, acleSeSym);
137706c3fb27SDimitry Andric     ++newEntries;
137806c3fb27SDimitry Andric   }
137906c3fb27SDimitry Andric   sgVeneers.emplace_back(ss);
138006c3fb27SDimitry Andric }
138106c3fb27SDimitry Andric 
writeTo(uint8_t * buf)138206c3fb27SDimitry Andric void ArmCmseSGSection::writeTo(uint8_t *buf) {
138306c3fb27SDimitry Andric   for (ArmCmseSGVeneer *s : sgVeneers) {
138406c3fb27SDimitry Andric     uint8_t *p = buf + s->offset;
138506c3fb27SDimitry Andric     write16(p + 0, 0xe97f); // SG
138606c3fb27SDimitry Andric     write16(p + 2, 0xe97f);
138706c3fb27SDimitry Andric     write16(p + 4, 0xf000); // B.W S
138806c3fb27SDimitry Andric     write16(p + 6, 0xb000);
138906c3fb27SDimitry Andric     target->relocateNoSym(p + 4, R_ARM_THM_JUMP24,
139006c3fb27SDimitry Andric                           s->acleSeSym->getVA() -
139106c3fb27SDimitry Andric                               (getVA() + s->offset + s->size));
139206c3fb27SDimitry Andric   }
139306c3fb27SDimitry Andric }
139406c3fb27SDimitry Andric 
addMappingSymbol()139506c3fb27SDimitry Andric void ArmCmseSGSection::addMappingSymbol() {
139606c3fb27SDimitry Andric   addSyntheticLocal("$t", STT_NOTYPE, /*off=*/0, /*size=*/0, *this);
139706c3fb27SDimitry Andric }
139806c3fb27SDimitry Andric 
getSize() const139906c3fb27SDimitry Andric size_t ArmCmseSGSection::getSize() const {
140006c3fb27SDimitry Andric   if (sgVeneers.empty())
140106c3fb27SDimitry Andric     return (impLibMaxAddr ? impLibMaxAddr - getVA() : 0) + newEntries * entsize;
140206c3fb27SDimitry Andric 
140306c3fb27SDimitry Andric   return entries.size() * entsize;
140406c3fb27SDimitry Andric }
140506c3fb27SDimitry Andric 
finalizeContents()140606c3fb27SDimitry Andric void ArmCmseSGSection::finalizeContents() {
140706c3fb27SDimitry Andric   if (sgVeneers.empty())
140806c3fb27SDimitry Andric     return;
140906c3fb27SDimitry Andric 
141006c3fb27SDimitry Andric   auto it =
141106c3fb27SDimitry Andric       std::stable_partition(sgVeneers.begin(), sgVeneers.end(),
141206c3fb27SDimitry Andric                             [](auto *i) { return i->getAddr().has_value(); });
141306c3fb27SDimitry Andric   std::sort(sgVeneers.begin(), it, [](auto *a, auto *b) {
141406c3fb27SDimitry Andric     return a->getAddr().value() < b->getAddr().value();
141506c3fb27SDimitry Andric   });
141606c3fb27SDimitry Andric   // This is the partition of the veneers with fixed addresses.
141706c3fb27SDimitry Andric   uint64_t addr = (*sgVeneers.begin())->getAddr().has_value()
141806c3fb27SDimitry Andric                       ? (*sgVeneers.begin())->getAddr().value()
141906c3fb27SDimitry Andric                       : getVA();
142006c3fb27SDimitry Andric   // Check if the start address of '.gnu.sgstubs' correspond to the
142106c3fb27SDimitry Andric   // linker-synthesized veneer with the lowest address.
142206c3fb27SDimitry Andric   if ((getVA() & ~1) != (addr & ~1)) {
142306c3fb27SDimitry Andric     error("start address of '.gnu.sgstubs' is different from previous link");
142406c3fb27SDimitry Andric     return;
142506c3fb27SDimitry Andric   }
142606c3fb27SDimitry Andric 
142706c3fb27SDimitry Andric   for (size_t i = 0; i < sgVeneers.size(); ++i) {
142806c3fb27SDimitry Andric     ArmCmseSGVeneer *s = sgVeneers[i];
142906c3fb27SDimitry Andric     s->offset = i * s->size;
143006c3fb27SDimitry Andric     Defined(file, StringRef(), s->sym->binding, s->sym->stOther, s->sym->type,
143106c3fb27SDimitry Andric             s->offset | 1, s->size, this)
143206c3fb27SDimitry Andric         .overwrite(*s->sym);
143306c3fb27SDimitry Andric   }
143406c3fb27SDimitry Andric }
143506c3fb27SDimitry Andric 
143606c3fb27SDimitry Andric // Write the CMSE import library to disk.
143706c3fb27SDimitry Andric // The CMSE import library is a relocatable object with only a symbol table.
143806c3fb27SDimitry Andric // The symbols are copies of the (absolute) symbols of the secure gateways
143906c3fb27SDimitry Andric // in the executable output by this link.
144006c3fb27SDimitry Andric // See Arm® v8-M Security Extensions: Requirements on Development Tools
144106c3fb27SDimitry Andric // https://developer.arm.com/documentation/ecm0359818/latest
writeARMCmseImportLib()144206c3fb27SDimitry Andric template <typename ELFT> void elf::writeARMCmseImportLib() {
144306c3fb27SDimitry Andric   StringTableSection *shstrtab =
144406c3fb27SDimitry Andric       make<StringTableSection>(".shstrtab", /*dynamic=*/false);
144506c3fb27SDimitry Andric   StringTableSection *strtab =
144606c3fb27SDimitry Andric       make<StringTableSection>(".strtab", /*dynamic=*/false);
144706c3fb27SDimitry Andric   SymbolTableBaseSection *impSymTab = make<SymbolTableSection<ELFT>>(*strtab);
144806c3fb27SDimitry Andric 
144906c3fb27SDimitry Andric   SmallVector<std::pair<OutputSection *, SyntheticSection *>, 0> osIsPairs;
145006c3fb27SDimitry Andric   osIsPairs.emplace_back(make<OutputSection>(strtab->name, 0, 0), strtab);
145106c3fb27SDimitry Andric   osIsPairs.emplace_back(make<OutputSection>(impSymTab->name, 0, 0), impSymTab);
145206c3fb27SDimitry Andric   osIsPairs.emplace_back(make<OutputSection>(shstrtab->name, 0, 0), shstrtab);
145306c3fb27SDimitry Andric 
145406c3fb27SDimitry Andric   std::sort(symtab.cmseSymMap.begin(), symtab.cmseSymMap.end(),
145506c3fb27SDimitry Andric             [](const auto &a, const auto &b) -> bool {
145606c3fb27SDimitry Andric               return a.second.sym->getVA() < b.second.sym->getVA();
145706c3fb27SDimitry Andric             });
145806c3fb27SDimitry Andric   // Copy the secure gateway entry symbols to the import library symbol table.
145906c3fb27SDimitry Andric   for (auto &p : symtab.cmseSymMap) {
146006c3fb27SDimitry Andric     Defined *d = cast<Defined>(p.second.sym);
14617a6dacacSDimitry Andric     impSymTab->addSymbol(makeDefined(
14627a6dacacSDimitry Andric         ctx.internalFile, d->getName(), d->computeBinding(),
14637a6dacacSDimitry Andric         /*stOther=*/0, STT_FUNC, d->getVA(), d->getSize(), nullptr));
146406c3fb27SDimitry Andric   }
146506c3fb27SDimitry Andric 
146606c3fb27SDimitry Andric   size_t idx = 0;
146706c3fb27SDimitry Andric   uint64_t off = sizeof(typename ELFT::Ehdr);
146806c3fb27SDimitry Andric   for (auto &[osec, isec] : osIsPairs) {
146906c3fb27SDimitry Andric     osec->sectionIndex = ++idx;
147006c3fb27SDimitry Andric     osec->recordSection(isec);
147106c3fb27SDimitry Andric     osec->finalizeInputSections();
147206c3fb27SDimitry Andric     osec->shName = shstrtab->addString(osec->name);
147306c3fb27SDimitry Andric     osec->size = isec->getSize();
147406c3fb27SDimitry Andric     isec->finalizeContents();
147506c3fb27SDimitry Andric     osec->offset = alignToPowerOf2(off, osec->addralign);
147606c3fb27SDimitry Andric     off = osec->offset + osec->size;
147706c3fb27SDimitry Andric   }
147806c3fb27SDimitry Andric 
147906c3fb27SDimitry Andric   const uint64_t sectionHeaderOff = alignToPowerOf2(off, config->wordsize);
148006c3fb27SDimitry Andric   const auto shnum = osIsPairs.size() + 1;
148106c3fb27SDimitry Andric   const uint64_t fileSize =
148206c3fb27SDimitry Andric       sectionHeaderOff + shnum * sizeof(typename ELFT::Shdr);
148306c3fb27SDimitry Andric   const unsigned flags =
148406c3fb27SDimitry Andric       config->mmapOutputFile ? 0 : (unsigned)FileOutputBuffer::F_no_mmap;
148506c3fb27SDimitry Andric   unlinkAsync(config->cmseOutputLib);
148606c3fb27SDimitry Andric   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
148706c3fb27SDimitry Andric       FileOutputBuffer::create(config->cmseOutputLib, fileSize, flags);
148806c3fb27SDimitry Andric   if (!bufferOrErr) {
148906c3fb27SDimitry Andric     error("failed to open " + config->cmseOutputLib + ": " +
149006c3fb27SDimitry Andric           llvm::toString(bufferOrErr.takeError()));
149106c3fb27SDimitry Andric     return;
149206c3fb27SDimitry Andric   }
149306c3fb27SDimitry Andric 
149406c3fb27SDimitry Andric   // Write the ELF Header
149506c3fb27SDimitry Andric   std::unique_ptr<FileOutputBuffer> &buffer = *bufferOrErr;
149606c3fb27SDimitry Andric   uint8_t *const buf = buffer->getBufferStart();
149706c3fb27SDimitry Andric   memcpy(buf, "\177ELF", 4);
149806c3fb27SDimitry Andric   auto *eHdr = reinterpret_cast<typename ELFT::Ehdr *>(buf);
149906c3fb27SDimitry Andric   eHdr->e_type = ET_REL;
150006c3fb27SDimitry Andric   eHdr->e_entry = 0;
150106c3fb27SDimitry Andric   eHdr->e_shoff = sectionHeaderOff;
150206c3fb27SDimitry Andric   eHdr->e_ident[EI_CLASS] = ELFCLASS32;
150306c3fb27SDimitry Andric   eHdr->e_ident[EI_DATA] = config->isLE ? ELFDATA2LSB : ELFDATA2MSB;
150406c3fb27SDimitry Andric   eHdr->e_ident[EI_VERSION] = EV_CURRENT;
150506c3fb27SDimitry Andric   eHdr->e_ident[EI_OSABI] = config->osabi;
150606c3fb27SDimitry Andric   eHdr->e_ident[EI_ABIVERSION] = 0;
150706c3fb27SDimitry Andric   eHdr->e_machine = EM_ARM;
150806c3fb27SDimitry Andric   eHdr->e_version = EV_CURRENT;
150906c3fb27SDimitry Andric   eHdr->e_flags = config->eflags;
151006c3fb27SDimitry Andric   eHdr->e_ehsize = sizeof(typename ELFT::Ehdr);
151106c3fb27SDimitry Andric   eHdr->e_phnum = 0;
151206c3fb27SDimitry Andric   eHdr->e_shentsize = sizeof(typename ELFT::Shdr);
151306c3fb27SDimitry Andric   eHdr->e_phoff = 0;
151406c3fb27SDimitry Andric   eHdr->e_phentsize = 0;
151506c3fb27SDimitry Andric   eHdr->e_shnum = shnum;
151606c3fb27SDimitry Andric   eHdr->e_shstrndx = shstrtab->getParent()->sectionIndex;
151706c3fb27SDimitry Andric 
151806c3fb27SDimitry Andric   // Write the section header table.
151906c3fb27SDimitry Andric   auto *sHdrs = reinterpret_cast<typename ELFT::Shdr *>(buf + eHdr->e_shoff);
152006c3fb27SDimitry Andric   for (auto &[osec, _] : osIsPairs)
152106c3fb27SDimitry Andric     osec->template writeHeaderTo<ELFT>(++sHdrs);
152206c3fb27SDimitry Andric 
152306c3fb27SDimitry Andric   // Write section contents to a mmap'ed file.
152406c3fb27SDimitry Andric   {
152506c3fb27SDimitry Andric     parallel::TaskGroup tg;
152606c3fb27SDimitry Andric     for (auto &[osec, _] : osIsPairs)
152706c3fb27SDimitry Andric       osec->template writeTo<ELFT>(buf + osec->offset, tg);
152806c3fb27SDimitry Andric   }
152906c3fb27SDimitry Andric 
153006c3fb27SDimitry Andric   if (auto e = buffer->commit())
153106c3fb27SDimitry Andric     fatal("failed to write output '" + buffer->getPath() +
153206c3fb27SDimitry Andric           "': " + toString(std::move(e)));
153306c3fb27SDimitry Andric }
153406c3fb27SDimitry Andric 
getARMTargetInfo()15355ffd83dbSDimitry Andric TargetInfo *elf::getARMTargetInfo() {
15360b57cec5SDimitry Andric   static ARM target;
15370b57cec5SDimitry Andric   return &target;
15380b57cec5SDimitry Andric }
153906c3fb27SDimitry Andric 
154006c3fb27SDimitry Andric template void elf::writeARMCmseImportLib<ELF32LE>();
154106c3fb27SDimitry Andric template void elf::writeARMCmseImportLib<ELF32BE>();
154206c3fb27SDimitry Andric template void elf::writeARMCmseImportLib<ELF64LE>();
154306c3fb27SDimitry Andric template void elf::writeARMCmseImportLib<ELF64BE>();
154406c3fb27SDimitry Andric 
154506c3fb27SDimitry Andric template void ObjFile<ELF32LE>::importCmseSymbols();
154606c3fb27SDimitry Andric template void ObjFile<ELF32BE>::importCmseSymbols();
154706c3fb27SDimitry Andric template void ObjFile<ELF64LE>::importCmseSymbols();
154806c3fb27SDimitry Andric template void ObjFile<ELF64BE>::importCmseSymbols();
1549