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 "
40*f3bfe1b4SPaul Robinson                "definition. The syntax is <macro>=<definition>"),
41*f3bfe1b4SPaul Robinson       cl::cat(Cat));
42e3951248SFangrui Song 
43a29a9a34SFangrui Song cl::opt<unsigned>
44f97af8a0SSimon Atanasyan     DocNum("docnum", cl::init(1),
45a29a9a34SFangrui Song            cl::desc("Read specified document from input (default = 1)"),
46a29a9a34SFangrui Song            cl::cat(Cat));
47f97af8a0SSimon Atanasyan 
483c123acfSGeorgii Rymar static cl::opt<uint64_t> MaxSize(
493c123acfSGeorgii Rymar     "max-size", cl::init(10 * 1024 * 1024),
503c123acfSGeorgii Rymar     cl::desc(
51*f3bfe1b4SPaul Robinson         "Sets the maximum allowed output size (0 means no limit) [ELF only]"),
52*f3bfe1b4SPaul Robinson     cl::cat(Cat));
533c123acfSGeorgii Rymar 
54a29a9a34SFangrui Song cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
55a29a9a34SFangrui Song                                     cl::value_desc("filename"), cl::init("-"),
56a29a9a34SFangrui Song                                     cl::Prefix, cl::cat(Cat));
57a29a9a34SFangrui Song } // namespace
58741cebbeSSean Silva 
preprocess(StringRef Buf,yaml::ErrorHandler ErrHandler)59e3951248SFangrui Song static Optional<std::string> preprocess(StringRef Buf,
60e3951248SFangrui Song                                         yaml::ErrorHandler ErrHandler) {
61e3951248SFangrui Song   DenseMap<StringRef, StringRef> Defines;
62e3951248SFangrui Song   for (StringRef Define : D) {
63e3951248SFangrui Song     StringRef Macro, Definition;
64e3951248SFangrui Song     std::tie(Macro, Definition) = Define.split('=');
65e3951248SFangrui Song     if (!Define.count('=') || Macro.empty()) {
66e3951248SFangrui Song       ErrHandler("invalid syntax for -D: " + Define);
67e3951248SFangrui Song       return {};
68e3951248SFangrui Song     }
69e3951248SFangrui Song     if (!Defines.try_emplace(Macro, Definition).second) {
70e3951248SFangrui Song       ErrHandler("'" + Macro + "'" + " redefined");
71e3951248SFangrui Song       return {};
72e3951248SFangrui Song     }
73e3951248SFangrui Song   }
74e3951248SFangrui Song 
75e3951248SFangrui Song   std::string Preprocessed;
76e3951248SFangrui Song   while (!Buf.empty()) {
77e3951248SFangrui Song     if (Buf.startswith("[[")) {
78e3951248SFangrui Song       size_t I = Buf.find_first_of("[]", 2);
79e3951248SFangrui Song       if (Buf.substr(I).startswith("]]")) {
80657c4ab3SGeorgii Rymar         StringRef MacroExpr = Buf.substr(2, I - 2);
81657c4ab3SGeorgii Rymar         StringRef Macro;
82657c4ab3SGeorgii Rymar         StringRef Default;
83657c4ab3SGeorgii Rymar         std::tie(Macro, Default) = MacroExpr.split('=');
84657c4ab3SGeorgii Rymar 
85657c4ab3SGeorgii Rymar         // When the -D option is requested, we use the provided value.
86657c4ab3SGeorgii Rymar         // Otherwise we use a default macro value if present.
87e3951248SFangrui Song         auto It = Defines.find(Macro);
88657c4ab3SGeorgii Rymar         Optional<StringRef> Value;
89657c4ab3SGeorgii Rymar         if (It != Defines.end())
90657c4ab3SGeorgii Rymar           Value = It->second;
91657c4ab3SGeorgii Rymar         else if (!Default.empty() || MacroExpr.endswith("="))
92657c4ab3SGeorgii Rymar           Value = Default;
93657c4ab3SGeorgii Rymar 
94657c4ab3SGeorgii Rymar         if (Value) {
95657c4ab3SGeorgii Rymar           Preprocessed += *Value;
96e3951248SFangrui Song           Buf = Buf.substr(I + 2);
97e3951248SFangrui Song           continue;
98e3951248SFangrui Song         }
99e3951248SFangrui Song       }
100e3951248SFangrui Song     }
101e3951248SFangrui Song 
102e3951248SFangrui Song     Preprocessed += Buf[0];
103e3951248SFangrui Song     Buf = Buf.substr(1);
104e3951248SFangrui Song   }
105e3951248SFangrui Song 
106e3951248SFangrui Song   return Preprocessed;
107e3951248SFangrui Song }
108e3951248SFangrui Song 
main(int argc,char ** argv)109741cebbeSSean Silva int main(int argc, char **argv) {
110197194b6SRui Ueyama   InitLLVM X(argc, argv);
111a29a9a34SFangrui Song   cl::HideUnrelatedOptions(Cat);
112a29a9a34SFangrui Song   cl::ParseCommandLineOptions(
113a29a9a34SFangrui Song       argc, argv, "Create an object file from a YAML description", nullptr,
114a29a9a34SFangrui Song       nullptr, /*LongOptionsUseDoubleDash=*/true);
11573e047e5SSimon Atanasyan 
11685011027SGeorge Rimar   auto ErrHandler = [](const Twine &Msg) {
11785011027SGeorge Rimar     WithColor::error(errs(), "yaml2obj") << Msg << "\n";
11885011027SGeorge Rimar   };
11985011027SGeorge Rimar 
1203fd1e993SRafael Espindola   std::error_code EC;
1213fc649cbSReid Kleckner   std::unique_ptr<ToolOutputFile> Out(
122d9b948b6SFangrui Song       new ToolOutputFile(OutputFilename, EC, sys::fs::OF_None));
12385011027SGeorge Rimar   if (EC) {
12485011027SGeorge Rimar     ErrHandler("failed to open '" + OutputFilename + "': " + EC.message());
12585011027SGeorge Rimar     return 1;
12685011027SGeorge Rimar   }
12773e047e5SSimon Atanasyan 
128adf21f2aSRafael Espindola   ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
129adf21f2aSRafael Espindola       MemoryBuffer::getFileOrSTDIN(Input);
130adf21f2aSRafael Espindola   if (!Buf)
131741cebbeSSean Silva     return 1;
13273e047e5SSimon Atanasyan 
133e3951248SFangrui Song   Optional<std::string> Buffer = preprocess(Buf.get()->getBuffer(), ErrHandler);
134e3951248SFangrui Song   if (!Buffer)
135e3951248SFangrui Song     return 1;
136e3951248SFangrui Song   yaml::Input YIn(*Buffer);
1373c123acfSGeorgii Rymar 
1383c123acfSGeorgii Rymar   if (!convertYAML(YIn, Out->os(), ErrHandler, DocNum,
1393c123acfSGeorgii Rymar                    MaxSize == 0 ? UINT64_MAX : MaxSize))
140c22d9666SAlex Brachet     return 1;
141fc21bb66SDmitri Gribenko 
142c22d9666SAlex Brachet   Out->keep();
143948a5966SZachary Turner   Out->os().flush();
144c22d9666SAlex Brachet   return 0;
1453add3e9cSRafael Espindola }
146