yaml2obj.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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.Wasm)
  41. return yaml2wasm(*Doc.Wasm, Out, ErrHandler);
  42. ErrHandler("unknown document type");
  43. return false;
  44. } while (YIn.nextDocument());
  45. ErrHandler("cannot find the " + Twine(DocNum) +
  46. getOrdinalSuffix(DocNum).data() + " document");
  47. return false;
  48. }
  49. std::unique_ptr<object::ObjectFile>
  50. yaml2ObjectFile(SmallVectorImpl<char> &Storage, StringRef Yaml,
  51. ErrorHandler ErrHandler) {
  52. Storage.clear();
  53. raw_svector_ostream OS(Storage);
  54. yaml::Input YIn(Yaml);
  55. if (!convertYAML(YIn, OS, ErrHandler))
  56. return {};
  57. Expected<std::unique_ptr<object::ObjectFile>> ObjOrErr =
  58. object::ObjectFile::createObjectFile(
  59. MemoryBufferRef(OS.str(), "YamlObject"));
  60. if (ObjOrErr)
  61. return std::move(*ObjOrErr);
  62. ErrHandler(toString(ObjOrErr.takeError()));
  63. return {};
  64. }
  65. } // namespace yaml
  66. } // namespace llvm