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