Index: llvm/test/tools/llvm-elfabi/invalid-bin-target.test =================================================================== --- /dev/null +++ llvm/test/tools/llvm-elfabi/invalid-bin-target.test @@ -0,0 +1,10 @@ +# RUN: not llvm-elfabi %s --output-target=nope %t 2>&1 | FileCheck %s + +--- !tapi-tbe +SoName: somelib.so +TbeVersion: 1.0 +Arch: x86_64 +Symbols: {} +... + +# CHECK: llvm-elfabi: for the -output-target option: Cannot find option named 'nope'! Index: llvm/test/tools/llvm-elfabi/missing-bin-target.test =================================================================== --- /dev/null +++ llvm/test/tools/llvm-elfabi/missing-bin-target.test @@ -0,0 +1,10 @@ +# RUN: not llvm-elfabi %s %t 2>&1 | FileCheck %s + +--- !tapi-tbe +SoName: somelib.so +TbeVersion: 1.0 +Arch: x86_64 +Symbols: {} +... + +# CHECK: No binary output target specified. Index: llvm/test/tools/llvm-elfabi/write-elf32be-ehdr.test =================================================================== --- /dev/null +++ llvm/test/tools/llvm-elfabi/write-elf32be-ehdr.test @@ -0,0 +1,26 @@ +# RUN: llvm-elfabi %s --output-target=elf32-big %t +# RUN: llvm-readobj --file-headers %t | FileCheck %s + +--- !tapi-tbe +TbeVersion: 1.0 +Arch: x86_64 +Symbols: {} +... + +# CHECK: ElfHeader { +# CHECK-NEXT: Ident { +# CHECK-NEXT: Magic: (7F 45 4C 46) +# CHECK-NEXT: Class: 32-bit (0x1) +# CHECK-NEXT: DataEncoding: BigEndian (0x2) +# CHECK-NEXT: FileVersion: 1 +# CHECK-NEXT: OS/ABI: SystemV (0x0) +# CHECK-NEXT: ABIVersion: 0 +# CHECK-NEXT: Unused: (00 00 00 00 00 00 00) +# CHECK-NEXT: } +# CHECK-NEXT: Type: SharedObject (0x3) +# CHECK-NEXT: Machine: EM_X86_64 (0x3E) +# CHECK-NEXT: Version: 1 +# CHECK-NEXT: Entry: 0x0 +# CHECK: Flags [ (0x0) +# CHECK-NEXT: ] +# CHECK-NEXT: HeaderSize: 52 Index: llvm/test/tools/llvm-elfabi/write-elf32le-ehdr.test =================================================================== --- /dev/null +++ llvm/test/tools/llvm-elfabi/write-elf32le-ehdr.test @@ -0,0 +1,26 @@ +# RUN: llvm-elfabi %s --output-target=elf32-little %t +# RUN: llvm-readobj --file-headers %t | FileCheck %s + +--- !tapi-tbe +TbeVersion: 1.0 +Arch: x86_64 +Symbols: {} +... + +# CHECK: ElfHeader { +# CHECK-NEXT: Ident { +# CHECK-NEXT: Magic: (7F 45 4C 46) +# CHECK-NEXT: Class: 32-bit (0x1) +# CHECK-NEXT: DataEncoding: LittleEndian (0x1) +# CHECK-NEXT: FileVersion: 1 +# CHECK-NEXT: OS/ABI: SystemV (0x0) +# CHECK-NEXT: ABIVersion: 0 +# CHECK-NEXT: Unused: (00 00 00 00 00 00 00) +# CHECK-NEXT: } +# CHECK-NEXT: Type: SharedObject (0x3) +# CHECK-NEXT: Machine: EM_X86_64 (0x3E) +# CHECK-NEXT: Version: 1 +# CHECK-NEXT: Entry: 0x0 +# CHECK: Flags [ (0x0) +# CHECK-NEXT: ] +# CHECK-NEXT: HeaderSize: 52 Index: llvm/test/tools/llvm-elfabi/write-elf64be-ehdr.test =================================================================== --- /dev/null +++ llvm/test/tools/llvm-elfabi/write-elf64be-ehdr.test @@ -0,0 +1,26 @@ +# RUN: llvm-elfabi %s --output-target=elf64-big %t +# RUN: llvm-readobj --file-headers %t | FileCheck %s + +--- !tapi-tbe +TbeVersion: 1.0 +Arch: x86_64 +Symbols: {} +... + +# CHECK: ElfHeader { +# CHECK-NEXT: Ident { +# CHECK-NEXT: Magic: (7F 45 4C 46) +# CHECK-NEXT: Class: 64-bit (0x2) +# CHECK-NEXT: DataEncoding: BigEndian (0x2) +# CHECK-NEXT: FileVersion: 1 +# CHECK-NEXT: OS/ABI: SystemV (0x0) +# CHECK-NEXT: ABIVersion: 0 +# CHECK-NEXT: Unused: (00 00 00 00 00 00 00) +# CHECK-NEXT: } +# CHECK-NEXT: Type: SharedObject (0x3) +# CHECK-NEXT: Machine: EM_X86_64 (0x3E) +# CHECK-NEXT: Version: 1 +# CHECK-NEXT: Entry: 0x0 +# CHECK: Flags [ (0x0) +# CHECK-NEXT: ] +# CHECK-NEXT: HeaderSize: 64 Index: llvm/test/tools/llvm-elfabi/write-elf64le-ehdr.test =================================================================== --- /dev/null +++ llvm/test/tools/llvm-elfabi/write-elf64le-ehdr.test @@ -0,0 +1,26 @@ +# RUN: llvm-elfabi %s --output-target=elf64-little %t +# RUN: llvm-readobj --file-headers %t | FileCheck %s + +--- !tapi-tbe +TbeVersion: 1.0 +Arch: AArch64 +Symbols: {} +... + +# CHECK: ElfHeader { +# CHECK-NEXT: Ident { +# CHECK-NEXT: Magic: (7F 45 4C 46) +# CHECK-NEXT: Class: 64-bit (0x2) +# CHECK-NEXT: DataEncoding: LittleEndian (0x1) +# CHECK-NEXT: FileVersion: 1 +# CHECK-NEXT: OS/ABI: SystemV (0x0) +# CHECK-NEXT: ABIVersion: 0 +# CHECK-NEXT: Unused: (00 00 00 00 00 00 00) +# CHECK-NEXT: } +# CHECK-NEXT: Type: SharedObject (0x3) +# CHECK-NEXT: Machine: EM_AARCH64 (0xB7) +# CHECK-NEXT: Version: 1 +# CHECK-NEXT: Entry: 0x0 +# CHECK: Flags [ (0x0) +# CHECK-NEXT: ] +# CHECK-NEXT: HeaderSize: 64 Index: llvm/tools/llvm-elfabi/ELFObjHandler.h =================================================================== --- llvm/tools/llvm-elfabi/ELFObjHandler.h +++ llvm/tools/llvm-elfabi/ELFObjHandler.h @@ -23,9 +23,26 @@ namespace elfabi { +enum class ELFTarget { + ELF32LE, + ELF32BE, + ELF64LE, + ELF64BE +}; + /// Attempt to read a binary ELF file from a MemoryBuffer. Expected> readELFFile(MemoryBufferRef Buf); +/// Attempt to write a binary ELF stub. +/// This function determines appropriate ELFType using the passed ELFTarget and +/// then writes a binary ELF stub to a specified file path. +/// +/// @param FilePath File path for writing the ELF binary. +/// @param Stub Source ELFStub to generate a binary ELF stub from. +/// @param OutputFormat Target ELFType to write binary as. +Error writeBinaryStub(StringRef FilePath, const ELFStub &Stub, + ELFTarget OutputFormat); + } // end namespace elfabi } // end namespace llvm Index: llvm/tools/llvm-elfabi/ELFObjHandler.cpp =================================================================== --- llvm/tools/llvm-elfabi/ELFObjHandler.cpp +++ llvm/tools/llvm-elfabi/ELFObjHandler.cpp @@ -12,6 +12,7 @@ #include "llvm/Object/ELFTypes.h" #include "llvm/Support/Errc.h" #include "llvm/Support/Error.h" +#include "llvm/Support/FileOutputBuffer.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/TextAPI/ELF/ELFStub.h" @@ -210,5 +211,129 @@ return createStringError(errc::not_supported, "Unsupported binary format"); } +/// This function calculates the size a binary ELF stub will be. +/// `Stub` is used to determine the exact binary size. This calculation includes +/// padding that may be added between sections to ensure proper alignment. +/// +/// @param Stub The ELFStub that will be used for size calculation. +/// @return Size (in bytes) of the final binary stub. +template static size_t getBinarySize(const ELFStub &Stub) { + using Elf_Ehdr = typename ELFT::Ehdr; + return sizeof(Elf_Ehdr); + // TODO: Calculate size of section headers. + // TODO: Calculate size of program headers. + // TODO: Calculate size of .dynsym section. + // TODO: Calculate size of .dynstr section. + // TODO: Calculate size of .dynamic section. + // TODO: Calculate size of .shstrtab section. +} + +/// This initializes an ELF file header with information specific to a binary +/// dynamic shared object. +/// Offsets, indexes, links, etc. for section and program headers are just +/// zero-initialized as they will be updated elsewhere. +/// +/// @param ElfHeader Target ELFT::Ehdr to populate. +/// @param Machine Target architecture (e_machine from ELF specifications). +template +static void initELFHeader(typename ELFT::Ehdr &ElfHeader, uint16_t Machine) { + using Elf_Ehdr = typename ELFT::Ehdr; + using Elf_Phdr = typename ELFT::Phdr; + using Elf_Shdr = typename ELFT::Shdr; + + memset(&ElfHeader, 0, sizeof(Elf_Ehdr)); + // ELF identification + ElfHeader.e_ident[EI_MAG0] = 0x7f; // ELFMAG0 + ElfHeader.e_ident[EI_MAG1] = 'E'; // ELFMAG1 + ElfHeader.e_ident[EI_MAG2] = 'L'; // ELFMAG2 + ElfHeader.e_ident[EI_MAG3] = 'F'; // ELFMAG3 + ElfHeader.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32; + bool IsLittleEndian = ELFT::TargetEndianness == support::little; + ElfHeader.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB; + ElfHeader.e_ident[EI_VERSION] = EV_CURRENT; + ElfHeader.e_ident[EI_OSABI] = ELFOSABI_NONE; + ElfHeader.e_ident[EI_ABIVERSION] = 0; + + // remainder of ELF header + ElfHeader.e_type = ET_DYN; + ElfHeader.e_machine = Machine; + ElfHeader.e_version = EV_CURRENT; + ElfHeader.e_entry = 0; + ElfHeader.e_flags = 0; + ElfHeader.e_ehsize = sizeof(Elf_Ehdr); + ElfHeader.e_phentsize = sizeof(Elf_Phdr); + ElfHeader.e_shentsize = sizeof(Elf_Shdr); +} + +/// This function uses an ELFStub to generate an ELF binary stub that is written +/// to a buffer. +/// +/// @param FilePath File path for writing the ELF binary. +/// @param Stub Source ELFStub to generate a binary ELF stub from. +template +static Error writeELFBinaryToBuffer(const ELFStub &Stub, + MutableArrayRef BufRef) { + using Elf_Ehdr = typename ELFT::Ehdr; + uint8_t *Buf = BufRef.data(); + Elf_Ehdr *ElfHeader = reinterpret_cast(Buf); + initELFHeader(*ElfHeader, Stub.Arch); + // TODO: Write section headers. + // TODO: Write program headers. + // TODO: Write .dynsym section. + // TODO: Write .dynstr section. + // TODO: Write .dynamic section. + // TODO: Write .shstrtab section. + return Error::success(); +} + +/// This function opens a file for writing and then writes a binary ELF stub to +/// the file. +/// +/// @param FilePath File path for writing the ELF binary. +/// @param Stub Source ELFStub to generate a binary ELF stub from. +template +static Error writeELFBinaryToFile(StringRef FilePath, const ELFStub &Stub) { + // Open file for writing. + Expected> BufOrError = + FileOutputBuffer::create(FilePath, getBinarySize(Stub)); + if (!BufOrError) { + Error FileReadError = BufOrError.takeError(); + std::string Message; + raw_string_ostream Stream(Message); + Stream << FileReadError; + Stream << " when trying to open `" << FilePath <<"` for writing"; + consumeError(std::move(FileReadError)); + return createStringError(errc::invalid_argument, Stream.str().c_str()); + } + + // Write binary to file. + std::unique_ptr Buf = std::move(*BufOrError); + MutableArrayRef BufRef(Buf->getBufferStart(), Buf->getBufferSize()); + if (Error BinaryWriteError = writeELFBinaryToBuffer(Stub, BufRef)) + return BinaryWriteError; + + if (Error FileWriteError = Buf->commit()) + return FileWriteError; + + return Error::success(); +} + +// This function wraps the ELFT writeELFBinaryToFile() so writeBinaryStub() +// can be called without having to use ELFType templates directly. +Error writeBinaryStub(StringRef FilePath, const ELFStub &Stub, + ELFTarget OutputFormat) { + if (OutputFormat == ELFTarget::ELF32LE) { + return writeELFBinaryToFile(FilePath, Stub); + } else if (OutputFormat == ELFTarget::ELF32BE) { + return writeELFBinaryToFile(FilePath, Stub); + } else if (OutputFormat == ELFTarget::ELF64LE) { + return writeELFBinaryToFile(FilePath, Stub); + } else if (OutputFormat == ELFTarget::ELF64BE) { + return writeELFBinaryToFile(FilePath, Stub); + } + return createStringError(errc::invalid_argument, + "Invalid binary output target"); +} + } // end namespace elfabi } // end namespace llvm Index: llvm/tools/llvm-elfabi/llvm-elfabi.cpp =================================================================== --- llvm/tools/llvm-elfabi/llvm-elfabi.cpp +++ llvm/tools/llvm-elfabi/llvm-elfabi.cpp @@ -49,6 +49,17 @@ "soname", cl::desc("Manually set the DT_SONAME entry of any emitted files"), cl::value_desc("name")); +cl::opt BinaryOutputTarget( + "output-target", cl::desc("Create a binary stub for the specified target"), + cl::values(clEnumValN(ELFTarget::ELF32LE, "elf32-little", + "32-bit little-endian ELF stub"), + clEnumValN(ELFTarget::ELF32BE, "elf32-big", + "32-bit big-endian ELF stub"), + clEnumValN(ELFTarget::ELF64LE, "elf64-little", + "64-bit little-endian ELF stub"), + clEnumValN(ELFTarget::ELF64BE, "elf64-big", + "64-bit big-endian ELF stub"))); +cl::opt BinaryOutputFilePath(cl::Positional, cl::desc("output")); /// writeTBE() writes a Text-Based ELF stub to a file using the latest version /// of the YAML parser. @@ -127,16 +138,32 @@ std::unique_ptr TargetStub = std::move(StubOrErr.get()); + // Change SoName before emitting stubs. + if (SOName.getNumOccurrences() == 1) { + TargetStub->SoName = SOName; + } + // Write out .tbe file. if (EmitTBE.getNumOccurrences() == 1) { TargetStub->TbeVersion = TBEVersionCurrent; - if (SOName.getNumOccurrences() == 1) { - TargetStub->SoName = SOName; - } Error TBEWriteError = writeTBE(EmitTBE, *TargetStub); if (TBEWriteError) { WithColor::error() << TBEWriteError << "\n"; exit(1); } } + + // Write out binary ELF stub. + if (BinaryOutputFilePath.getNumOccurrences() == 1) { + if (BinaryOutputTarget.getNumOccurrences() == 0) { + WithColor::error() << "No binary output target specified.\n"; + exit(1); + } + Error BinaryWriteError = writeBinaryStub(BinaryOutputFilePath, *TargetStub, + BinaryOutputTarget); + if (BinaryWriteError) { + WithColor::error() << BinaryWriteError << "\n"; + exit(1); + } + } }