1 //===- yaml2obj - Convert YAML to a binary object file --------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This program takes a YAML description of an object file and outputs the
12 // This is used for writing tests that require binary files.
14 //===----------------------------------------------------------------------===//
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/YAMLTraits.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include <system_error>
30 static cl::opt
<std::string
>
31 Input(cl::Positional
, cl::desc("<input>"), cl::init("-"));
34 DocNum("docnum", cl::init(1),
35 cl::desc("Read specified document from input (default = 1)"));
37 static cl::opt
<std::string
> OutputFilename("o", cl::desc("Output filename"),
38 cl::value_desc("filename"));
40 LLVM_ATTRIBUTE_NORETURN
static void error(Twine Message
) {
41 errs() << Message
<< "\n";
45 static int convertYAML(yaml::Input
&YIn
, raw_ostream
&Out
) {
46 unsigned CurDocNum
= 0;
48 if (++CurDocNum
== DocNum
) {
49 yaml::YamlObjectFile Doc
;
52 error("yaml2obj: Failed to parse YAML file!");
54 return yaml2elf(*Doc
.Elf
, Out
);
56 return yaml2coff(*Doc
.Coff
, Out
);
57 if (Doc
.MachO
|| Doc
.FatMachO
)
58 return yaml2macho(Doc
, Out
);
60 return yaml2minidump(*Doc
.Minidump
, Out
);
62 return yaml2wasm(*Doc
.Wasm
, Out
);
63 error("yaml2obj: Unknown document type!");
65 } while (YIn
.nextDocument());
67 error("yaml2obj: Cannot find the " + Twine(DocNum
) +
68 llvm::getOrdinalSuffix(DocNum
) + " document");
71 int main(int argc
, char **argv
) {
72 InitLLVM
X(argc
, argv
);
73 cl::ParseCommandLineOptions(argc
, argv
);
75 if (OutputFilename
.empty())
79 std::unique_ptr
<ToolOutputFile
> Out(
80 new ToolOutputFile(OutputFilename
, EC
, sys::fs::F_None
));
82 error("yaml2obj: Error opening '" + OutputFilename
+ "': " + EC
.message());
84 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> Buf
=
85 MemoryBuffer::getFileOrSTDIN(Input
);
89 StringRef Buffer
= Buf
.get()->getBuffer();
90 if (Buffer
.trim().size() == 0)
91 error("yaml2obj: Error opening '" + Input
+ "': Empty File.");
92 yaml::Input
YIn(Buffer
);
94 int Res
= convertYAML(YIn
, Out
->os());