1 //===-- BPFELFObjectWriter.cpp - BPF ELF Writer ---------------------------===//
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
7 //===----------------------------------------------------------------------===//
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"
22 class BPFELFObjectWriter
: public MCELFObjectTargetWriter
{
24 BPFELFObjectWriter(uint8_t OSABI
);
25 ~BPFELFObjectWriter() override
= default;
28 unsigned getRelocType(MCContext
&Ctx
, const MCValue
&Target
,
29 const MCFixup
&Fixup
, bool IsPCRel
) const override
;
32 } // end anonymous namespace
34 BPFELFObjectWriter::BPFELFObjectWriter(uint8_t OSABI
)
35 : MCELFObjectTargetWriter(/*Is64Bit*/ true, OSABI
, ELF::EM_BPF
,
36 /*HasRelocationAddend*/ false) {}
38 unsigned BPFELFObjectWriter::getRelocType(MCContext
&Ctx
, const MCValue
&Target
,
41 // determine the type of the relocation
42 switch (Fixup
.getKind()) {
44 llvm_unreachable("invalid fixup kind!");
46 return ELF::R_BPF_64_64
;
49 return ELF::R_BPF_64_32
;
51 return ELF::R_BPF_64_64
;
53 if (const MCSymbolRefExpr
*A
= Target
.getSymA()) {
54 const MCSymbol
&Sym
= A
->getSymbol();
56 if (Sym
.isDefined()) {
57 MCSection
&Section
= Sym
.getSection();
58 const MCSectionELF
*SectionELF
= dyn_cast
<MCSectionELF
>(&Section
);
59 assert(SectionELF
&& "Null section for reloc symbol");
61 unsigned Flags
= SectionELF
->getFlags();
63 if (Sym
.isTemporary()) {
64 // .BTF.ext generates FK_Data_4 relocations for
65 // insn offset by creating temporary labels.
66 // The insn offset is within the code section and
67 // already been fulfilled by applyFixup(). No
68 // further relocation is needed.
69 // The reloc symbol should be in text section.
70 if ((Flags
& ELF::SHF_ALLOC
) && (Flags
& ELF::SHF_EXECINSTR
))
71 return ELF::R_BPF_NONE
;
73 // .BTF generates FK_Data_4 relocations for variable
74 // offset in DataSec kind. Similar to the above .BTF.ext
75 // insn offset, no further relocation is needed.
76 // The reloc symbol should be in data section.
77 if ((Flags
& ELF::SHF_ALLOC
) && (Flags
& ELF::SHF_WRITE
))
78 return ELF::R_BPF_NONE
;
82 return ELF::R_BPF_64_32
;
86 std::unique_ptr
<MCObjectTargetWriter
>
87 llvm::createBPFELFObjectWriter(uint8_t OSABI
) {
88 return std::make_unique
<BPFELFObjectWriter
>(OSABI
);