yaml2obj.cpp 2.5 KB

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