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 "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" 17 18 using namespace llvm; 19 using namespace llvm::object; 20 21 static Error dumpObject(const ObjectFile &Obj) { 22 if (Obj.isCOFF()) 23 return errorCodeToError(coff2yaml(outs(), cast<COFFObjectFile>(Obj))); 24 25 if (Obj.isXCOFF()) 26 return errorCodeToError(xcoff2yaml(outs(), cast<XCOFFObjectFile>(Obj))); 27 28 if (Obj.isELF()) 29 return elf2yaml(outs(), Obj); 30 31 if (Obj.isWasm()) 32 return errorCodeToError(wasm2yaml(outs(), cast<WasmObjectFile>(Obj))); 33 34 llvm_unreachable("unexpected object file format"); 35 } 36 37 static Error dumpInput(StringRef File) { 38 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = 39 MemoryBuffer::getFileOrSTDIN(File, /*IsText=*/false, 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); 47 48 Expected<std::unique_ptr<Binary>> BinOrErr = 49 createBinary(MemBuf, /*Context=*/nullptr); 50 if (!BinOrErr) 51 return BinOrErr.takeError(); 52 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); 62 63 return Error::success(); 64 } 65 66 static void reportError(StringRef Input, Error Err) { 67 if (Input == "-") 68 Input = "<stdin>"; 69 std::string ErrMsg; 70 raw_string_ostream OS(ErrMsg); 71 logAllUnhandledErrors(std::move(Err), OS); 72 OS.flush(); 73 errs() << "Error reading file: " << Input << ": " << ErrMsg; 74 errs().flush(); 75 } 76 77 cl::opt<std::string> InputFilename(cl::Positional, cl::desc("<input file>"), 78 cl::init("-")); 79 80 int main(int argc, char *argv[]) { 81 InitLLVM X(argc, argv); 82 cl::ParseCommandLineOptions(argc, argv); 83 84 if (Error Err = dumpInput(InputFilename)) { 85 reportError(InputFilename, std::move(Err)); 86 return 1; 87 } 88 89 return 0; 90 } 91