1 //===-- yaml2obj.cpp ------------------------------------------------------===// 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 #include "llvm/ObjectYAML/yaml2obj.h" 10 #include "llvm/ADT/StringExtras.h" 11 #include "llvm/ADT/Twine.h" 12 #include "llvm/Object/ObjectFile.h" 13 #include "llvm/ObjectYAML/ObjectYAML.h" 14 #include "llvm/Support/Errc.h" 15 #include "llvm/Support/WithColor.h" 16 #include "llvm/Support/YAMLTraits.h" 17 18 namespace llvm { 19 namespace yaml { 20 21 bool convertYAML(yaml::Input &YIn, raw_ostream &Out, ErrorHandler ErrHandler, 22 unsigned DocNum, uint64_t MaxSize) { 23 unsigned CurDocNum = 0; 24 do { 25 if (++CurDocNum != DocNum) 26 continue; 27 28 yaml::YamlObjectFile Doc; 29 YIn >> Doc; 30 if (std::error_code EC = YIn.error()) { 31 ErrHandler("failed to parse YAML input: " + EC.message()); 32 return false; 33 } 34 35 if (Doc.Arch) 36 return yaml2archive(*Doc.Arch, Out, ErrHandler); 37 if (Doc.Elf) 38 return yaml2elf(*Doc.Elf, Out, ErrHandler, MaxSize); 39 if (Doc.Coff) 40 return yaml2coff(*Doc.Coff, Out, ErrHandler); 41 if (Doc.MachO || Doc.FatMachO) 42 return yaml2macho(Doc, Out, ErrHandler); 43 if (Doc.Minidump) 44 return yaml2minidump(*Doc.Minidump, Out, ErrHandler); 45 if (Doc.Wasm) 46 return yaml2wasm(*Doc.Wasm, Out, ErrHandler); 47 if (Doc.Xcoff) 48 return yaml2xcoff(*Doc.Xcoff, Out, ErrHandler); 49 if (Doc.DXContainer) 50 return yaml2dxcontainer(*Doc.DXContainer, Out, ErrHandler); 51 52 ErrHandler("unknown document type"); 53 return false; 54 55 } while (YIn.nextDocument()); 56 57 ErrHandler("cannot find the " + Twine(DocNum) + 58 getOrdinalSuffix(DocNum).data() + " document"); 59 return false; 60 } 61 62 std::unique_ptr<object::ObjectFile> 63 yaml2ObjectFile(SmallVectorImpl<char> &Storage, StringRef Yaml, 64 ErrorHandler ErrHandler) { 65 Storage.clear(); 66 raw_svector_ostream OS(Storage); 67 68 yaml::Input YIn(Yaml); 69 if (!convertYAML(YIn, OS, ErrHandler)) 70 return {}; 71 72 Expected<std::unique_ptr<object::ObjectFile>> ObjOrErr = 73 object::ObjectFile::createObjectFile( 74 MemoryBufferRef(OS.str(), "YamlObject")); 75 if (ObjOrErr) 76 return std::move(*ObjOrErr); 77 78 ErrHandler(toString(ObjOrErr.takeError())); 79 return {}; 80 } 81 82 } // namespace yaml 83 } // namespace llvm 84