13add3e9cSRafael Espindola //===- yaml2obj - Convert YAML to a binary object file --------------------===//
23add3e9cSRafael Espindola //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
63add3e9cSRafael Espindola //
73add3e9cSRafael Espindola //===----------------------------------------------------------------------===//
83add3e9cSRafael Espindola //
93add3e9cSRafael Espindola // This program takes a YAML description of an object file and outputs the
103add3e9cSRafael Espindola // binary equivalent.
113add3e9cSRafael Espindola //
123add3e9cSRafael Espindola // This is used for writing tests that require binary files.
133add3e9cSRafael Espindola //
143add3e9cSRafael Espindola //===----------------------------------------------------------------------===//
153add3e9cSRafael Espindola 
16c22d9666SAlex Brachet #include "llvm/ObjectYAML/yaml2obj.h"
17f97af8a0SSimon Atanasyan #include "llvm/ADT/StringExtras.h"
188ff0c113SChris Bieneman #include "llvm/ObjectYAML/ObjectYAML.h"
193add3e9cSRafael Espindola #include "llvm/Support/CommandLine.h"
2073e047e5SSimon Atanasyan #include "llvm/Support/FileSystem.h"
21197194b6SRui Ueyama #include "llvm/Support/InitLLVM.h"
223add3e9cSRafael Espindola #include "llvm/Support/MemoryBuffer.h"
2373e047e5SSimon Atanasyan #include "llvm/Support/ToolOutputFile.h"
24c22d9666SAlex Brachet #include "llvm/Support/WithColor.h"
25f97af8a0SSimon Atanasyan #include "llvm/Support/YAMLTraits.h"
26a6e9c3e4SRafael Espindola #include "llvm/Support/raw_ostream.h"
27a6e9c3e4SRafael Espindola #include <system_error>
283add3e9cSRafael Espindola 
293add3e9cSRafael Espindola using namespace llvm;
303add3e9cSRafael Espindola 
31a29a9a34SFangrui Song namespace {
32a29a9a34SFangrui Song cl::OptionCategory Cat("yaml2obj Options");
333add3e9cSRafael Espindola 
34a29a9a34SFangrui Song cl::opt<std::string> Input(cl::Positional, cl::desc("<input file>"),
35a29a9a34SFangrui Song                            cl::init("-"), cl::cat(Cat));
36a29a9a34SFangrui Song 
37e3951248SFangrui Song cl::list<std::string>
38e3951248SFangrui Song     D("D", cl::Prefix,
39e3951248SFangrui Song       cl::desc("Defined the specified macros to their specified "
40e3951248SFangrui Song                "definition. The syntax is <macro>=<definition>"));
41e3951248SFangrui Song 
42a29a9a34SFangrui Song cl::opt<unsigned>
43f97af8a0SSimon Atanasyan     DocNum("docnum", cl::init(1),
44a29a9a34SFangrui Song            cl::desc("Read specified document from input (default = 1)"),
45a29a9a34SFangrui Song            cl::cat(Cat));
46f97af8a0SSimon Atanasyan 
473c123acfSGeorgii Rymar static cl::opt<uint64_t> MaxSize(
483c123acfSGeorgii Rymar     "max-size", cl::init(10 * 1024 * 1024),
493c123acfSGeorgii Rymar     cl::desc(
503c123acfSGeorgii Rymar         "Sets the maximum allowed output size (0 means no limit) [ELF only]"));
513c123acfSGeorgii Rymar 
52a29a9a34SFangrui Song cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
53a29a9a34SFangrui Song                                     cl::value_desc("filename"), cl::init("-"),
54a29a9a34SFangrui Song                                     cl::Prefix, cl::cat(Cat));
55a29a9a34SFangrui Song } // namespace
56741cebbeSSean Silva 
57e3951248SFangrui Song static Optional<std::string> preprocess(StringRef Buf,
58e3951248SFangrui Song                                         yaml::ErrorHandler ErrHandler) {
59e3951248SFangrui Song   DenseMap<StringRef, StringRef> Defines;
60e3951248SFangrui Song   for (StringRef Define : D) {
61e3951248SFangrui Song     StringRef Macro, Definition;
62e3951248SFangrui Song     std::tie(Macro, Definition) = Define.split('=');
63e3951248SFangrui Song     if (!Define.count('=') || Macro.empty()) {
64e3951248SFangrui Song       ErrHandler("invalid syntax for -D: " + Define);
65e3951248SFangrui Song       return {};
66e3951248SFangrui Song     }
67e3951248SFangrui Song     if (!Defines.try_emplace(Macro, Definition).second) {
68e3951248SFangrui Song       ErrHandler("'" + Macro + "'" + " redefined");
69e3951248SFangrui Song       return {};
70e3951248SFangrui Song     }
71e3951248SFangrui Song   }
72e3951248SFangrui Song 
73e3951248SFangrui Song   std::string Preprocessed;
74e3951248SFangrui Song   while (!Buf.empty()) {
75e3951248SFangrui Song     if (Buf.startswith("[[")) {
76e3951248SFangrui Song       size_t I = Buf.find_first_of("[]", 2);
77e3951248SFangrui Song       if (Buf.substr(I).startswith("]]")) {
78*657c4ab3SGeorgii Rymar         StringRef MacroExpr = Buf.substr(2, I - 2);
79*657c4ab3SGeorgii Rymar         StringRef Macro;
80*657c4ab3SGeorgii Rymar         StringRef Default;
81*657c4ab3SGeorgii Rymar         std::tie(Macro, Default) = MacroExpr.split('=');
82*657c4ab3SGeorgii Rymar 
83*657c4ab3SGeorgii Rymar         // When the -D option is requested, we use the provided value.
84*657c4ab3SGeorgii Rymar         // Otherwise we use a default macro value if present.
85e3951248SFangrui Song         auto It = Defines.find(Macro);
86*657c4ab3SGeorgii Rymar         Optional<StringRef> Value;
87*657c4ab3SGeorgii Rymar         if (It != Defines.end())
88*657c4ab3SGeorgii Rymar           Value = It->second;
89*657c4ab3SGeorgii Rymar         else if (!Default.empty() || MacroExpr.endswith("="))
90*657c4ab3SGeorgii Rymar           Value = Default;
91*657c4ab3SGeorgii Rymar 
92*657c4ab3SGeorgii Rymar         if (Value) {
93*657c4ab3SGeorgii Rymar           Preprocessed += *Value;
94e3951248SFangrui Song           Buf = Buf.substr(I + 2);
95e3951248SFangrui Song           continue;
96e3951248SFangrui Song         }
97e3951248SFangrui Song       }
98e3951248SFangrui Song     }
99e3951248SFangrui Song 
100e3951248SFangrui Song     Preprocessed += Buf[0];
101e3951248SFangrui Song     Buf = Buf.substr(1);
102e3951248SFangrui Song   }
103e3951248SFangrui Song 
104e3951248SFangrui Song   return Preprocessed;
105e3951248SFangrui Song }
106e3951248SFangrui Song 
107741cebbeSSean Silva int main(int argc, char **argv) {
108197194b6SRui Ueyama   InitLLVM X(argc, argv);
109a29a9a34SFangrui Song   cl::HideUnrelatedOptions(Cat);
110a29a9a34SFangrui Song   cl::ParseCommandLineOptions(
111a29a9a34SFangrui Song       argc, argv, "Create an object file from a YAML description", nullptr,
112a29a9a34SFangrui Song       nullptr, /*LongOptionsUseDoubleDash=*/true);
11373e047e5SSimon Atanasyan 
11485011027SGeorge Rimar   auto ErrHandler = [](const Twine &Msg) {
11585011027SGeorge Rimar     WithColor::error(errs(), "yaml2obj") << Msg << "\n";
11685011027SGeorge Rimar   };
11785011027SGeorge Rimar 
1183fd1e993SRafael Espindola   std::error_code EC;
1193fc649cbSReid Kleckner   std::unique_ptr<ToolOutputFile> Out(
120d9b948b6SFangrui Song       new ToolOutputFile(OutputFilename, EC, sys::fs::OF_None));
12185011027SGeorge Rimar   if (EC) {
12285011027SGeorge Rimar     ErrHandler("failed to open '" + OutputFilename + "': " + EC.message());
12385011027SGeorge Rimar     return 1;
12485011027SGeorge Rimar   }
12573e047e5SSimon Atanasyan 
126adf21f2aSRafael Espindola   ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
127adf21f2aSRafael Espindola       MemoryBuffer::getFileOrSTDIN(Input);
128adf21f2aSRafael Espindola   if (!Buf)
129741cebbeSSean Silva     return 1;
13073e047e5SSimon Atanasyan 
131e3951248SFangrui Song   Optional<std::string> Buffer = preprocess(Buf.get()->getBuffer(), ErrHandler);
132e3951248SFangrui Song   if (!Buffer)
133e3951248SFangrui Song     return 1;
134e3951248SFangrui Song   yaml::Input YIn(*Buffer);
1353c123acfSGeorgii Rymar 
1363c123acfSGeorgii Rymar   if (!convertYAML(YIn, Out->os(), ErrHandler, DocNum,
1373c123acfSGeorgii Rymar                    MaxSize == 0 ? UINT64_MAX : MaxSize))
138c22d9666SAlex Brachet     return 1;
139fc21bb66SDmitri Gribenko 
140c22d9666SAlex Brachet   Out->keep();
141948a5966SZachary Turner   Out->os().flush();
142c22d9666SAlex Brachet   return 0;
1433add3e9cSRafael Espindola }
144