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,28 @@ +# 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{{$}} +# CHECK-NEXT: ProgramHeaderEntrySize: 32{{$}} +# CHECK: SectionHeaderEntrySize: 40{{$}} Index: llvm/test/tools/llvm-elfabi/write-elf32le-ehdr.test =================================================================== --- /dev/null +++ llvm/test/tools/llvm-elfabi/write-elf32le-ehdr.test @@ -0,0 +1,28 @@ +# 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{{$}} +# CHECK-NEXT: ProgramHeaderEntrySize: 32{{$}} +# CHECK: SectionHeaderEntrySize: 40{{$}} Index: llvm/test/tools/llvm-elfabi/write-elf64be-ehdr.test =================================================================== --- /dev/null +++ llvm/test/tools/llvm-elfabi/write-elf64be-ehdr.test @@ -0,0 +1,28 @@ +# 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{{$}} +# CHECK-NEXT: ProgramHeaderEntrySize: 56{{$}} +# CHECK: SectionHeaderEntrySize: 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,28 @@ +# 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{{$}} +# CHECK-NEXT: ProgramHeaderEntrySize: 56{{$}} +# CHECK: SectionHeaderEntrySize: 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,9 +12,12 @@ #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" +#include + using llvm::MemoryBufferRef; using llvm::object::ELFObjectFile; @@ -22,8 +25,9 @@ using namespace llvm::object; using namespace llvm::ELF; -namespace llvm { -namespace elfabi { +namespace { + +using namespace llvm::elfabi; // Simple struct to hold relevant .dynamic entries. struct DynamicEntries { @@ -38,13 +42,36 @@ Optional GnuHash; }; +class CommandWriter { +private: + uint64_t MaxLocation = 0; + std::vector> Commands; +public: + template + void add(uint64_t Offset, const T& Value) { + MaxLocation = std::max(Offset + sizeof(T), MaxLocation); + Commands.emplace_back([Offset, Value](uint8_t *Data) { + *reinterpret_cast(Data + Offset) = Value; + }); + } + + uint64_t size() const { + return MaxLocation; + } + + void write(uint8_t* Data) { + for (const auto &Cmd : Commands) + Cmd(Data); + } +}; + /// This function behaves similarly to StringRef::substr(), but attempts to /// terminate the returned StringRef at the first null terminator. If no null /// terminator is found, an error is returned. /// /// @param Str Source string to create a substring from. /// @param Offset The start index of the desired substring. -static Expected terminatedSubstr(StringRef Str, size_t Offset) { +Expected terminatedSubstr(StringRef Str, size_t Offset) { size_t StrEnd = Str.find('\0', Offset); if (StrEnd == StringLiteral::npos) { return createError( @@ -78,7 +105,7 @@ /// @param Dyn Target DynamicEntries struct to populate. /// @param DynTable Source dynamic table. template -static Error populateDynamic(DynamicEntries &Dyn, +Error populateDynamic(DynamicEntries &Dyn, typename ELFT::DynRange DynTable) { if (DynTable.empty()) return createError("No .dynamic section found"); @@ -151,7 +178,7 @@ /// /// @param Table The GNU hash table for .dynsym. template -static uint64_t getDynSymtabSize(const typename ELFT::GnuHash &Table) { +uint64_t getDynSymtabSize(const typename ELFT::GnuHash &Table) { using Elf_Word = typename ELFT::Word; if (Table.nbuckets == 0) return Table.symndx + 1; @@ -179,7 +206,7 @@ /// @param Dyn Entries with the locations of hash tables. /// @param ElfFile The ElfFile that the section contents reside in. template -static Expected getNumSyms(DynamicEntries &Dyn, +Expected getNumSyms(DynamicEntries &Dyn, const ELFFile &ElfFile) { using Elf_Hash = typename ELFT::Hash; using Elf_GnuHash = typename ELFT::GnuHash; @@ -209,7 +236,7 @@ /// Other symbol types are mapped to ELFSymbolType::Unknown. /// /// @param Info Binary symbol st_info to extract symbol type from. -static ELFSymbolType convertInfoToType(uint8_t Info) { +ELFSymbolType convertInfoToType(uint8_t Info) { Info = Info & 0xf; switch (Info) { case ELF::STT_NOTYPE: @@ -231,7 +258,7 @@ /// @param SymName The desired name of the ELFSymbol. /// @param RawSym ELFT::Sym to extract symbol information from. template -static ELFSymbol createELFSym(StringRef SymName, +ELFSymbol createELFSym(StringRef SymName, const typename ELFT::Sym &RawSym) { ELFSymbol TargetSym(SymName); uint8_t Binding = RawSym.getBinding(); @@ -258,7 +285,7 @@ /// @param DynSym Range of dynamic symbols to add to TargetStub. /// @param DynStr StringRef to the dynamic string table. template -static Error populateSymbols(ELFStub &TargetStub, +Error populateSymbols(ELFStub &TargetStub, const typename ELFT::SymRange DynSym, StringRef DynStr) { // Skips the first symbol since it's the NULL symbol. @@ -286,7 +313,7 @@ /// Returns a new ELFStub with all members populated from an ELFObjectFile. /// @param ElfObj Source ELFObjectFile. template -static Expected> +Expected> buildStub(const ELFObjectFile &ElfObj) { using Elf_Dyn_Range = typename ELFT::DynRange; using Elf_Phdr_Range = typename ELFT::PhdrRange; @@ -367,6 +394,121 @@ return std::move(DestStub); } +/// 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 +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 a CommandWriter that can be +/// written to a buffer and will represent a full stub written to disk. +/// +/// @param FilePath File path for writing the ELF binary. +/// @param Stub Source ELFStub to generate a binary ELF stub from. +template +CommandWriter makeELFBinaryWriter(const ELFStub &Stub) { + using Elf_Ehdr = typename ELFT::Ehdr; + CommandWriter out; + + Elf_Ehdr ElfHeader; + initELFHeader(ElfHeader, Stub.Arch); + out.add(0, ElfHeader); + // TODO: Not everyone will want all of these. We should add options that + // let us configure which of these are written and which are not. For + // instance at a first pass only the section headers, .dynsym, and .dynstr + // are all that are needed. + // 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 out; +} + +/// 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 +Error writeELFBinaryToFile(StringRef FilePath, const ELFStub &Stub) { + CommandWriter Writer = makeELFBinaryWriter(Stub); + Expected> BufOrError = + FileOutputBuffer::create(FilePath, Writer.size()); + 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); + Writer.write(Buf->getBufferStart()); + + if (Error FileWriteError = Buf->commit()) + return FileWriteError; + + return Error::success(); +} + +} // end namespace + +namespace llvm { +namespace elfabi { + +// 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"); +} + Expected> readELFFile(MemoryBufferRef Buf) { Expected> BinOrErr = createBinary(Buf); if (!BinOrErr) { 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); + } + } }