Path: blob/main/contrib/llvm-project/llvm/lib/Target/BPF/MCTargetDesc/BPFELFObjectWriter.cpp
35294 views
//===-- BPFELFObjectWriter.cpp - BPF ELF Writer ---------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "MCTargetDesc/BPFMCTargetDesc.h"9#include "llvm/BinaryFormat/ELF.h"10#include "llvm/MC/MCELFObjectWriter.h"11#include "llvm/MC/MCFixup.h"12#include "llvm/MC/MCObjectWriter.h"13#include "llvm/MC/MCValue.h"14#include "llvm/Support/ErrorHandling.h"15#include <cstdint>1617using namespace llvm;1819namespace {2021class BPFELFObjectWriter : public MCELFObjectTargetWriter {22public:23BPFELFObjectWriter(uint8_t OSABI);24~BPFELFObjectWriter() override = default;2526protected:27unsigned getRelocType(MCContext &Ctx, const MCValue &Target,28const MCFixup &Fixup, bool IsPCRel) const override;29};3031} // end anonymous namespace3233BPFELFObjectWriter::BPFELFObjectWriter(uint8_t OSABI)34: MCELFObjectTargetWriter(/*Is64Bit*/ true, OSABI, ELF::EM_BPF,35/*HasRelocationAddend*/ false) {}3637unsigned BPFELFObjectWriter::getRelocType(MCContext &Ctx, const MCValue &Target,38const MCFixup &Fixup,39bool IsPCRel) const {40// determine the type of the relocation41switch (Fixup.getKind()) {42default:43llvm_unreachable("invalid fixup kind!");44case FK_SecRel_8:45// LD_imm64 instruction.46return ELF::R_BPF_64_64;47case FK_PCRel_4:48// CALL instruction.49return ELF::R_BPF_64_32;50case FK_Data_8:51return ELF::R_BPF_64_ABS64;52case FK_Data_4:53if (const MCSymbolRefExpr *A = Target.getSymA()) {54const MCSymbol &Sym = A->getSymbol();5556if (Sym.isDefined()) {57MCSection &Section = Sym.getSection();58const MCSectionELF *SectionELF = dyn_cast<MCSectionELF>(&Section);59assert(SectionELF && "Null section for reloc symbol");6061unsigned Flags = SectionELF->getFlags();6263if (Sym.isTemporary()) {64// .BTF.ext generates FK_Data_4 relocations for65// insn offset by creating temporary labels.66// The reloc symbol should be in text section.67// Use a different relocation to instruct ExecutionEngine68// RuntimeDyld not to do relocation for it, yet still to69// allow lld to do proper adjustment when merging sections.70if ((Flags & ELF::SHF_ALLOC) && (Flags & ELF::SHF_EXECINSTR))71return ELF::R_BPF_64_NODYLD32;72} else {73// .BTF generates FK_Data_4 relocations for variable74// offset in DataSec kind.75// The reloc symbol should be in data section.76if ((Flags & ELF::SHF_ALLOC) && (Flags & ELF::SHF_WRITE))77return ELF::R_BPF_64_NODYLD32;78}79}80}81return ELF::R_BPF_64_ABS32;82}83}8485std::unique_ptr<MCObjectTargetWriter>86llvm::createBPFELFObjectWriter(uint8_t OSABI) {87return std::make_unique<BPFELFObjectWriter>(OSABI);88}899091