OSDN Git Service

[llvm-readobj] Allow --hex-dump/--string-dump to dump multiple sections
[android-x86/external-llvm.git] / tools / obj2yaml / obj2yaml.cpp
1 //===------ utils/obj2yaml.cpp - obj2yaml conversion tool -------*- C++ -*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "obj2yaml.h"
10 #include "Error.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/InitLLVM.h"
16
17 using namespace llvm;
18 using namespace llvm::object;
19
20 static std::error_code dumpObject(const ObjectFile &Obj) {
21   if (Obj.isCOFF())
22     return coff2yaml(outs(), cast<COFFObjectFile>(Obj));
23
24   if (Obj.isXCOFF())
25     return xcoff2yaml(outs(), cast<XCOFFObjectFile>(Obj));
26
27   if (Obj.isELF())
28     return elf2yaml(outs(), Obj);
29   if (Obj.isWasm())
30     return wasm2yaml(outs(), cast<WasmObjectFile>(Obj));
31
32   return obj2yaml_error::unsupported_obj_file_format;
33 }
34
35 static Error dumpInput(StringRef File) {
36   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(File);
37   if (!BinaryOrErr)
38     return BinaryOrErr.takeError();
39
40   Binary &Binary = *BinaryOrErr.get().getBinary();
41   // Universal MachO is not a subclass of ObjectFile, so it needs to be handled
42   // here with the other binary types.
43   if (Binary.isMachO() || Binary.isMachOUniversalBinary())
44     return errorCodeToError(macho2yaml(outs(), Binary));
45   // TODO: If this is an archive, then burst it and dump each entry
46   if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary))
47     return errorCodeToError(dumpObject(*Obj));
48   if (MinidumpFile *Minidump = dyn_cast<MinidumpFile>(&Binary))
49     return minidump2yaml(outs(), *Minidump);
50
51   return Error::success();
52 }
53
54 static void reportError(StringRef Input, Error Err) {
55   if (Input == "-")
56     Input = "<stdin>";
57   std::string ErrMsg;
58   raw_string_ostream OS(ErrMsg);
59   logAllUnhandledErrors(std::move(Err), OS);
60   OS.flush();
61   errs() << "Error reading file: " << Input << ": " << ErrMsg;
62   errs().flush();
63 }
64
65 cl::opt<std::string> InputFilename(cl::Positional, cl::desc("<input file>"),
66                                    cl::init("-"));
67
68 int main(int argc, char *argv[]) {
69   InitLLVM X(argc, argv);
70   cl::ParseCommandLineOptions(argc, argv);
71
72   if (Error Err = dumpInput(InputFilename)) {
73     reportError(InputFilename, std::move(Err));
74     return 1;
75   }
76
77   return 0;
78 }