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/Option/ArgList.h"
19#include "llvm/Option/OptTable.h"
20#include "llvm/Option/Option.h"
21#include "llvm/Support/CommandLine.h"
22#include "llvm/Support/FileSystem.h"
23#include "llvm/Support/InitLLVM.h"
24#include "llvm/Support/MemoryBuffer.h"
25#include "llvm/Support/StringSaver.h"
26#include "llvm/Support/ToolOutputFile.h"
27#include "llvm/Support/WithColor.h"
28#include "llvm/Support/YAMLTraits.h"
29#include "llvm/Support/raw_ostream.h"
30#include <optional>
31#include <system_error>
32
33using namespace llvm;
34
35namespace {
36enum ID {
37 OPT_INVALID = 0, // This is not an option ID.
38#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
39#include "Opts.inc"
40#undef OPTION
41};
42
43using namespace llvm::opt;
44#define OPTTABLE_CODE
45#include "Opts.inc"
46
47class Yaml2ObjOptTable : public opt::OptTable {
48public:
49 Yaml2ObjOptTable() : OptTable(optionTables()) { setDashDashParsing(true); }
50};
51} // namespace
52
53static std::optional<std::string> preprocess(StringRef Buf,
54 ArrayRef<std::string> D,
55 yaml::ErrorHandler ErrHandler) {
56 DenseMap<StringRef, StringRef> Defines;
57 for (StringRef Define : D) {
58 StringRef Macro, Definition;
59 std::tie(args&: Macro, args&: Definition) = Define.split(Separator: '=');
60 if (!Define.count(C: '=') || Macro.empty()) {
61 ErrHandler("invalid syntax for -D: " + Define);
62 return {};
63 }
64 if (!Defines.try_emplace(Key: Macro, Args&: Definition).second) {
65 ErrHandler("'" + Macro + "'" + " redefined");
66 return {};
67 }
68 }
69
70 std::string Preprocessed;
71 while (!Buf.empty()) {
72 if (Buf.starts_with(Prefix: "[[")) {
73 size_t I = Buf.find_first_of(Chars: "[]", From: 2);
74 if (Buf.substr(Start: I).starts_with(Prefix: "]]")) {
75 StringRef MacroExpr = Buf.substr(Start: 2, N: I - 2);
76 StringRef Macro;
77 StringRef Default;
78 std::tie(args&: Macro, args&: Default) = MacroExpr.split(Separator: '=');
79
80 // When the -D option is requested, we use the provided value.
81 // Otherwise we use a default macro value if present.
82 auto It = Defines.find(Val: Macro);
83 std::optional<StringRef> Value;
84 if (It != Defines.end())
85 Value = It->second;
86 else if (!Default.empty() || MacroExpr.ends_with(Suffix: "="))
87 Value = Default;
88
89 if (Value) {
90 Preprocessed += *Value;
91 Buf = Buf.substr(Start: I + 2);
92 continue;
93 }
94 }
95 }
96
97 Preprocessed += Buf[0];
98 Buf = Buf.substr(Start: 1);
99 }
100
101 return Preprocessed;
102}
103
104template <class T>
105static void parseIntArg(const opt::InputArgList &Args, int ID, T &Value,
106 yaml::ErrorHandler ErrHandler) {
107 if (const opt::Arg *A = Args.getLastArg(Ids: ID)) {
108 StringRef V(A->getValue());
109 if (!to_integer(V, Value, 0)) {
110 ErrHandler("expected an integer, but got '" + V + "'");
111 exit(status: 1);
112 }
113 }
114}
115
116int main(int argc, char **argv) {
117 InitLLVM X(argc, argv);
118 constexpr StringRef ProgName = "yaml2obj";
119 auto ErrHandler = [&](const Twine &Msg) {
120 WithColor::error(OS&: errs(), Prefix: ProgName) << Msg << "\n";
121 };
122
123 BumpPtrAllocator A;
124 StringSaver Saver(A);
125 Yaml2ObjOptTable Tbl;
126 opt::InputArgList Args =
127 Tbl.parseArgs(Argc: argc, Argv: argv, Unknown: OPT_UNKNOWN, Saver, ErrorFn: [&](StringRef Msg) {
128 ErrHandler(Msg);
129 exit(status: 1);
130 });
131 if (Args.hasArg(Ids: OPT_help)) {
132 Tbl.printHelp(OS&: outs(), Usage: "yaml2obj [options] <input file>",
133 Title: "Create an object file from a YAML description");
134 return 0;
135 }
136 if (Args.hasArg(Ids: OPT_version)) {
137 cl::PrintVersionMessage();
138 return 0;
139 }
140
141 std::vector<std::string> Inputs = Args.getAllArgValues(Id: OPT_INPUT);
142 if (Inputs.size() > 1) {
143 ErrHandler("too many input files");
144 return 1;
145 }
146 StringRef Input = Inputs.empty() ? StringRef("-") : StringRef(Inputs[0]);
147 StringRef OutputFilename = Args.getLastArgValue(Id: OPT_o, Default: "-");
148 unsigned DocNum = 1;
149 parseIntArg(Args, ID: OPT_docnum_EQ, Value&: DocNum, ErrHandler);
150 uint64_t MaxSize = 10 * 1024 * 1024;
151 parseIntArg(Args, ID: OPT_max_size_EQ, Value&: MaxSize, ErrHandler);
152
153 std::error_code EC;
154 std::unique_ptr<ToolOutputFile> Out(
155 new ToolOutputFile(OutputFilename, EC, sys::fs::OF_None));
156 if (EC) {
157 ErrHandler("failed to open '" + OutputFilename + "': " + EC.message());
158 return 1;
159 }
160
161 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
162 MemoryBuffer::getFileOrSTDIN(Filename: Input, /*IsText=*/true);
163 if (std::error_code EC = Buf.getError()) {
164 WithColor::error(OS&: errs(), Prefix: ProgName) << Input << ": " << EC.message() << '\n';
165 return 1;
166 }
167
168 std::optional<std::string> Buffer = preprocess(
169 Buf: Buf.get()->getBuffer(), D: Args.getAllArgValues(Id: OPT_D), ErrHandler);
170 if (!Buffer)
171 return 1;
172
173 if (Args.hasArg(Ids: OPT_E)) {
174 Out->os() << Buffer;
175 } else {
176 yaml::Input YIn(*Buffer);
177
178 if (!convertYAML(YIn, Out&: Out->os(), ErrHandler, DocNum,
179 MaxSize: MaxSize == 0 ? UINT64_MAX : MaxSize))
180 return 1;
181 }
182
183 Out->keep();
184 Out->os().flush();
185 return 0;
186}
187