Path: blob/main/contrib/llvm-project/llvm/lib/ObjectYAML/MinidumpEmitter.cpp
35233 views
//===- yaml2minidump.cpp - Convert a YAML file to a minidump file ---------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#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#include <optional>1314using namespace llvm;15using namespace llvm::minidump;16using namespace llvm::MinidumpYAML;1718namespace {19/// A helper class to manage the placement of various structures into the final20/// minidump binary. Space for objects can be allocated via various allocate***21/// methods, while the final minidump file is written by calling the writeTo22/// method. The plain versions of allocation functions take a reference to the23/// data which is to be written (and hence the data must be available until24/// writeTo is called), while the "New" versions allocate the data in an25/// allocator-managed buffer, which is available until the allocator object is26/// destroyed. For both kinds of functions, it is possible to modify the27/// data for which the space has been "allocated" until the final writeTo call.28/// This is useful for "linking" the allocated structures via their offsets.29class BlobAllocator {30public:31size_t tell() const { return NextOffset; }3233size_t allocateCallback(size_t Size,34std::function<void(raw_ostream &)> Callback) {35size_t Offset = NextOffset;36NextOffset += Size;37Callbacks.push_back(std::move(Callback));38return Offset;39}4041size_t allocateBytes(ArrayRef<uint8_t> Data) {42return allocateCallback(43Data.size(), [Data](raw_ostream &OS) { OS << toStringRef(Data); });44}4546size_t allocateBytes(yaml::BinaryRef Data) {47return allocateCallback(Data.binary_size(), [Data](raw_ostream &OS) {48Data.writeAsBinary(OS);49});50}5152template <typename T> size_t allocateArray(ArrayRef<T> Data) {53return allocateBytes({reinterpret_cast<const uint8_t *>(Data.data()),54sizeof(T) * Data.size()});55}5657template <typename T, typename RangeType>58std::pair<size_t, MutableArrayRef<T>>59allocateNewArray(const iterator_range<RangeType> &Range);6061template <typename T> size_t allocateObject(const T &Data) {62return allocateArray(ArrayRef(Data));63}6465template <typename T, typename... Types>66std::pair<size_t, T *> allocateNewObject(Types &&... Args) {67T *Object = new (Temporaries.Allocate<T>()) T(std::forward<Types>(Args)...);68return {allocateObject(*Object), Object};69}7071size_t allocateString(StringRef Str);7273void writeTo(raw_ostream &OS) const;7475private:76size_t NextOffset = 0;7778BumpPtrAllocator Temporaries;79std::vector<std::function<void(raw_ostream &)>> Callbacks;80};81} // namespace8283template <typename T, typename RangeType>84std::pair<size_t, MutableArrayRef<T>>85BlobAllocator::allocateNewArray(const iterator_range<RangeType> &Range) {86size_t Num = std::distance(Range.begin(), Range.end());87MutableArrayRef<T> Array(Temporaries.Allocate<T>(Num), Num);88std::uninitialized_copy(Range.begin(), Range.end(), Array.begin());89return {allocateArray(Array), Array};90}9192size_t BlobAllocator::allocateString(StringRef Str) {93SmallVector<UTF16, 32> WStr;94bool OK = convertUTF8ToUTF16String(Str, WStr);95assert(OK && "Invalid UTF8 in Str?");96(void)OK;9798// The utf16 string is null-terminated, but the terminator is not counted in99// the string size.100WStr.push_back(0);101size_t Result =102allocateNewObject<support::ulittle32_t>(2 * (WStr.size() - 1)).first;103allocateNewArray<support::ulittle16_t>(make_range(WStr.begin(), WStr.end()));104return Result;105}106107void BlobAllocator::writeTo(raw_ostream &OS) const {108size_t BeginOffset = OS.tell();109for (const auto &Callback : Callbacks)110Callback(OS);111assert(OS.tell() == BeginOffset + NextOffset &&112"Callbacks wrote an unexpected number of bytes.");113(void)BeginOffset;114}115116static LocationDescriptor layout(BlobAllocator &File, yaml::BinaryRef Data) {117return {support::ulittle32_t(Data.binary_size()),118support::ulittle32_t(File.allocateBytes(Data))};119}120121static size_t layout(BlobAllocator &File, MinidumpYAML::ExceptionStream &S) {122File.allocateObject(S.MDExceptionStream);123124size_t DataEnd = File.tell();125126// Lay out the thread context data, (which is not a part of the stream).127// TODO: This usually (always?) matches the thread context of the128// corresponding thread, and may overlap memory regions as well. We could129// add a level of indirection to the MinidumpYAML format (like an array of130// Blobs that the LocationDescriptors index into) to be able to distinguish131// the cases where location descriptions overlap vs happen to reference132// identical data.133S.MDExceptionStream.ThreadContext = layout(File, S.ThreadContext);134135return DataEnd;136}137138static void layout(BlobAllocator &File, MemoryListStream::entry_type &Range) {139Range.Entry.Memory = layout(File, Range.Content);140}141142static void layout(BlobAllocator &File, ModuleListStream::entry_type &M) {143M.Entry.ModuleNameRVA = File.allocateString(M.Name);144145M.Entry.CvRecord = layout(File, M.CvRecord);146M.Entry.MiscRecord = layout(File, M.MiscRecord);147}148149static void layout(BlobAllocator &File, ThreadListStream::entry_type &T) {150T.Entry.Stack.Memory = layout(File, T.Stack);151T.Entry.Context = layout(File, T.Context);152}153154template <typename EntryT>155static size_t layout(BlobAllocator &File,156MinidumpYAML::detail::ListStream<EntryT> &S) {157158File.allocateNewObject<support::ulittle32_t>(S.Entries.size());159for (auto &E : S.Entries)160File.allocateObject(E.Entry);161162size_t DataEnd = File.tell();163164// Lay out the auxiliary data, (which is not a part of the stream).165DataEnd = File.tell();166for (auto &E : S.Entries)167layout(File, E);168169return DataEnd;170}171172static Directory layout(BlobAllocator &File, Stream &S) {173Directory Result;174Result.Type = S.Type;175Result.Location.RVA = File.tell();176std::optional<size_t> DataEnd;177switch (S.Kind) {178case Stream::StreamKind::Exception:179DataEnd = layout(File, cast<MinidumpYAML::ExceptionStream>(S));180break;181case Stream::StreamKind::MemoryInfoList: {182MemoryInfoListStream &InfoList = cast<MemoryInfoListStream>(S);183File.allocateNewObject<minidump::MemoryInfoListHeader>(184sizeof(minidump::MemoryInfoListHeader), sizeof(minidump::MemoryInfo),185InfoList.Infos.size());186File.allocateArray(ArrayRef(InfoList.Infos));187break;188}189case Stream::StreamKind::MemoryList:190DataEnd = layout(File, cast<MemoryListStream>(S));191break;192case Stream::StreamKind::ModuleList:193DataEnd = layout(File, cast<ModuleListStream>(S));194break;195case Stream::StreamKind::RawContent: {196RawContentStream &Raw = cast<RawContentStream>(S);197File.allocateCallback(Raw.Size, [&Raw](raw_ostream &OS) {198Raw.Content.writeAsBinary(OS);199assert(Raw.Content.binary_size() <= Raw.Size);200OS << std::string(Raw.Size - Raw.Content.binary_size(), '\0');201});202break;203}204case Stream::StreamKind::SystemInfo: {205SystemInfoStream &SystemInfo = cast<SystemInfoStream>(S);206File.allocateObject(SystemInfo.Info);207// The CSD string is not a part of the stream.208DataEnd = File.tell();209SystemInfo.Info.CSDVersionRVA = File.allocateString(SystemInfo.CSDVersion);210break;211}212case Stream::StreamKind::TextContent:213File.allocateArray(arrayRefFromStringRef(cast<TextContentStream>(S).Text));214break;215case Stream::StreamKind::ThreadList:216DataEnd = layout(File, cast<ThreadListStream>(S));217break;218}219// If DataEnd is not set, we assume everything we generated is a part of the220// stream.221Result.Location.DataSize =222DataEnd.value_or(File.tell()) - Result.Location.RVA;223return Result;224}225226namespace llvm {227namespace yaml {228229bool yaml2minidump(MinidumpYAML::Object &Obj, raw_ostream &Out,230ErrorHandler /*EH*/) {231BlobAllocator File;232File.allocateObject(Obj.Header);233234std::vector<Directory> StreamDirectory(Obj.Streams.size());235Obj.Header.StreamDirectoryRVA = File.allocateArray(ArrayRef(StreamDirectory));236Obj.Header.NumberOfStreams = StreamDirectory.size();237238for (const auto &[Index, Stream] : enumerate(Obj.Streams))239StreamDirectory[Index] = layout(File, *Stream);240241File.writeTo(Out);242return true;243}244245} // namespace yaml246} // namespace llvm247248249