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 "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/YAMLTraits.h" 25 #include "llvm/Support/raw_ostream.h" 26 #include <system_error> 27 28 using namespace llvm; 29 30 static cl::opt<std::string> 31 Input(cl::Positional, cl::desc("<input>"), cl::init("-")); 32 33 cl::opt<unsigned> 34 DocNum("docnum", cl::init(1), 35 cl::desc("Read specified document from input (default = 1)")); 36 37 static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"), 38 cl::value_desc("filename")); 39 40 LLVM_ATTRIBUTE_NORETURN static void error(Twine Message) { 41 errs() << Message << "\n"; 42 exit(1); 43 } 44 45 static int convertYAML(yaml::Input &YIn, raw_ostream &Out) { 46 unsigned CurDocNum = 0; 47 do { 48 if (++CurDocNum == DocNum) { 49 yaml::YamlObjectFile Doc; 50 YIn >> Doc; 51 if (YIn.error()) 52 error("yaml2obj: Failed to parse YAML file!"); 53 if (Doc.Elf) 54 return yaml2elf(*Doc.Elf, Out); 55 if (Doc.Coff) 56 return yaml2coff(*Doc.Coff, Out); 57 if (Doc.MachO || Doc.FatMachO) 58 return yaml2macho(Doc, Out); 59 if (Doc.Wasm) 60 return yaml2wasm(*Doc.Wasm, Out); 61 error("yaml2obj: Unknown document type!"); 62 } 63 } while (YIn.nextDocument()); 64 65 error("yaml2obj: Cannot find the " + Twine(DocNum) + 66 llvm::getOrdinalSuffix(DocNum) + " document"); 67 } 68 69 int main(int argc, char **argv) { 70 InitLLVM X(argc, argv); 71 cl::ParseCommandLineOptions(argc, argv); 72 73 if (OutputFilename.empty()) 74 OutputFilename = "-"; 75 76 std::error_code EC; 77 std::unique_ptr<ToolOutputFile> Out( 78 new ToolOutputFile(OutputFilename, EC, sys::fs::F_None)); 79 if (EC) 80 error("yaml2obj: Error opening '" + OutputFilename + "': " + EC.message()); 81 82 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = 83 MemoryBuffer::getFileOrSTDIN(Input); 84 if (!Buf) 85 return 1; 86 87 yaml::Input YIn(Buf.get()->getBuffer()); 88 89 int Res = convertYAML(YIn, Out->os()); 90 if (Res == 0) 91 Out->keep(); 92 93 Out->os().flush(); 94 return Res; 95 } 96