1 //===------ utils/obj2yaml.cpp - obj2yaml conversion tool -------*- C++ -*-===//
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 //===----------------------------------------------------------------------===//
10 #include "llvm/BinaryFormat/Magic.h"
11 #include "llvm/Object/Archive.h"
12 #include "llvm/Object/COFF.h"
13 #include "llvm/Object/Minidump.h"
14 #include "llvm/Support/CommandLine.h"
15 #include "llvm/Support/Errc.h"
16 #include "llvm/Support/InitLLVM.h"
19 using namespace llvm::object
;
21 static Error
dumpObject(const ObjectFile
&Obj
) {
23 return errorCodeToError(coff2yaml(outs(), cast
<COFFObjectFile
>(Obj
)));
26 return errorCodeToError(xcoff2yaml(outs(), cast
<XCOFFObjectFile
>(Obj
)));
29 return elf2yaml(outs(), Obj
);
32 return errorCodeToError(wasm2yaml(outs(), cast
<WasmObjectFile
>(Obj
)));
34 llvm_unreachable("unexpected object file format");
37 static Error
dumpInput(StringRef File
) {
38 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> FileOrErr
=
39 MemoryBuffer::getFileOrSTDIN(File
, /*FileSize=*/-1,
40 /*RequiresNullTerminator=*/false);
41 if (std::error_code EC
= FileOrErr
.getError())
42 return errorCodeToError(EC
);
43 std::unique_ptr
<MemoryBuffer
> &Buffer
= FileOrErr
.get();
44 MemoryBufferRef MemBuf
= Buffer
->getMemBufferRef();
45 if (file_magic::archive
== identify_magic(MemBuf
.getBuffer()))
46 return archive2yaml(outs(), MemBuf
);
48 Expected
<std::unique_ptr
<Binary
>> BinOrErr
=
49 createBinary(MemBuf
, /*Context=*/nullptr);
51 return BinOrErr
.takeError();
53 Binary
&Binary
= *BinOrErr
->get();
54 // Universal MachO is not a subclass of ObjectFile, so it needs to be handled
55 // here with the other binary types.
56 if (Binary
.isMachO() || Binary
.isMachOUniversalBinary())
57 return macho2yaml(outs(), Binary
);
58 if (ObjectFile
*Obj
= dyn_cast
<ObjectFile
>(&Binary
))
59 return dumpObject(*Obj
);
60 if (MinidumpFile
*Minidump
= dyn_cast
<MinidumpFile
>(&Binary
))
61 return minidump2yaml(outs(), *Minidump
);
63 return Error::success();
66 static void reportError(StringRef Input
, Error Err
) {
70 raw_string_ostream
OS(ErrMsg
);
71 logAllUnhandledErrors(std::move(Err
), OS
);
73 errs() << "Error reading file: " << Input
<< ": " << ErrMsg
;
77 cl::opt
<std::string
> InputFilename(cl::Positional
, cl::desc("<input file>"),
80 int main(int argc
, char *argv
[]) {
81 InitLLVM
X(argc
, argv
);
82 cl::ParseCommandLineOptions(argc
, argv
);
84 if (Error Err
= dumpInput(InputFilename
)) {
85 reportError(InputFilename
, std::move(Err
));