MinidumpEmitter.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. //===- yaml2minidump.cpp - Convert a YAML file to a minidump file ---------===//
  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/MinidumpYAML.h"
  9. #include "llvm/ObjectYAML/yaml2obj.h"
  10. #include "llvm/Support/ConvertUTF.h"
  11. #include "llvm/Support/raw_ostream.h"
  12. using namespace llvm;
  13. using namespace llvm::minidump;
  14. using namespace llvm::MinidumpYAML;
  15. namespace {
  16. /// A helper class to manage the placement of various structures into the final
  17. /// minidump binary. Space for objects can be allocated via various allocate***
  18. /// methods, while the final minidump file is written by calling the writeTo
  19. /// method. The plain versions of allocation functions take a reference to the
  20. /// data which is to be written (and hence the data must be available until
  21. /// writeTo is called), while the "New" versions allocate the data in an
  22. /// allocator-managed buffer, which is available until the allocator object is
  23. /// destroyed. For both kinds of functions, it is possible to modify the
  24. /// data for which the space has been "allocated" until the final writeTo call.
  25. /// This is useful for "linking" the allocated structures via their offsets.
  26. class BlobAllocator {
  27. public:
  28. size_t tell() const { return NextOffset; }
  29. size_t allocateCallback(size_t Size,
  30. std::function<void(raw_ostream &)> Callback) {
  31. size_t Offset = NextOffset;
  32. NextOffset += Size;
  33. Callbacks.push_back(std::move(Callback));
  34. return Offset;
  35. }
  36. size_t allocateBytes(ArrayRef<uint8_t> Data) {
  37. return allocateCallback(
  38. Data.size(), [Data](raw_ostream &OS) { OS << toStringRef(Data); });
  39. }
  40. size_t allocateBytes(yaml::BinaryRef Data) {
  41. return allocateCallback(Data.binary_size(), [Data](raw_ostream &OS) {
  42. Data.writeAsBinary(OS);
  43. });
  44. }
  45. template <typename T> size_t allocateArray(ArrayRef<T> Data) {
  46. return allocateBytes({reinterpret_cast<const uint8_t *>(Data.data()),
  47. sizeof(T) * Data.size()});
  48. }
  49. template <typename T, typename RangeType>
  50. std::pair<size_t, MutableArrayRef<T>>
  51. allocateNewArray(const iterator_range<RangeType> &Range);
  52. template <typename T> size_t allocateObject(const T &Data) {
  53. return allocateArray(makeArrayRef(Data));
  54. }
  55. template <typename T, typename... Types>
  56. std::pair<size_t, T *> allocateNewObject(Types &&... Args) {
  57. T *Object = new (Temporaries.Allocate<T>()) T(std::forward<Types>(Args)...);
  58. return {allocateObject(*Object), Object};
  59. }
  60. size_t allocateString(StringRef Str);
  61. void writeTo(raw_ostream &OS) const;
  62. private:
  63. size_t NextOffset = 0;
  64. BumpPtrAllocator Temporaries;
  65. std::vector<std::function<void(raw_ostream &)>> Callbacks;
  66. };
  67. } // namespace
  68. template <typename T, typename RangeType>
  69. std::pair<size_t, MutableArrayRef<T>>
  70. BlobAllocator::allocateNewArray(const iterator_range<RangeType> &Range) {
  71. size_t Num = std::distance(Range.begin(), Range.end());
  72. MutableArrayRef<T> Array(Temporaries.Allocate<T>(Num), Num);
  73. std::uninitialized_copy(Range.begin(), Range.end(), Array.begin());
  74. return {allocateArray(Array), Array};
  75. }
  76. size_t BlobAllocator::allocateString(StringRef Str) {
  77. SmallVector<UTF16, 32> WStr;
  78. bool OK = convertUTF8ToUTF16String(Str, WStr);
  79. assert(OK && "Invalid UTF8 in Str?");
  80. (void)OK;
  81. // The utf16 string is null-terminated, but the terminator is not counted in
  82. // the string size.
  83. WStr.push_back(0);
  84. size_t Result =
  85. allocateNewObject<support::ulittle32_t>(2 * (WStr.size() - 1)).first;
  86. allocateNewArray<support::ulittle16_t>(make_range(WStr.begin(), WStr.end()));
  87. return Result;
  88. }
  89. void BlobAllocator::writeTo(raw_ostream &OS) const {
  90. size_t BeginOffset = OS.tell();
  91. for (const auto &Callback : Callbacks)
  92. Callback(OS);
  93. assert(OS.tell() == BeginOffset + NextOffset &&
  94. "Callbacks wrote an unexpected number of bytes.");
  95. (void)BeginOffset;
  96. }
  97. static LocationDescriptor layout(BlobAllocator &File, yaml::BinaryRef Data) {
  98. return {support::ulittle32_t(Data.binary_size()),
  99. support::ulittle32_t(File.allocateBytes(Data))};
  100. }
  101. static size_t layout(BlobAllocator &File, MinidumpYAML::ExceptionStream &S) {
  102. File.allocateObject(S.MDExceptionStream);
  103. size_t DataEnd = File.tell();
  104. // Lay out the thread context data, (which is not a part of the stream).
  105. // TODO: This usually (always?) matches the thread context of the
  106. // corresponding thread, and may overlap memory regions as well. We could
  107. // add a level of indirection to the MinidumpYAML format (like an array of
  108. // Blobs that the LocationDescriptors index into) to be able to distinguish
  109. // the cases where location descriptions overlap vs happen to reference
  110. // identical data.
  111. S.MDExceptionStream.ThreadContext = layout(File, S.ThreadContext);
  112. return DataEnd;
  113. }
  114. static void layout(BlobAllocator &File, MemoryListStream::entry_type &Range) {
  115. Range.Entry.Memory = layout(File, Range.Content);
  116. }
  117. static void layout(BlobAllocator &File, ModuleListStream::entry_type &M) {
  118. M.Entry.ModuleNameRVA = File.allocateString(M.Name);
  119. M.Entry.CvRecord = layout(File, M.CvRecord);
  120. M.Entry.MiscRecord = layout(File, M.MiscRecord);
  121. }
  122. static void layout(BlobAllocator &File, ThreadListStream::entry_type &T) {
  123. T.Entry.Stack.Memory = layout(File, T.Stack);
  124. T.Entry.Context = layout(File, T.Context);
  125. }
  126. template <typename EntryT>
  127. static size_t layout(BlobAllocator &File,
  128. MinidumpYAML::detail::ListStream<EntryT> &S) {
  129. File.allocateNewObject<support::ulittle32_t>(S.Entries.size());
  130. for (auto &E : S.Entries)
  131. File.allocateObject(E.Entry);
  132. size_t DataEnd = File.tell();
  133. // Lay out the auxiliary data, (which is not a part of the stream).
  134. DataEnd = File.tell();
  135. for (auto &E : S.Entries)
  136. layout(File, E);
  137. return DataEnd;
  138. }
  139. static Directory layout(BlobAllocator &File, Stream &S) {
  140. Directory Result;
  141. Result.Type = S.Type;
  142. Result.Location.RVA = File.tell();
  143. Optional<size_t> DataEnd;
  144. switch (S.Kind) {
  145. case Stream::StreamKind::Exception:
  146. DataEnd = layout(File, cast<MinidumpYAML::ExceptionStream>(S));
  147. break;
  148. case Stream::StreamKind::MemoryInfoList: {
  149. MemoryInfoListStream &InfoList = cast<MemoryInfoListStream>(S);
  150. File.allocateNewObject<minidump::MemoryInfoListHeader>(
  151. sizeof(minidump::MemoryInfoListHeader), sizeof(minidump::MemoryInfo),
  152. InfoList.Infos.size());
  153. File.allocateArray(makeArrayRef(InfoList.Infos));
  154. break;
  155. }
  156. case Stream::StreamKind::MemoryList:
  157. DataEnd = layout(File, cast<MemoryListStream>(S));
  158. break;
  159. case Stream::StreamKind::ModuleList:
  160. DataEnd = layout(File, cast<ModuleListStream>(S));
  161. break;
  162. case Stream::StreamKind::RawContent: {
  163. RawContentStream &Raw = cast<RawContentStream>(S);
  164. File.allocateCallback(Raw.Size, [&Raw](raw_ostream &OS) {
  165. Raw.Content.writeAsBinary(OS);
  166. assert(Raw.Content.binary_size() <= Raw.Size);
  167. OS << std::string(Raw.Size - Raw.Content.binary_size(), '\0');
  168. });
  169. break;
  170. }
  171. case Stream::StreamKind::SystemInfo: {
  172. SystemInfoStream &SystemInfo = cast<SystemInfoStream>(S);
  173. File.allocateObject(SystemInfo.Info);
  174. // The CSD string is not a part of the stream.
  175. DataEnd = File.tell();
  176. SystemInfo.Info.CSDVersionRVA = File.allocateString(SystemInfo.CSDVersion);
  177. break;
  178. }
  179. case Stream::StreamKind::TextContent:
  180. File.allocateArray(arrayRefFromStringRef(cast<TextContentStream>(S).Text));
  181. break;
  182. case Stream::StreamKind::ThreadList:
  183. DataEnd = layout(File, cast<ThreadListStream>(S));
  184. break;
  185. }
  186. // If DataEnd is not set, we assume everything we generated is a part of the
  187. // stream.
  188. Result.Location.DataSize =
  189. DataEnd.getValueOr(File.tell()) - Result.Location.RVA;
  190. return Result;
  191. }
  192. namespace llvm {
  193. namespace yaml {
  194. bool yaml2minidump(MinidumpYAML::Object &Obj, raw_ostream &Out,
  195. ErrorHandler /*EH*/) {
  196. BlobAllocator File;
  197. File.allocateObject(Obj.Header);
  198. std::vector<Directory> StreamDirectory(Obj.Streams.size());
  199. Obj.Header.StreamDirectoryRVA =
  200. File.allocateArray(makeArrayRef(StreamDirectory));
  201. Obj.Header.NumberOfStreams = StreamDirectory.size();
  202. for (auto &Stream : enumerate(Obj.Streams))
  203. StreamDirectory[Stream.index()] = layout(File, *Stream.value());
  204. File.writeTo(Out);
  205. return true;
  206. }
  207. } // namespace yaml
  208. } // namespace llvm