[llvm-readobj] - Refine the LLVM-style output to be consistent.
[llvm-complete.git] / tools / yaml2obj / yaml2obj.cpp
blob66e0da69881dfae967d0c2c3e78aa657d289a5c5
1 //===- yaml2obj - Convert YAML to a binary object file --------------------===//
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 // This program takes a YAML description of an object file and outputs the
10 // binary equivalent.
12 // This is used for writing tests that require binary files.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/ObjectYAML/yaml2obj.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ObjectYAML/ObjectYAML.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/InitLLVM.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/ToolOutputFile.h"
24 #include "llvm/Support/WithColor.h"
25 #include "llvm/Support/YAMLTraits.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <system_error>
29 using namespace llvm;
31 static cl::opt<std::string>
32 Input(cl::Positional, cl::desc("<input>"), cl::init("-"));
34 cl::opt<unsigned>
35 DocNum("docnum", cl::init(1),
36 cl::desc("Read specified document from input (default = 1)"));
38 static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
39 cl::value_desc("filename"));
41 int main(int argc, char **argv) {
42 InitLLVM X(argc, argv);
43 cl::ParseCommandLineOptions(argc, argv);
45 if (OutputFilename.empty())
46 OutputFilename = "-";
48 auto ErrHandler = [](const Twine &Msg) {
49 WithColor::error(errs(), "yaml2obj") << Msg << "\n";
52 std::error_code EC;
53 std::unique_ptr<ToolOutputFile> Out(
54 new ToolOutputFile(OutputFilename, EC, sys::fs::OF_None));
55 if (EC) {
56 ErrHandler("failed to open '" + OutputFilename + "': " + EC.message());
57 return 1;
60 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
61 MemoryBuffer::getFileOrSTDIN(Input);
62 if (!Buf)
63 return 1;
65 yaml::Input YIn(Buf.get()->getBuffer());
66 if (!convertYAML(YIn, Out->os(), ErrHandler, DocNum))
67 return 1;
69 Out->keep();
70 Out->os().flush();
71 return 0;