1 //===- yaml2obj - Convert YAML to a binary object file --------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This program takes a YAML description of an object file and outputs the 11 // binary equivalent. 12 // 13 // This is used for writing tests that require binary files. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "yaml2obj.h" 18 #include "llvm/ADT/StringExtras.h" 19 #include "llvm/ObjectYAML/ObjectYAML.h" 20 #include "llvm/Support/CommandLine.h" 21 #include "llvm/Support/FileSystem.h" 22 #include "llvm/Support/ManagedStatic.h" 23 #include "llvm/Support/MemoryBuffer.h" 24 #include "llvm/Support/PrettyStackTrace.h" 25 #include "llvm/Support/Signals.h" 26 #include "llvm/Support/ToolOutputFile.h" 27 #include "llvm/Support/YAMLTraits.h" 28 #include "llvm/Support/raw_ostream.h" 29 #include <system_error> 30 31 using namespace llvm; 32 33 static cl::opt<std::string> 34 Input(cl::Positional, cl::desc("<input>"), cl::init("-")); 35 36 cl::opt<unsigned> 37 DocNum("docnum", cl::init(1), 38 cl::desc("Read specified document from input (default = 1)")); 39 40 static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"), 41 cl::value_desc("filename")); 42 43 static int convertYAML(yaml::Input &YIn, raw_ostream &Out) { 44 unsigned CurDocNum = 0; 45 do { 46 if (++CurDocNum == DocNum) { 47 yaml::YamlObjectFile Doc; 48 YIn >> Doc; 49 if (YIn.error()) { 50 errs() << "yaml2obj: Failed to parse YAML file!\n"; 51 return 1; 52 } 53 54 if (Doc.Elf) 55 return yaml2elf(*Doc.Elf, Out); 56 if (Doc.Coff) 57 return yaml2coff(*Doc.Coff, Out); 58 if (Doc.MachO || Doc.FatMachO) 59 return yaml2macho(Doc, Out); 60 if (Doc.Wasm) 61 return yaml2wasm(*Doc.Wasm, Out); 62 errs() << "yaml2obj: Unknown document type!\n"; 63 return 1; 64 } 65 } while (YIn.nextDocument()); 66 67 errs() << "yaml2obj: Cannot find the " << DocNum 68 << llvm::getOrdinalSuffix(DocNum) << " document\n"; 69 return 1; 70 } 71 72 int main(int argc, char **argv) { 73 cl::ParseCommandLineOptions(argc, argv); 74 sys::PrintStackTraceOnErrorSignal(argv[0]); 75 PrettyStackTraceProgram X(argc, argv); 76 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 77 78 if (OutputFilename.empty()) 79 OutputFilename = "-"; 80 81 std::error_code EC; 82 std::unique_ptr<tool_output_file> Out( 83 new tool_output_file(OutputFilename, EC, sys::fs::F_None)); 84 if (EC) { 85 errs() << EC.message() << '\n'; 86 return 1; 87 } 88 89 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = 90 MemoryBuffer::getFileOrSTDIN(Input); 91 if (!Buf) 92 return 1; 93 94 yaml::Input YIn(Buf.get()->getBuffer()); 95 96 int Res = convertYAML(YIn, Out->os()); 97 if (Res == 0) 98 Out->keep(); 99 100 return Res; 101 } 102