llvm.org GIT mirror llvm / 18952b8
[elfabi] Introduce tool for ELF TextAPI Follow up for D53051 This patch introduces the tool associated with the ELF implementation of TextAPI (previously llvm-tapi, renamed for better distinction). This tool will house a number of features related to enalysis and manipulation of shared object's exposed interfaces. The first major feature for this tool is support for producing binary stubs that are useful for compile-time linking of shared objects. This patch introduces beginnings of support for reading binary ELF objects to work towards that goal. Added: - elfabi tool. - support for reading architecture from a binary ELF file into an ELFStub. - Support for writing .tbe files. Differential Revision: https://reviews.llvm.org/D55352 git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@350341 91177308-0d34-0410-b5e6-96231b3b80d8 Armando Montanez 8 months ago
15 changed file(s) with 482 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
6060 dsymutil
6161 llvm-dwarfdump
6262 llvm-dwp
63 llvm-elfabi
6364 llvm-exegesis
6465 llvm-extract
6566 llvm-isel-fuzzer
0 # RUN: yaml2obj %s > %t
1 # RUN: llvm-elfabi %t --emit-tbe=- | FileCheck %s
2
3 !ELF
4 FileHeader:
5 Class: ELFCLASS64
6 Data: ELFDATA2LSB
7 Type: ET_DYN
8 Machine: EM_X86_64
9
10 # CHECK: --- !tapi-tbe
11 # CHECK-NEXT: TbeVersion: {{[1-9]\d*\.(0|([1-9]\d*))}}
12 # CHECK-NEXT: Arch: x86_64
13 # CHECK-NEXT: Symbols: {}
14 # CHECK-NEXT: ...
0 # RUN: not llvm-elfabi %s.NotAFileInTestingDir --emit-tbe=%t 2>&1 | FileCheck %s
1
2 This file will not be read. An invalid file path is fed to llvm-elfabi.
3
4 # CHECK: error: Could not open `{{.*}}.NotAFileInTestingDir`
0 # RUN: not llvm-elfabi %s --emit-tbe=%t 2>&1 | FileCheck %s
1
2 This is just some text that cannot be read by llvm-elfabi.
3
4 # CHECK: The file was not recognized as a valid object file
5 # CHECK: YAML failed reading as TBE
6 # CHECK: No file readers succeeded reading `{{.*}}` (unsupported/malformed file?)
0 # RUN: yaml2obj %s > %t
1 # RUN: llvm-elfabi %t --emit-tbe=- --soname=best.so | FileCheck %s
2
3 !ELF
4 FileHeader:
5 Class: ELFCLASS64
6 Data: ELFDATA2LSB
7 Type: ET_DYN
8 Machine: EM_AARCH64
9
10 # CHECK: --- !tapi-tbe
11 # CHECK-NEXT: TbeVersion: {{[1-9]\d*\.(0|([1-9]\d*))}}
12 # CHECK-NEXT: SoName: best.so
13 # CHECK-NEXT: Arch: AArch64
14 # CHECK-NEXT: Symbols: {}
15 # CHECK-NEXT: ...
0 # RUN: llvm-elfabi %s --emit-tbe=- | FileCheck %s
1
2 --- !tapi-tbe
3 TbeVersion: 1.0
4 Arch: AArch64
5 Symbols: {}
6 ...
7
8 # As the tbe reader/writer is updated, update this check to ensure --emit-tbe
9 # uses the latest tbe writer by default.
10
11 # CHECK: --- !tapi-tbe
12 # CHECK-NEXT: TbeVersion: 1.0
0 # RUN: llvm-elfabi %s --emit-tbe=- | FileCheck %s
1
2 --- !tapi-tbe
3 SoName: somelib.so
4 TbeVersion: 1.0
5 Arch: x86_64
6 Symbols:
7 foo: { Type: Func }
8 bar: { Type: Object, Size: 42 }
9 baz: { Type: Object, Size: 8 }
10 not: { Type: Object, Undefined: true, Size: 128 }
11 nor: { Type: Func, Undefined: true }
12 ...
13
14 # CHECK: --- !tapi-tbe
15 # CHECK-NEXT: TbeVersion: {{[1-9]\d*\.(0|([1-9]\d*))}}
16 # CHECK-NEXT: SoName: somelib.so
17 # CHECK-NEXT: Arch: x86_64
18 # CHECK-NEXT: Symbols:
19 # CHECK-NEXT: bar: { Type: Object, Size: 42 }
20 # CHECK-NEXT: baz: { Type: Object, Size: 8 }
21 # CHECK-NEXT: foo: { Type: Func }
22 # CHECK-NEXT: nor: { Type: Func, Undefined: true }
23 # CHECK-NEXT: not: { Type: Object, Size: 128, Undefined: true }
24 # CHECK-NEXT: ...
3131 llvm-dis
3232 llvm-dwarfdump
3333 llvm-dwp
34 llvm-elfabi
3435 llvm-exegesis
3536 llvm-extract
3637 llvm-jitlistener
0 set(LLVM_LINK_COMPONENTS
1 Object
2 Support
3 TextAPI
4 )
5
6 add_llvm_tool(llvm-elfabi
7 ELFObjHandler.cpp
8 ErrorCollector.cpp
9 llvm-elfabi.cpp
10 )
0 //===- ELFObjHandler.cpp --------------------------------------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===-----------------------------------------------------------------------===/
8
9 #include "ELFObjHandler.h"
10 #include "llvm/Object/Binary.h"
11 #include "llvm/Object/ELFObjectFile.h"
12 #include "llvm/Object/ELFTypes.h"
13 #include "llvm/Support/Errc.h"
14 #include "llvm/Support/Error.h"
15 #include "llvm/Support/MemoryBuffer.h"
16 #include "llvm/TextAPI/ELF/ELFStub.h"
17
18 using llvm::MemoryBufferRef;
19 using llvm::object::ELFObjectFile;
20
21 using namespace llvm;
22 using namespace llvm::object;
23 using namespace llvm::elfabi;
24 using namespace llvm::ELF;
25
26 namespace llvm {
27 namespace elfabi {
28
29 /// Returns a new ELFStub with all members populated from an ELFObjectFile.
30 /// @param ElfObj Source ELFObjectFile.
31 template
32 Expected>
33 buildStub(const ELFObjectFile &ElfObj) {
34 std::unique_ptr DestStub = make_unique();
35 const ELFFile *ElfFile = ElfObj.getELFFile();
36
37 DestStub->Arch = ElfFile->getHeader()->e_machine;
38
39 // TODO: Populate SoName from .dynamic entries and linked string table.
40 // TODO: Populate NeededLibs from .dynamic entries and linked string table.
41 // TODO: Populate Symbols from .dynsym table and linked string table.
42
43 return std::move(DestStub);
44 }
45
46 Expected> readELFFile(MemoryBufferRef Buf) {
47 Expected> BinOrErr = createBinary(Buf);
48 if (!BinOrErr) {
49 return BinOrErr.takeError();
50 }
51
52 Binary *Bin = BinOrErr->get();
53 if (auto Obj = dyn_cast>(Bin)) {
54 return buildStub(*Obj);
55 } else if (auto Obj = dyn_cast>(Bin)) {
56 return buildStub(*Obj);
57 } else if (auto Obj = dyn_cast>(Bin)) {
58 return buildStub(*Obj);
59 } else if (auto Obj = dyn_cast>(Bin)) {
60 return buildStub(*Obj);
61 }
62
63 return createStringError(errc::not_supported, "Unsupported binary format");
64 }
65
66 } // end namespace elfabi
67 } // end namespace llvm
0 //===- ELFObjHandler.h ------------------------------------------*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===-----------------------------------------------------------------------===/
8 ///
9 /// This supports reading and writing of elf dynamic shared objects.
10 ///
11 //===-----------------------------------------------------------------------===/
12
13 #ifndef LLVM_TOOLS_ELFABI_ELFOBJHANDLER_H
14 #define LLVM_TOOLS_ELFABI_ELFOBJHANDLER_H
15
16 #include "llvm/Object/ELFObjectFile.h"
17 #include "llvm/Object/ELFTypes.h"
18 #include "llvm/TextAPI/ELF/ELFStub.h"
19
20 namespace llvm {
21
22 class MemoryBuffer;
23
24 namespace elfabi {
25
26 /// Attempt to read a binary ELF file from a MemoryBuffer.
27 Expected> readELFFile(MemoryBufferRef Buf);
28
29 } // end namespace elfabi
30 } // end namespace llvm
31
32 #endif // LLVM_TOOLS_ELFABI_ELFOBJHANDLER_H
0 //===- ErrorCollector.cpp -------------------------------------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===-----------------------------------------------------------------------===/
8
9 #include "ErrorCollector.h"
10 #include "llvm/Support/Errc.h"
11 #include "llvm/Support/Error.h"
12 #include "llvm/Support/raw_ostream.h"
13 #include "llvm/Support/WithColor.h"
14 #include
15
16 using namespace llvm;
17 using namespace llvm::elfabi;
18
19 void ErrorCollector::escalateToFatal() {
20 ErrorsAreFatal = true;
21 }
22
23 void ErrorCollector::addError(Error &&Err, StringRef Tag) {
24 if (Err) {
25 Errors.push_back(std::move(Err));
26 Tags.push_back(Tag.str());
27 }
28 }
29
30 Error ErrorCollector::makeError() {
31 // TODO: Make this return something (an AggregateError?) that gives more
32 // individual control over each error and which might be of interest.
33 Error JoinedErrors = Error::success();
34 for (Error &E : Errors) {
35 JoinedErrors = joinErrors(std::move(JoinedErrors), std::move(E));
36 }
37 Errors.clear();
38 Tags.clear();
39 return JoinedErrors;
40 }
41
42 void ErrorCollector::log(raw_ostream &OS) {
43 OS << "Encountered multiple errors:\n";
44 for (size_t i = 0; i < Errors.size(); ++i) {
45 WithColor::error(OS) << "(" << Tags[i] << ") " << Errors[i];
46 if (i != Errors.size() - 1)
47 OS << "\n";
48 }
49 }
50
51 bool ErrorCollector::allErrorsHandled() const {
52 return Errors.empty();
53 }
54
55 ErrorCollector::~ErrorCollector() {
56 if (ErrorsAreFatal && !allErrorsHandled())
57 fatalUnhandledError();
58
59 for (Error &E : Errors) {
60 consumeError(std::move(E));
61 }
62 }
63
64 LLVM_ATTRIBUTE_NORETURN void ErrorCollector::fatalUnhandledError() {
65 errs() << "Program aborted due to unhandled Error(s):\n";
66 log(errs());
67 errs() << "\n";
68 abort();
69 }
0 //===- ErrorCollector.h -----------------------------------------*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===-----------------------------------------------------------------------===/
8 ///
9 /// This class collects errors that should be reported or ignored in aggregate.
10 ///
11 /// Like llvm::Error, an ErrorCollector cannot be copied. Unlike llvm::Error,
12 /// an ErrorCollector may be destroyed if it was originally constructed to treat
13 /// errors as non-fatal. In this case, all Errors are consumed upon destruction.
14 /// An ErrorCollector may be initially constructed (or escalated) such that
15 /// errors are treated as fatal. This causes a crash if an attempt is made to
16 /// delete the ErrorCollector when some Errors have not been retrieved via
17 /// makeError().
18 ///
19 //===-----------------------------------------------------------------------===/
20
21 #ifndef LLVM_TOOLS_ELFABI_ERRORCOLLECTOR_H
22 #define LLVM_TOOLS_ELFABI_ERRORCOLLECTOR_H
23
24 #include "llvm/Support/Error.h"
25 #include
26
27 namespace llvm {
28 namespace elfabi {
29
30 class ErrorCollector {
31 public:
32 /// Upon destruction, an ErrorCollector will crash if UseFatalErrors=true and
33 /// there are remaining errors that haven't been fetched by makeError().
34 ErrorCollector(bool UseFatalErrors = true) : ErrorsAreFatal(UseFatalErrors) {}
35 // Don't allow copying.
36 ErrorCollector(const ErrorCollector &Stub) = delete;
37 ErrorCollector &operator=(const ErrorCollector &Other) = delete;
38 ~ErrorCollector();
39
40 // TODO: Add move constructor and operator= when a testable situation arises.
41
42 /// Returns a single error that contains messages for all stored Errors.
43 Error makeError();
44
45 /// Adds an error with a descriptive tag that helps with identification.
46 /// If the error is an Error::success(), it is checked and discarded.
47 void addError(Error &&E, StringRef Tag);
48
49 /// This ensures an ErrorCollector will treat unhandled errors as fatal.
50 /// This function should be called if errors that usually can be ignored
51 /// are suddenly of concern (i.e. attempt multiple things that return Error,
52 /// but only care about the Errors if no attempt succeeds).
53 void escalateToFatal();
54
55 private:
56 /// Logs all errors to a raw_ostream.
57 void log(raw_ostream &OS);
58
59 /// Returns true if all errors have been retrieved through makeError(), or
60 /// false if errors have been added since the last makeError() call.
61 bool allErrorsHandled() const;
62
63 /// Dump output and crash.
64 LLVM_ATTRIBUTE_NORETURN void fatalUnhandledError();
65
66 bool ErrorsAreFatal;
67 std::vector Errors;
68 std::vector Tags;
69 };
70
71 } // end namespace elfabi
72 } // end namespace llvm
73
74 #endif // LLVM_TOOLS_ELFABI_ERRORCOLLECTOR_H
0 ;===- ./tools/llvm-elfabi/LLVMBuild.txt ------------------------*- Conf -*--===;
1 ;
2 ; The LLVM Compiler Infrastructure
3 ;
4 ; This file is distributed under the University of Illinois Open Source
5 ; License. See LICENSE.TXT for details.
6 ;
7 ;===------------------------------------------------------------------------===;
8 ;
9 ; This is an LLVMBuild description file for the components in this subdirectory.
10 ;
11 ; For more information on the LLVMBuild system, please see:
12 ;
13 ; http://llvm.org/docs/LLVMBuild.html
14 ;
15 ;===------------------------------------------------------------------------===;
16
17 [component_0]
18 type = Tool
19 name = llvm-elfabi
20 parent = Tools
21 required_libraries = Object Support TextAPI
0 //===- llvm-elfabi.cpp ----------------------------------------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===-----------------------------------------------------------------------===/
8
9 #include "ELFObjHandler.h"
10 #include "ErrorCollector.h"
11 #include "llvm/Support/CommandLine.h"
12 #include "llvm/Support/Errc.h"
13 #include "llvm/Support/FileOutputBuffer.h"
14 #include "llvm/Support/MemoryBuffer.h"
15 #include "llvm/Support/Path.h"
16 #include "llvm/Support/raw_ostream.h"
17 #include "llvm/Support/WithColor.h"
18 #include "llvm/TextAPI/ELF/TBEHandler.h"
19 #include
20
21 using namespace llvm;
22 using namespace llvm::elfabi;
23
24 // Command line flags:
25 cl::opt InputFilePath(cl::Positional, cl::desc("input"),
26 cl::Required);
27 cl::opt
28 EmitTBE("emit-tbe",
29 cl::desc("Emit a text-based ELF stub (.tbe) from the input file"),
30 cl::value_desc("path"));
31 cl::opt SOName(
32 "soname",
33 cl::desc("Manually set the DT_SONAME entry of any emitted files"),
34 cl::value_desc("name"));
35
36 /// writeTBE() writes a Text-Based ELF stub to a file using the latest version
37 /// of the YAML parser.
38 static Error writeTBE(StringRef FilePath, ELFStub &Stub) {
39 std::error_code SysErr;
40
41 // Open file for writing.
42 raw_fd_ostream Out(FilePath, SysErr);
43 if (SysErr)
44 return createStringError(SysErr, "Couldn't open `%s` for writing",
45 FilePath.data());
46 // Write file.
47 Error YAMLErr = writeTBEToOutputStream(Out, Stub);
48 if (YAMLErr)
49 return YAMLErr;
50
51 return Error::success();
52 }
53
54 /// readInputFile populates an ELFStub by attempting to read the
55 /// input file using both the TBE and binary ELF parsers.
56 static Expected> readInputFile(StringRef FilePath) {
57 // Read in file.
58 ErrorOr> BufOrError =
59 MemoryBuffer::getFile(FilePath);
60 if (!BufOrError) {
61 return createStringError(BufOrError.getError(), "Could not open `%s`",
62 FilePath.data());
63 }
64
65 std::unique_ptr FileReadBuffer = std::move(*BufOrError);
66 ErrorCollector EC(/*UseFatalErrors=*/false);
67
68 // First try to read as a binary (fails fast if not binary).
69 Expected> StubFromELF =
70 readELFFile(FileReadBuffer->getMemBufferRef());
71 if (StubFromELF) {
72 return std::move(*StubFromELF);
73 }
74 EC.addError(StubFromELF.takeError(), "BinaryRead");
75
76 // Fall back to reading as a tbe.
77 Expected> StubFromTBE =
78 readTBEFromBuffer(FileReadBuffer->getBuffer());
79 if (StubFromTBE) {
80 return std::move(*StubFromTBE);
81 }
82 EC.addError(StubFromTBE.takeError(), "YamlParse");
83
84 // If both readers fail, build a new error that includes all information.
85 EC.addError(createStringError(errc::not_supported,
86 "No file readers succeeded reading `%s` "
87 "(unsupported/malformed file?)",
88 FilePath.data()),
89 "ReadInputFile");
90 EC.escalateToFatal();
91 return EC.makeError();
92 }
93
94 int main(int argc, char *argv[]) {
95 // Parse arguments.
96 cl::ParseCommandLineOptions(argc, argv);
97
98 Expected> StubOrErr = readInputFile(InputFilePath);
99 if (!StubOrErr) {
100 Error ReadError = StubOrErr.takeError();
101 WithColor::error() << ReadError << "\n";
102 exit(1);
103 }
104
105 std::unique_ptr TargetStub = std::move(StubOrErr.get());
106
107 // Write out .tbe file.
108 if (EmitTBE.getNumOccurrences() == 1) {
109 TargetStub->TbeVersion = TBEVersionCurrent;
110 if (SOName.getNumOccurrences() == 1) {
111 TargetStub->SoName = SOName;
112 }
113 Error TBEWriteError = writeTBE(EmitTBE, *TargetStub);
114 if (TBEWriteError) {
115 WithColor::error() << TBEWriteError << "\n";
116 exit(1);
117 }
118 }
119 }