#include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h"
#include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
#include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
#include "llvm/DebugInfo/CodeView/TypeIndex.h"
#include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
#include "llvm/DebugInfo/CodeView/TypeRecord.h"
#include "llvm/DebugInfo/CodeView/TypeRecordHelpers.h"
#include "llvm/Support/Error.h"
using namespace llvm;
using namespace llvm::codeview;
static inline size_t slotForIndex(TypeIndex Idx) {
assert(!Idx.isSimple() && "simple type indices have no slots");
return Idx.getIndex() - TypeIndex::FirstNonSimpleIndex;
}
namespace {
class TypeStreamMerger {
public:
explicit TypeStreamMerger(SmallVectorImpl<TypeIndex> &SourceToDest)
: IndexMap(SourceToDest) {
CurIndex += SourceToDest.size();
}
static const TypeIndex Untranslated;
Error mergeTypesAndIds(MergingTypeTableBuilder &DestIds,
MergingTypeTableBuilder &DestTypes,
const CVTypeArray &IdsAndTypes, Optional<uint32_t> &S);
Error mergeIdRecords(MergingTypeTableBuilder &Dest,
ArrayRef<TypeIndex> TypeSourceToDest,
const CVTypeArray &Ids);
Error mergeTypeRecords(MergingTypeTableBuilder &Dest,
const CVTypeArray &Types);
Error mergeTypesAndIds(GlobalTypeTableBuilder &DestIds,
GlobalTypeTableBuilder &DestTypes,
const CVTypeArray &IdsAndTypes,
ArrayRef<GloballyHashedType> Hashes,
Optional<uint32_t> &S);
Error mergeIdRecords(GlobalTypeTableBuilder &Dest,
ArrayRef<TypeIndex> TypeSourceToDest,
const CVTypeArray &Ids,
ArrayRef<GloballyHashedType> Hashes);
Error mergeTypeRecords(GlobalTypeTableBuilder &Dest, const CVTypeArray &Types,
ArrayRef<GloballyHashedType> Hashes,
Optional<uint32_t> &S);
private:
Error doit(const CVTypeArray &Types);
Error remapAllTypes(const CVTypeArray &Types);
Error remapType(const CVType &Type);
void addMapping(TypeIndex Idx);
inline bool remapTypeIndex(TypeIndex &Idx) {
if (!hasTypeStream())
return remapIndex(Idx, TypeLookup);
assert(TypeLookup.empty());
return remapIndex(Idx, IndexMap);
}
inline bool remapItemIndex(TypeIndex &Idx) {
assert(hasIdStream());
return remapIndex(Idx, IndexMap);
}
bool hasTypeStream() const {
return (UseGlobalHashes) ? (!!DestGlobalTypeStream) : (!!DestTypeStream);
}
bool hasIdStream() const {
return (UseGlobalHashes) ? (!!DestGlobalIdStream) : (!!DestIdStream);
}
ArrayRef<uint8_t> remapIndices(const CVType &OriginalType,
MutableArrayRef<uint8_t> Storage);
inline bool remapIndex(TypeIndex &Idx, ArrayRef<TypeIndex> Map) {
if (LLVM_LIKELY(remapIndexSimple(Idx, Map)))
return true;
return remapIndexFallback(Idx, Map);
}
inline bool remapIndexSimple(TypeIndex &Idx, ArrayRef<TypeIndex> Map) const {
if (Idx.isSimple())
return true;
unsigned MapPos = slotForIndex(Idx);
if (LLVM_UNLIKELY(MapPos >= Map.size() || Map[MapPos] == Untranslated))
return false;
Idx = Map[MapPos];
return true;
}
bool remapIndexFallback(TypeIndex &Idx, ArrayRef<TypeIndex> Map);
Error errorCorruptRecord() const {
return llvm::make_error<CodeViewError>(cv_error_code::corrupt_record);
}
Expected<bool> shouldRemapType(const CVType &Type);
Optional<Error> LastError;
bool UseGlobalHashes = false;
bool IsSecondPass = false;
unsigned NumBadIndices = 0;
TypeIndex CurIndex{TypeIndex::FirstNonSimpleIndex};
MergingTypeTableBuilder *DestIdStream = nullptr;
MergingTypeTableBuilder *DestTypeStream = nullptr;
GlobalTypeTableBuilder *DestGlobalIdStream = nullptr;
GlobalTypeTableBuilder *DestGlobalTypeStream = nullptr;
ArrayRef<GloballyHashedType> GlobalHashes;
ArrayRef<TypeIndex> TypeLookup;
SmallVectorImpl<TypeIndex> &IndexMap;
SmallVector<uint8_t, 256> RemapStorage;
Optional<uint32_t> PCHSignature;
};
}
const TypeIndex TypeStreamMerger::Untranslated(SimpleTypeKind::NotTranslated);
void TypeStreamMerger::addMapping(TypeIndex Idx) {
if (!IsSecondPass) {
assert(IndexMap.size() == slotForIndex(CurIndex) &&
"visitKnownRecord should add one index map entry");
IndexMap.push_back(Idx);
} else {
assert(slotForIndex(CurIndex) < IndexMap.size());
IndexMap[slotForIndex(CurIndex)] = Idx;
}
}
bool TypeStreamMerger::remapIndexFallback(TypeIndex &Idx,
ArrayRef<TypeIndex> Map) {
size_t MapPos = slotForIndex(Idx);
if (IsSecondPass && MapPos >= Map.size()) {
if (LastError)
LastError = joinErrors(std::move(*LastError), errorCorruptRecord());
else
LastError = errorCorruptRecord();
}
++NumBadIndices;
Idx = Untranslated;
return false;
}
Error TypeStreamMerger::mergeTypeRecords(MergingTypeTableBuilder &Dest,
const CVTypeArray &Types) {
DestTypeStream = &Dest;
UseGlobalHashes = false;
return doit(Types);
}
Error TypeStreamMerger::mergeIdRecords(MergingTypeTableBuilder &Dest,
ArrayRef<TypeIndex> TypeSourceToDest,
const CVTypeArray &Ids) {
DestIdStream = &Dest;
TypeLookup = TypeSourceToDest;
UseGlobalHashes = false;
return doit(Ids);
}
Error TypeStreamMerger::mergeTypesAndIds(MergingTypeTableBuilder &DestIds,
MergingTypeTableBuilder &DestTypes,
const CVTypeArray &IdsAndTypes,
Optional<uint32_t> &S) {
DestIdStream = &DestIds;
DestTypeStream = &DestTypes;
UseGlobalHashes = false;
auto Err = doit(IdsAndTypes);
S = PCHSignature;
return Err;
}
Error TypeStreamMerger::mergeTypeRecords(GlobalTypeTableBuilder &Dest,
const CVTypeArray &Types,
ArrayRef<GloballyHashedType> Hashes,
Optional<uint32_t> &S) {
DestGlobalTypeStream = &Dest;
UseGlobalHashes = true;
GlobalHashes = Hashes;
auto Err = doit(Types);
S = PCHSignature;
return Err;
}
Error TypeStreamMerger::mergeIdRecords(GlobalTypeTableBuilder &Dest,
ArrayRef<TypeIndex> TypeSourceToDest,
const CVTypeArray &Ids,
ArrayRef<GloballyHashedType> Hashes) {
DestGlobalIdStream = &Dest;
TypeLookup = TypeSourceToDest;
UseGlobalHashes = true;
GlobalHashes = Hashes;
return doit(Ids);
}
Error TypeStreamMerger::mergeTypesAndIds(GlobalTypeTableBuilder &DestIds,
GlobalTypeTableBuilder &DestTypes,
const CVTypeArray &IdsAndTypes,
ArrayRef<GloballyHashedType> Hashes,
Optional<uint32_t> &S) {
DestGlobalIdStream = &DestIds;
DestGlobalTypeStream = &DestTypes;
UseGlobalHashes = true;
GlobalHashes = Hashes;
auto Err = doit(IdsAndTypes);
S = PCHSignature;
return Err;
}
Error TypeStreamMerger::doit(const CVTypeArray &Types) {
if (auto EC = remapAllTypes(Types))
return EC;
while (!LastError && NumBadIndices > 0) {
unsigned BadIndicesRemaining = NumBadIndices;
IsSecondPass = true;
NumBadIndices = 0;
CurIndex = TypeIndex(TypeIndex::FirstNonSimpleIndex);
if (auto EC = remapAllTypes(Types))
return EC;
assert(NumBadIndices <= BadIndicesRemaining &&
"second pass found more bad indices");
if (!LastError && NumBadIndices == BadIndicesRemaining) {
return llvm::make_error<CodeViewError>(
cv_error_code::corrupt_record, "Input type graph contains cycles");
}
}
if (LastError)
return std::move(*LastError);
return Error::success();
}
Error TypeStreamMerger::remapAllTypes(const CVTypeArray &Types) {
BinaryStreamRef Stream = Types.getUnderlyingStream();
ArrayRef<uint8_t> Buffer;
cantFail(Stream.readBytes(0, Stream.getLength(), Buffer));
return forEachCodeViewRecord<CVType>(
Buffer, [this](const CVType &T) { return remapType(T); });
}
Error TypeStreamMerger::remapType(const CVType &Type) {
auto R = shouldRemapType(Type);
if (!R)
return R.takeError();
TypeIndex DestIdx = Untranslated;
if (*R) {
auto DoSerialize =
[this, Type](MutableArrayRef<uint8_t> Storage) -> ArrayRef<uint8_t> {
return remapIndices(Type, Storage);
};
unsigned AlignedSize = alignTo(Type.RecordData.size(), 4);
if (LLVM_LIKELY(UseGlobalHashes)) {
GlobalTypeTableBuilder &Dest =
isIdRecord(Type.kind()) ? *DestGlobalIdStream : *DestGlobalTypeStream;
GloballyHashedType H = GlobalHashes[CurIndex.toArrayIndex()];
DestIdx = Dest.insertRecordAs(H, AlignedSize, DoSerialize);
} else {
MergingTypeTableBuilder &Dest =
isIdRecord(Type.kind()) ? *DestIdStream : *DestTypeStream;
RemapStorage.resize(AlignedSize);
ArrayRef<uint8_t> Result = DoSerialize(RemapStorage);
if (!Result.empty())
DestIdx = Dest.insertRecordBytes(Result);
}
}
addMapping(DestIdx);
++CurIndex;
assert((IsSecondPass || IndexMap.size() == slotForIndex(CurIndex)) &&
"visitKnownRecord should add one index map entry");
return Error::success();
}
ArrayRef<uint8_t>
TypeStreamMerger::remapIndices(const CVType &OriginalType,
MutableArrayRef<uint8_t> Storage) {
unsigned Align = OriginalType.RecordData.size() & 3;
assert(Storage.size() == alignTo(OriginalType.RecordData.size(), 4) &&
"The storage buffer size is not a multiple of 4 bytes which will "
"cause misalignment in the output TPI stream!");
SmallVector<TiReference, 4> Refs;
discoverTypeIndices(OriginalType.RecordData, Refs);
if (Refs.empty() && Align == 0)
return OriginalType.RecordData;
::memcpy(Storage.data(), OriginalType.RecordData.data(),
OriginalType.RecordData.size());
uint8_t *DestContent = Storage.data() + sizeof(RecordPrefix);
for (auto &Ref : Refs) {
TypeIndex *DestTIs =
reinterpret_cast<TypeIndex *>(DestContent + Ref.Offset);
for (size_t I = 0; I < Ref.Count; ++I) {
TypeIndex &TI = DestTIs[I];
bool Success = (Ref.Kind == TiRefKind::IndexRef) ? remapItemIndex(TI)
: remapTypeIndex(TI);
if (LLVM_UNLIKELY(!Success))
return {};
}
}
if (Align > 0) {
RecordPrefix *StorageHeader =
reinterpret_cast<RecordPrefix *>(Storage.data());
StorageHeader->RecordLen += 4 - Align;
DestContent = Storage.data() + OriginalType.RecordData.size();
for (; Align < 4; ++Align)
*DestContent++ = LF_PAD4 - Align;
}
return Storage;
}
Error llvm::codeview::mergeTypeRecords(MergingTypeTableBuilder &Dest,
SmallVectorImpl<TypeIndex> &SourceToDest,
const CVTypeArray &Types) {
TypeStreamMerger M(SourceToDest);
return M.mergeTypeRecords(Dest, Types);
}
Error llvm::codeview::mergeIdRecords(MergingTypeTableBuilder &Dest,
ArrayRef<TypeIndex> TypeSourceToDest,
SmallVectorImpl<TypeIndex> &SourceToDest,
const CVTypeArray &Ids) {
TypeStreamMerger M(SourceToDest);
return M.mergeIdRecords(Dest, TypeSourceToDest, Ids);
}
Error llvm::codeview::mergeTypeAndIdRecords(
MergingTypeTableBuilder &DestIds, MergingTypeTableBuilder &DestTypes,
SmallVectorImpl<TypeIndex> &SourceToDest, const CVTypeArray &IdsAndTypes,
Optional<uint32_t> &PCHSignature) {
TypeStreamMerger M(SourceToDest);
return M.mergeTypesAndIds(DestIds, DestTypes, IdsAndTypes, PCHSignature);
}
Error llvm::codeview::mergeTypeAndIdRecords(
GlobalTypeTableBuilder &DestIds, GlobalTypeTableBuilder &DestTypes,
SmallVectorImpl<TypeIndex> &SourceToDest, const CVTypeArray &IdsAndTypes,
ArrayRef<GloballyHashedType> Hashes, Optional<uint32_t> &PCHSignature) {
TypeStreamMerger M(SourceToDest);
return M.mergeTypesAndIds(DestIds, DestTypes, IdsAndTypes, Hashes,
PCHSignature);
}
Error llvm::codeview::mergeTypeRecords(GlobalTypeTableBuilder &Dest,
SmallVectorImpl<TypeIndex> &SourceToDest,
const CVTypeArray &Types,
ArrayRef<GloballyHashedType> Hashes,
Optional<uint32_t> &PCHSignature) {
TypeStreamMerger M(SourceToDest);
return M.mergeTypeRecords(Dest, Types, Hashes, PCHSignature);
}
Error llvm::codeview::mergeIdRecords(GlobalTypeTableBuilder &Dest,
ArrayRef<TypeIndex> Types,
SmallVectorImpl<TypeIndex> &SourceToDest,
const CVTypeArray &Ids,
ArrayRef<GloballyHashedType> Hashes) {
TypeStreamMerger M(SourceToDest);
return M.mergeIdRecords(Dest, Types, Ids, Hashes);
}
Expected<bool> TypeStreamMerger::shouldRemapType(const CVType &Type) {
if (Type.kind() == LF_ENDPRECOMP) {
EndPrecompRecord EP;
if (auto EC = TypeDeserializer::deserializeAs(const_cast<CVType &>(Type),
EP))
return joinErrors(std::move(EC), errorCorruptRecord());
if (PCHSignature)
return errorCorruptRecord();
PCHSignature.emplace(EP.getSignature());
return false;
}
return true;
}