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.
11 //
12 // This is used for writing tests that require binary files.
13 //
14 //===----------------------------------------------------------------------===//
15 
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>
28 
29 using namespace llvm;
30 
31 static cl::opt<std::string>
32   Input(cl::Positional, cl::desc("<input>"), cl::init("-"));
33 
34 cl::opt<unsigned>
35 DocNum("docnum", cl::init(1),
36        cl::desc("Read specified document from input (default = 1)"));
37 
38 static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
39                                            cl::value_desc("filename"));
40 
41 LLVM_ATTRIBUTE_NORETURN static void error(Twine Message) {
42   errs() << Message << "\n";
43   exit(1);
44 }
45 
46 int main(int argc, char **argv) {
47   InitLLVM X(argc, argv);
48   cl::ParseCommandLineOptions(argc, argv);
49 
50   if (OutputFilename.empty())
51     OutputFilename = "-";
52 
53   std::error_code EC;
54   std::unique_ptr<ToolOutputFile> Out(
55       new ToolOutputFile(OutputFilename, EC, sys::fs::OF_None));
56   if (EC)
57     error("yaml2obj: Error opening '" + OutputFilename + "': " + EC.message());
58 
59   ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
60       MemoryBuffer::getFileOrSTDIN(Input);
61   if (!Buf)
62     return 1;
63 
64   yaml::Input YIn(Buf.get()->getBuffer());
65   if (Error E = convertYAML(YIn, Out->os(), DocNum)) {
66     logAllUnhandledErrors(std::move(E), WithColor::error(errs(), argv[0]));
67     return 1;
68   }
69 
70   Out->keep();
71   Out->os().flush();
72   return 0;
73 }
74