1 //===-- BPFELFObjectWriter.cpp - BPF ELF Writer ---------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "MCTargetDesc/BPFMCTargetDesc.h" 10 #include "llvm/BinaryFormat/ELF.h" 11 #include "llvm/MC/MCELFObjectWriter.h" 12 #include "llvm/MC/MCFixup.h" 13 #include "llvm/MC/MCObjectWriter.h" 14 #include "llvm/MC/MCValue.h" 15 #include "llvm/Support/ErrorHandling.h" 16 #include <cstdint> 17 18 using namespace llvm; 19 20 namespace { 21 22 class BPFELFObjectWriter : public MCELFObjectTargetWriter { 23 public: 24 BPFELFObjectWriter(uint8_t OSABI); 25 ~BPFELFObjectWriter() override = default; 26 27 protected: 28 unsigned getRelocType(MCContext &Ctx, const MCValue &Target, 29 const MCFixup &Fixup, bool IsPCRel) const override; 30 }; 31 32 } // end anonymous namespace 33 34 BPFELFObjectWriter::BPFELFObjectWriter(uint8_t OSABI) 35 : MCELFObjectTargetWriter(/*Is64Bit*/ true, OSABI, ELF::EM_BPF, 36 /*HasRelocationAddend*/ false) {} 37 38 unsigned BPFELFObjectWriter::getRelocType(MCContext &Ctx, const MCValue &Target, 39 const MCFixup &Fixup, 40 bool IsPCRel) const { 41 // determine the type of the relocation 42 switch ((unsigned)Fixup.getKind()) { 43 default: 44 llvm_unreachable("invalid fixup kind!"); 45 case FK_SecRel_8: 46 return ELF::R_BPF_64_64; 47 case FK_PCRel_4: 48 case FK_SecRel_4: 49 return ELF::R_BPF_64_32; 50 case FK_Data_8: 51 return ELF::R_BPF_64_64; 52 case FK_Data_4: 53 // .BTF.ext generates FK_Data_4 relocations for 54 // insn offset by creating temporary labels. 55 // The insn offset is within the code section and 56 // already been fulfilled by applyFixup(). No 57 // further relocation is needed. 58 if (const MCSymbolRefExpr *A = Target.getSymA()) { 59 if (A->getSymbol().isTemporary()) { 60 MCSection &Section = A->getSymbol().getSection(); 61 const MCSectionELF *SectionELF = dyn_cast<MCSectionELF>(&Section); 62 assert(SectionELF && "Null section for reloc symbol"); 63 64 // The reloc symbol should be in text section. 65 unsigned Flags = SectionELF->getFlags(); 66 if ((Flags & ELF::SHF_ALLOC) && (Flags & ELF::SHF_EXECINSTR)) 67 return ELF::R_BPF_NONE; 68 } 69 } 70 return ELF::R_BPF_64_32; 71 } 72 } 73 74 std::unique_ptr<MCObjectTargetWriter> 75 llvm::createBPFELFObjectWriter(uint8_t OSABI) { 76 return llvm::make_unique<BPFELFObjectWriter>(OSABI); 77 } 78