#include "DebugMap.h"
#include "BinaryHolder.h"
#include "DebugMap.h"
#include "dsymutil.h"
#include "llvm/ADT/IntervalMap.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/DIE.h"
#include "llvm/Config/config.h"
#include "../../lib/CodeGen/AsmPrinter/DwarfAccelTable.h"
#include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCCodeEmitter.h"
#include "llvm/MC/MCDwarf.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCMachObjectWriter.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCAsmLayout.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCCodeEmitter.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCObjectStreamer.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSectionMachO.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/Object/MachO.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/LEB128.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include <cstdlib>
#include <string>
#include <tuple>
#define DEBUG_TYPE "dsymutil-dwarf-linker"
namespace llvm {
namespace dsymutil {
namespace {
void warn(const Twine &Warning, const Twine &Context) {
errs() << Twine("while processing ") + Context + ":\n";
errs() << Twine("warning: ") + Warning + "\n";
}
bool error(const Twine &Error, const Twine &Context) {
errs() << Twine("while processing ") + Context + ":\n";
errs() << Twine("error: ") + Error + "\n";
return false;
}
Optional<object::SectionRef>
getSectionByName(const object::ObjectFile &Obj, StringRef SecName) {
for (const object::SectionRef &Section : Obj.sections()) {
StringRef SectionName;
Section.getName(SectionName);
SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
if (SectionName != SecName)
continue;
return Section;
}
return None;
}
template <typename KeyT, typename ValT>
using HalfOpenIntervalMap =
IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
IntervalMapHalfOpenInfo<KeyT>>;
typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
class CompileUnit;
class DeclContext {
StringRef Name;
DeclContext *Parent;
DeclContext *Collision;
StringRef File;
uint32_t Line;
uint32_t ByteSize;
uint32_t LastSeenCompileUnitID;
const DWARFDebugInfoEntryMinimal *LastSeenDIE;
uint32_t QualifiedNameHash;
uint32_t CanonicalDIEOffset;
uint16_t Tag;
bool Valid;
public:
typedef DenseMap<uint32_t, DeclContext *> Map;
DeclContext()
: Parent(nullptr), LastSeenCompileUnitID(0), QualifiedNameHash(5381),
CanonicalDIEOffset(0), Tag(dwarf::DW_TAG_compile_unit), Valid(true) {}
DeclContext(StringRef Name, uint32_t Hash, DeclContext *Parent,
StringRef File, uint32_t Line, uint32_t ByteSize, uint16_t Tag,
unsigned CUId)
: Name(Name), Parent(Parent), Collision(nullptr), File(File), Line(Line),
ByteSize(ByteSize), LastSeenCompileUnitID(CUId), LastSeenDIE(nullptr),
QualifiedNameHash(Hash), CanonicalDIEOffset(0), Tag(Tag), Valid(true) {
}
uint32_t getQualifiedNameHash() const { return QualifiedNameHash; }
void setLastSeenDIE(const DWARFDebugInfoEntryMinimal *Die) {
LastSeenDIE = Die;
}
void resetLastSeen(CompileUnit &U);
std::pair<DeclContext *, DeclContext *>
getChild(DeclContext::Map &Contexts, StringRef ShortName,
StringRef Name, StringRef File, unsigned Line,
unsigned ByteSize, uint16_t Tag, CompileUnit &U);
uint32_t getCanonicalDIEOffset() const { return CanonicalDIEOffset; }
void setCanonicalDIEOffset(uint32_t Offset) { CanonicalDIEOffset = Offset; }
uint16_t getTag() const { return Tag; }
DeclContext *getParent() const { return Parent; }
void invalidate() { Valid = false; }
bool isValid() const { return Valid; }
};
class CompileUnit {
public:
struct DIEInfo {
int64_t AddrAdjust; DeclContext *Ctxt; DIE *Clone; uint32_t ParentIdx; bool Keep; bool InDebugMap; };
CompileUnit(DWARFUnit &OrigUnit, unsigned ID, bool CanUseODR,
const DebugMapObject &Obj)
: OrigUnit(OrigUnit), ID(ID), CUDie(nullptr), StartOffset(0),
NextUnitOffset(0), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
Ranges(RangeAlloc), UnitRangeAttribute(nullptr),
HasInterestingContent(false) {
Info.resize(OrigUnit.getNumDIEs());
const auto *CUDie = OrigUnit.getCompileUnitDIE(false);
unsigned Lang = CUDie->getAttributeValueAsUnsignedConstant(
&OrigUnit, dwarf::DW_AT_language, 0);
HasODR = CanUseODR && (Lang == dwarf::DW_LANG_C_plus_plus ||
Lang == dwarf::DW_LANG_C_plus_plus_03 ||
Lang == dwarf::DW_LANG_C_plus_plus_11 ||
Lang == dwarf::DW_LANG_C_plus_plus_14 ||
Lang == dwarf::DW_LANG_ObjC_plus_plus);
}
CompileUnit(CompileUnit &&RHS)
: OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
llvm_unreachable("CompileUnits should not be moved.");
}
DWARFUnit &getOrigUnit() const { return OrigUnit; }
unsigned getUniqueID() const { return ID; }
DIE *getOutputUnitDIE() const { return CUDie; }
void setOutputUnitDIE(DIE *Die) { CUDie = Die; }
bool hasODR() const { return HasODR; }
DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
uint64_t getStartOffset() const { return StartOffset; }
uint64_t getNextUnitOffset() const { return NextUnitOffset; }
void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
uint64_t getLowPc() const { return LowPc; }
uint64_t getHighPc() const { return HighPc; }
bool hasLabelAt(uint64_t Addr) const { return Labels.count(Addr); }
DIEInteger *getUnitRangesAttribute() const { return UnitRangeAttribute; }
const FunctionIntervals &getFunctionRanges() const { return Ranges; }
const std::vector<DIEInteger *> &getRangesAttributes() const {
return RangeAttributes;
}
const std::vector<std::pair<DIEInteger *, int64_t>> &
getLocationAttributes() const {
return LocationAttributes;
}
void setHasInterestingContent() { HasInterestingContent = true; }
bool hasInterestingContent() { return HasInterestingContent; }
void markEverythingAsKept();
uint64_t computeNextUnitOffset();
void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
DeclContext *Ctxt, DIEInteger *Attr);
void fixupForwardReferences();
void addLabelLowPc(uint64_t LabelLowPc, int64_t PcOffset);
uint64_t getMinLabelInCU() const { return LowPc; }
void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
void noteRangeAttribute(const DIE &Die, DIEInteger *Attr);
void noteLocationAttribute(DIEInteger *Attr, int64_t PcOffset);
void addObjCAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
bool SkipPubnamesSection = false);
void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
bool SkipPubnamesSection = false);
void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
bool ObjCClassIsImplementation,
uint32_t QualifiedNameHash);
void addNamespaceAccelerator(const DIE *Die, const char *Name,
uint32_t Offset);
struct AccelInfo {
StringRef Name;
const DIE *Die;
uint32_t NameOffset;
uint32_t QualifiedNameHash;
bool SkipPubSection : 1;
bool ObjCClassIsImplementation : 1;
AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
bool SkipPubSection = false,
bool ObjCClassIsImplementation = false, uint32_t Hash = 0)
: Name(Name), Die(Die), NameOffset(NameOffset), QualifiedNameHash(Hash),
SkipPubSection(SkipPubSection),
ObjCClassIsImplementation(ObjCClassIsImplementation) {}
};
const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
const std::vector<AccelInfo> &getNamespaces() const { return Namespaces; }
const std::vector<AccelInfo> &getObjC() const { return ObjC; }
private:
DWARFUnit &OrigUnit;
unsigned ID;
std::vector<DIEInfo> Info; DIE *CUDie;
uint64_t StartOffset;
uint64_t NextUnitOffset;
uint64_t LowPc;
uint64_t HighPc;
std::vector<std::tuple<DIE *, const CompileUnit *, DeclContext *,
DIEInteger *>> ForwardDIEReferences;
FunctionIntervals::Allocator RangeAlloc;
FunctionIntervals Ranges;
SmallDenseMap<uint64_t, uint64_t, 1> Labels;
std::vector<DIEInteger *> RangeAttributes;
DIEInteger *UnitRangeAttribute;
std::vector<std::pair<DIEInteger *, int64_t>> LocationAttributes;
std::vector<AccelInfo> Namespaces;
std::vector<AccelInfo> Pubnames;
std::vector<AccelInfo> Pubtypes;
std::vector<AccelInfo> ObjC;
public:
const DWARFDebugInfoEntryMinimal *
getParent(const DWARFDebugInfoEntryMinimal *DIE) {
unsigned Idx = OrigUnit.getDIEIndex(DIE);
if (Idx == 0)
return nullptr;
return OrigUnit.getDIEAtIndex(Info[Idx].ParentIdx);
}
const char *getResolvedPath(unsigned FileNum) {
if (FileNum >= ResolvedPaths.size())
return nullptr;
return ResolvedPaths[FileNum].size() ? ResolvedPaths[FileNum].c_str()
: nullptr;
}
void setResolvedPath(unsigned FileNum, const std::string &Path) {
if (ResolvedPaths.size() <= FileNum)
ResolvedPaths.resize(FileNum + 1);
ResolvedPaths[FileNum] = Path;
}
std::vector<std::string> ResolvedPaths;
bool HasODR;
bool HasInterestingContent; };
static bool inFunctionScope(CompileUnit &U, unsigned Idx) {
if (Idx == 0)
return false;
if (U.getOrigUnit().getDIEAtIndex(Idx)->getTag() == dwarf::DW_TAG_subprogram)
return true;
return inFunctionScope(U, U.getInfo(Idx).ParentIdx);
}
void CompileUnit::markEverythingAsKept() {
unsigned Idx = 0;
for (auto &I : Info) {
I.Keep = true;
const auto *DIE = OrigUnit.getDIEAtIndex(Idx++);
if (DIE->getTag() != dwarf::DW_TAG_variable &&
DIE->getTag() != dwarf::DW_TAG_constant)
continue;
DWARFFormValue Value;
if (!DIE->getAttributeValue(&OrigUnit, dwarf::DW_AT_location, Value)) {
if (DIE->getAttributeValue(&OrigUnit, dwarf::DW_AT_const_value, Value) &&
!inFunctionScope(*this, I.ParentIdx))
I.InDebugMap = true;
continue;
}
if (auto Block = Value.getAsBlock()) {
if (Block->size() >= OrigUnit.getAddressByteSize() + 1 &&
(*Block)[0] == dwarf::DW_OP_addr)
I.InDebugMap = true;
}
}
}
uint64_t CompileUnit::computeNextUnitOffset() {
NextUnitOffset = StartOffset + 11 ;
if (CUDie)
NextUnitOffset += CUDie->getSize();
return NextUnitOffset;
}
void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
DeclContext *Ctxt, DIEInteger *Attr) {
ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
}
void CompileUnit::fixupForwardReferences() {
for (const auto &Ref : ForwardDIEReferences) {
DIE *RefDie;
const CompileUnit *RefUnit;
DIEInteger *Attr;
DeclContext *Ctxt;
std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
if (Ctxt && Ctxt->getCanonicalDIEOffset())
Attr->setValue(Ctxt->getCanonicalDIEOffset());
else
Attr->setValue(RefDie->getOffset() + RefUnit->getStartOffset());
}
}
void CompileUnit::addLabelLowPc(uint64_t LabelLowPc, int64_t PcOffset) {
Labels.insert({LabelLowPc, PcOffset});
}
void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
int64_t PcOffset) {
Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
}
void CompileUnit::noteRangeAttribute(const DIE &Die, DIEInteger *Attr) {
if (Die.getTag() != dwarf::DW_TAG_compile_unit)
RangeAttributes.push_back(Attr);
else
UnitRangeAttribute = Attr;
}
void CompileUnit::noteLocationAttribute(DIEInteger *Attr, int64_t PcOffset) {
LocationAttributes.emplace_back(Attr, PcOffset);
}
void CompileUnit::addObjCAccelerator(const DIE *Die, const char *Name,
uint32_t Offset, bool SkipPubSection) {
ObjC.emplace_back(Name, Die, Offset, SkipPubSection);
}
void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
uint32_t Offset, bool SkipPubSection) {
Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
}
void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
uint32_t Offset,
bool ObjCClassIsImplementation,
uint32_t FullyQualifiedNameHash) {
Pubtypes.emplace_back(Name, Die, Offset, false, ObjCClassIsImplementation,
FullyQualifiedNameHash);
}
void CompileUnit::addNamespaceAccelerator(const DIE *Die, const char *Name,
uint32_t Offset) {
Namespaces.emplace_back(Name, Die, Offset);
}
class NonRelocatableStringpool {
public:
typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
MapTy;
typedef std::function<StringRef (StringRef)> TranslatorTy;
NonRelocatableStringpool(TranslatorTy T = TranslatorTy())
: CurrentEndOffset(0), Sentinel(0), Last(&Sentinel), Translator(T) {
getStringOffset("");
}
uint32_t getStringOffset(StringRef S);
std::pair<const char *, uint32_t> getStringAndOffset(StringRef S);
StringRef internString(StringRef S);
const MapTy::MapEntryTy *getFirstEntry() const {
return getNextEntry(&Sentinel);
}
const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
}
uint64_t getSize() { return CurrentEndOffset; }
private:
MapTy Strings;
uint32_t CurrentEndOffset;
MapTy::MapEntryTy Sentinel, *Last;
TranslatorTy Translator;
};
std::pair<const char *, uint32_t>
NonRelocatableStringpool::getStringAndOffset(StringRef S) {
if (S.empty() && !Strings.empty())
return std::make_pair("", 0);
std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
MapTy::iterator It;
bool Inserted;
if (Translator)
S = Translator(S);
std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
if (Inserted || It->getValue().first == 0) {
It->getValue().first = CurrentEndOffset;
CurrentEndOffset += S.size() + 1; Last->getValue().second = &*It;
Last = &*It;
}
return std::make_pair(It->getKey().data(), It->getValue().first);
};
uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
return getStringAndOffset(S).second;
};
StringRef NonRelocatableStringpool::internString(StringRef S) {
std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
if (Translator)
S = Translator(S);
auto InsertResult = Strings.insert(std::make_pair(S, Entry));
return InsertResult.first->getKey();
};
class DwarfStreamer {
std::unique_ptr<MCRegisterInfo> MRI;
std::unique_ptr<MCAsmInfo> MAI;
std::unique_ptr<MCObjectFileInfo> MOFI;
std::unique_ptr<MCContext> MC;
MCAsmBackend *MAB; std::unique_ptr<MCInstrInfo> MII;
std::unique_ptr<MCSubtargetInfo> MSTI;
MCCodeEmitter *MCE; MCStreamer *MS; std::unique_ptr<TargetMachine> TM;
std::unique_ptr<AsmPrinter> Asm;
std::unique_ptr<raw_fd_ostream> OutFile;
uint32_t RangesSectionSize;
uint32_t LocSectionSize;
uint32_t LineSectionSize;
uint32_t FrameSectionSize;
void emitPubSectionForUnit(const MCSection *Sec, StringRef Name,
const CompileUnit &Unit,
const std::vector<CompileUnit::AccelInfo> &Names);
public:
bool init(Triple TheTriple, StringRef OutputFilename, bool Minimize);
bool finish(const DebugMap &Map, NonRelocatableStringpool::TranslatorTy T);
AsmPrinter &getAsmPrinter() const { return *Asm; }
void switchToDebugInfoSection(unsigned DwarfVersion);
void emitCompileUnitHeader(CompileUnit &Unit);
void emitDIE(DIE &Die);
void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
void emitStrings(const NonRelocatableStringpool &Pool);
void emitRangesEntries(
int64_t UnitPcOffset, uint64_t OrigLowPc,
FunctionIntervals::const_iterator FuncRange,
const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
unsigned AddressSize);
void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
uint32_t getRangesSectionSize() const { return RangesSectionSize; }
void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
void emitLineTableForUnit(MCDwarfLineTableParameters Params,
StringRef PrologueBytes, unsigned MinInstLength,
std::vector<DWARFDebugLine::Row> &Rows,
unsigned AdddressSize);
void copyInvariantDebugSection(const object::ObjectFile &Obj,
LinkOptions &);
void translateLineTable(DataExtractor LineData, uint32_t Offset,
LinkOptions &Options);
uint32_t getLineSectionSize() const { return LineSectionSize; }
void emitPubNamesForUnit(const CompileUnit &Unit);
void emitPubTypesForUnit(const CompileUnit &Unit);
void emitCIE(StringRef CIEBytes);
void emitFDE(uint32_t CIEOffset, uint32_t AddrSize, uint64_t Address,
StringRef Bytes);
void emitAppleNamespaces(DwarfAccelTable &Table);
void emitAppleNames(DwarfAccelTable &Table);
void emitAppleTypes(DwarfAccelTable &Table);
void emitAppleObjc(DwarfAccelTable &Table);
void emitDebugInlined(
const std::map<std::pair<uint32_t, uint32_t>,
std::vector<std::pair<uint32_t, uint64_t>>> &Inlined);
void emitSwiftModule(StringRef Buffer);
uint32_t getFrameSectionSize() const { return FrameSectionSize; }
};
bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename,
bool Minimize) {
std::string ErrorStr;
std::string TripleName;
StringRef Context = "dwarf streamer init";
const Target *TheTarget =
TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
if (!TheTarget)
return error(ErrorStr, Context);
TripleName = TheTriple.getTriple();
MRI.reset(TheTarget->createMCRegInfo(TripleName));
if (!MRI)
return error(Twine("no register info for target ") + TripleName, Context);
MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
if (!MAI)
return error("no asm info for target " + TripleName, Context);
MOFI.reset(new MCObjectFileInfo);
MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
MOFI->InitMCObjectFileInfo(TripleName, Reloc::Default, CodeModel::Default,
*MC);
MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
if (!MAB)
return error("no asm backend for target " + TripleName, Context);
MII.reset(TheTarget->createMCInstrInfo());
if (!MII)
return error("no instr info info for target " + TripleName, Context);
MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
if (!MSTI)
return error("no subtarget info for target " + TripleName, Context);
MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
if (!MCE)
return error("no code emitter for target " + TripleName, Context);
std::error_code EC;
OutFile =
llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
if (EC)
return error(Twine(OutputFilename) + ": " + EC.message(), Context);
MS = TheTarget->createMCObjectStreamer(TripleName, *MC, *MAB, *OutFile, MCE,
*MSTI, false);
if (!MS)
return error("no object streamer for target " + TripleName, Context);
TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
if (!TM)
return error("no target machine for target " + TripleName, Context);
Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
if (!Asm)
return error("no asm printer for target " + TripleName, Context);
LineSectionSize = 0;
RangesSectionSize = 0;
LocSectionSize = 0;
LineSectionSize = 0;
FrameSectionSize = 0;
MS->SwitchSection(MOFI->getDwarfAbbrevSection());
MS->SwitchSection(MOFI->getDwarfARangesSection());
MS->SwitchSection(MOFI->getDwarfFrameSection());
MS->SwitchSection(MOFI->getDwarfInfoSection());
if (!Minimize)
Asm->OutStreamer.SwitchSection(
MC->getMachOSection("__DWARF", "__debug_inlined", MachO::S_ATTR_DEBUG,
SectionKind::getMetadata()));
MS->SwitchSection(MOFI->getDwarfLineSection());
MS->SwitchSection(MOFI->getDwarfLocSection());
if (!Minimize) {
MS->SwitchSection(MOFI->getDwarfPubNamesSection());
MS->SwitchSection(MOFI->getDwarfPubTypesSection());
}
MS->SwitchSection(MOFI->getDwarfRangesSection());
MS->SwitchSection(MOFI->getDwarfStrSection());
MS->SwitchSection(MOFI->getDwarfAccelNamesSection());
MS->SwitchSection(MOFI->getDwarfAccelTypesSection());
MS->SwitchSection(MOFI->getDwarfAccelNamespaceSection());
MS->SwitchSection(MOFI->getDwarfAccelObjCSection());
return true;
}
static MachO::mach_header getMachOHeader(const object::MachOObjectFile &Obj) {
if (!Obj.is64Bit())
return Obj.getHeader();
MachO::mach_header_64 Header64 = Obj.getHeader64();
MachO::mach_header Header;
memcpy(&Header, &Header64, sizeof(Header));
return Header;
}
template <typename FunctionTy>
static void iterateOnSegments(const object::MachOObjectFile &Obj,
const MachO::mach_header &Header,
FunctionTy Handler) {
object::MachOObjectFile::LoadCommandInfo LCI = Obj.getFirstLoadCommandInfo();
for (unsigned i = 0;; ++i) {
if (LCI.C.cmd == MachO::LC_SEGMENT) {
auto Segment = Obj.getSegmentLoadCommand(LCI);
Handler(LCI, Segment.segname, Segment.nsects);
} else if (LCI.C.cmd == MachO::LC_SEGMENT_64) {
auto Segment = Obj.getSegment64LoadCommand(LCI);
Handler(LCI, Segment.segname, Segment.nsects);
}
if (i == Header.ncmds - 1)
break;
LCI = Obj.getNextLoadCommandInfo(LCI);
}
}
template <typename NListTy>
static bool transferSymbol(NListTy NList, bool IsLittleEndian,
StringRef Strings, SmallVectorImpl<char> &NewSymtab,
NonRelocatableStringpool &NewStrings,
bool &InDebugNote) {
if ((NList.n_type & MachO::N_TYPE) == MachO::N_UNDF)
return false;
StringRef Name = StringRef(Strings.begin() + NList.n_strx);
if (InDebugNote) {
InDebugNote =
(NList.n_type != MachO::N_SO) || (!Name.empty() && Name[0] != '\0');
return false;
} else if (NList.n_type == MachO::N_SO) {
InDebugNote = true;
return false;
}
NList.n_strx = NewStrings.getStringOffset(Name) + 1;
if (IsLittleEndian != sys::IsLittleEndianHost)
MachO::swapStruct(NList);
NewSymtab.append((char *)&NList, (char *)(&NList + 1));
return true;
}
static unsigned transferSymbols(const object::MachOObjectFile &Obj,
SmallVectorImpl<char> &NewSymtab,
NonRelocatableStringpool &NewStrings) {
unsigned Syms = 0;
StringRef Strings = Obj.getStringTableData();
bool IsLittleEndian = Obj.isLittleEndian();
bool InDebugNote = false;
if (Obj.is64Bit()) {
for (const object::SymbolRef &Symbol : Obj.symbols()) {
object::DataRefImpl DRI = Symbol.getRawDataRefImpl();
if (transferSymbol(Obj.getSymbol64TableEntry(DRI), IsLittleEndian,
Strings, NewSymtab, NewStrings, InDebugNote))
++Syms;
}
} else {
for (const object::SymbolRef &Symbol : Obj.symbols()) {
object::DataRefImpl DRI = Symbol.getRawDataRefImpl();
if (transferSymbol(Obj.getSymbolTableEntry(DRI), IsLittleEndian, Strings,
NewSymtab, NewStrings, InDebugNote))
++Syms;
}
}
return Syms;
}
static MachO::section
getSection(const object::MachOObjectFile &Obj,
const MachO::segment_command &Seg,
const object::MachOObjectFile::LoadCommandInfo &LCI, unsigned Idx) {
return Obj.getSection(LCI, Idx);
}
static MachO::section_64
getSection(const object::MachOObjectFile &Obj,
const MachO::segment_command_64 &Seg,
const object::MachOObjectFile::LoadCommandInfo &LCI, unsigned Idx) {
return Obj.getSection64(LCI, Idx);
}
template <typename SegmentTy>
static void transferSegmentAndSections(
const object::MachOObjectFile::LoadCommandInfo &LCI, SegmentTy Segment,
const object::MachOObjectFile &Obj, MCObjectWriter &Writer,
uint64_t LinkeditOffset, uint64_t LinkeditSize, uint64_t DwarfSegmentSize,
uint64_t &GapForDwarf, uint64_t &EndAddress) {
if (StringRef("__DWARF") == Segment.segname)
return;
unsigned NumSections = Segment.nsects;
Segment.fileoff = Segment.filesize = 0;
if (StringRef("__LINKEDIT") == Segment.segname) {
Segment.fileoff = LinkeditOffset;
Segment.filesize = LinkeditSize;
}
uint64_t PrevEndAddress = EndAddress;
EndAddress = RoundUpToAlignment(EndAddress, 0x1000);
if (GapForDwarf == UINT64_MAX && Segment.vmaddr > EndAddress &&
Segment.vmaddr - EndAddress >= DwarfSegmentSize)
GapForDwarf = EndAddress;
EndAddress = std::max<uint64_t>(PrevEndAddress,
Segment.vmaddr + Segment.vmsize);
if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
MachO::swapStruct(Segment);
Writer.WriteBytes(StringRef((char *)&Segment, sizeof(Segment)));
for (unsigned i = 0; i < NumSections; ++i) {
auto Sect = getSection(Obj, Segment, LCI, i);
Sect.offset = Sect.reloff = Sect.nreloc = 0;
if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
MachO::swapStruct(Sect);
Writer.WriteBytes(StringRef((char *)&Sect, sizeof(Sect)));
}
return;
}
template <typename SegmentTy, typename SectionTy>
static void createDwarfSegment(uint64_t VMAddr, uint64_t FileOffset,
uint64_t FileSize, unsigned NumSections,
MCAsmLayout &Layout, MachObjectWriter &Writer) {
SegmentTy Segment;
memset(&Segment, 0, sizeof(Segment));
memcpy(Segment.segname, "__DWARF", sizeof("__DWARF"));
Segment.cmd = sizeof(Segment) == sizeof(MachO::segment_command)
? MachO::LC_SEGMENT
: MachO::LC_SEGMENT_64;
Segment.cmdsize = sizeof(SegmentTy) + NumSections * sizeof(SectionTy);
Segment.nsects = NumSections;
Segment.fileoff = FileOffset;
Segment.filesize = FileSize;
Segment.vmsize = RoundUpToAlignment(FileSize, 0x1000);
Segment.vmaddr = VMAddr;
Segment.maxprot = 7;
Segment.initprot = 3;
if (Writer.isLittleEndian() != sys::IsLittleEndianHost)
MachO::swapStruct(Segment);
Writer.WriteBytes(StringRef((char *)&Segment, sizeof(Segment)));
for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
MCSectionData *SD = Layout.getSectionOrder()[i];
if (SD->empty())
continue;
uint64_t Size = Layout.getSectionFileSize(SD);
if (!Size)
continue;
SectionTy Section;
memset(&Section, 0, sizeof(SectionTy));
const MCSectionMachO &MachOSec = cast<MCSectionMachO>(SD->getSection());
StringRef Name = MachOSec.getSectionName();
unsigned Align = SD->getAlignment();
if (Align > 1) {
VMAddr = RoundUpToAlignment(VMAddr, Align);
FileOffset = RoundUpToAlignment(FileOffset, Align);
}
Writer.WriteBytes(Name, 16);
Writer.WriteBytes("__DWARF", 16);
if (Writer.is64Bit()) {
Writer.Write64(VMAddr); Writer.Write64(Size); } else {
Writer.Write32(VMAddr); Writer.Write32(Size); }
Writer.Write32(FileOffset);
Writer.Write32(Log2_32(Align));
Writer.Write32(0); Writer.Write32(0); Writer.Write32(0); Writer.Write32(0); Writer.Write32(0); if (Writer.is64Bit())
Writer.Write32(0);
FileOffset += Layout.getSectionAddressSize(SD);
VMAddr += Layout.getSectionAddressSize(SD);
}
}
static bool isKext(const object::MachOObjectFile &Obj) {
if (Obj.is64Bit())
return Obj.getHeader64().filetype == MachO::MH_OBJECT;
else
return Obj.getHeader().filetype == MachO::MH_OBJECT;
}
static bool hasLinkEditSegment(const object::MachOObjectFile &Obj) {
bool Result = false;
iterateOnSegments(Obj, getMachOHeader(Obj),
[&](const object::MachOObjectFile::LoadCommandInfo &LCI,
const char *Name, uint32_t NumSections) {
if (StringRef("__LINKEDIT") == Name)
Result = true;
});
return Result;
}
bool DwarfStreamer::finish(const DebugMap &DM,
NonRelocatableStringpool::TranslatorTy T) {
auto &ObjectStreamer = *static_cast<MCObjectStreamer *>(MS);
MCAssembler &MCAsm = ObjectStreamer.getAssembler();
auto &Writer = static_cast<MachObjectWriter &>(MCAsm.getWriter());
MCAsmLayout Layout(MCAsm);
for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
MCSectionData *SD = Layout.getSectionOrder()[i];
unsigned FragmentIndex = 0;
for (auto &Fragment : make_range(SD->begin(), SD->end()))
Fragment.setLayoutOrder(FragmentIndex++);
if (!SD->empty())
Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
}
MCAsm.fixup(Layout);
BinaryHolder InputBinaryHolder(false);
auto ErrOrObjs = InputBinaryHolder.GetObjectFiles(DM.getBinaryPath());
if (auto Error = ErrOrObjs.getError())
return error(Twine("opening ") + DM.getBinaryPath() + ": " +
Error.message(),
"output file streaming");
auto ErrOrInputBinary =
InputBinaryHolder.GetAs<object::MachOObjectFile>(DM.getTriple());
if (auto Error = ErrOrInputBinary.getError())
return error(Twine("opening ") + DM.getBinaryPath() + ": " +
Error.message(),
"output file streaming");
auto &InputBinary = *ErrOrInputBinary;
bool Is64Bit = InputBinary.is64Bit();
object::MachOObjectFile::LoadCommandInfo LCI =
InputBinary.getFirstLoadCommandInfo();
MachO::symtab_command SymtabCmd = InputBinary.getSymtabLoadCommand();
MachO::uuid_command UUIDCmd;
memset(&UUIDCmd, 0, sizeof(UUIDCmd));
UUIDCmd.cmd = MachO::LC_UUID;
UUIDCmd.cmdsize = 24;
MachO::mach_header Header = getMachOHeader(InputBinary);
for (unsigned i = 0;; ++i) {
if (LCI.C.cmd == MachO::LC_UUID) {
UUIDCmd = InputBinary.getUuidCommand(LCI);
break;
}
if (i == Header.ncmds - 1)
break;
LCI = InputBinary.getNextLoadCommandInfo(LCI);
}
unsigned LoadCommandSize = 0;
unsigned NumLoadCommands = 0;
if (UUIDCmd.cmd != 0) {
++NumLoadCommands;
LoadCommandSize += sizeof(MachO::uuid_command);
}
bool ShouldEmitSymtab =
!isKext(InputBinary) && hasLinkEditSegment(InputBinary);
if (ShouldEmitSymtab) {
LoadCommandSize += sizeof(MachO::symtab_command);
++NumLoadCommands;
}
unsigned HeaderSize =
Is64Bit ? sizeof(MachO::mach_header_64) : sizeof(MachO::mach_header);
iterateOnSegments(InputBinary, Header,
[&](const object::MachOObjectFile::LoadCommandInfo &LCI,
const char *Name, uint32_t NumSections) {
if (StringRef("__DWARF") == Name)
return;
++NumLoadCommands;
if (Is64Bit) {
LoadCommandSize += sizeof(MachO::segment_command_64);
LoadCommandSize +=
NumSections * sizeof(MachO::section_64);
} else {
LoadCommandSize += sizeof(MachO::segment_command);
LoadCommandSize += NumSections * sizeof(MachO::section);
}
});
unsigned NumDwarfSections = 0;
uint64_t DwarfSegmentSize = 0;
for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
MCSectionData *SD = Layout.getSectionOrder()[i];
if (SD->empty())
continue;
if (uint64_t Size = Layout.getSectionFileSize(SD)) {
DwarfSegmentSize =
RoundUpToAlignment(DwarfSegmentSize, SD->getAlignment());
DwarfSegmentSize += Size;
++NumDwarfSections;
}
}
if (NumDwarfSections) {
++NumLoadCommands;
if (Is64Bit) {
LoadCommandSize += sizeof(MachO::segment_command_64);
LoadCommandSize += NumDwarfSections * sizeof(MachO::section_64);
} else {
LoadCommandSize += sizeof(MachO::segment_command);
LoadCommandSize += NumDwarfSections * sizeof(MachO::section);
}
}
SmallString<0> NewSymtab;
NonRelocatableStringpool NewStrings(T);
unsigned NListSize = Is64Bit ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
unsigned NumSyms = 0;
uint64_t NewStringsSize = 0;
if (ShouldEmitSymtab) {
NewSymtab.reserve(SymtabCmd.nsyms * NListSize / 2);
NumSyms = transferSymbols(InputBinary, NewSymtab, NewStrings);
NewStringsSize = NewStrings.getSize() + 1;
}
uint64_t SymtabStart = LoadCommandSize;
SymtabStart += HeaderSize;
SymtabStart = RoundUpToAlignment(SymtabStart, 0x1000);
Writer.WriteHeader(MachO::MH_DSYM, NumLoadCommands, LoadCommandSize, false);
assert(OutFile->tell() == HeaderSize);
if (UUIDCmd.cmd != 0) {
Writer.Write32(UUIDCmd.cmd);
Writer.Write32(UUIDCmd.cmdsize);
Writer.WriteBytes(StringRef((const char *)UUIDCmd.uuid, 16));
assert(OutFile->tell() == HeaderSize + sizeof(UUIDCmd));
}
assert(SymtabCmd.cmd && "No symbol table.");
uint64_t StringStart = SymtabStart + NumSyms * NListSize;
if (ShouldEmitSymtab)
Writer.WriteSymtabLoadCommand(SymtabStart, NumSyms, StringStart,
NewStringsSize);
uint64_t DwarfSegmentStart = StringStart + NewStringsSize;
DwarfSegmentStart = RoundUpToAlignment(DwarfSegmentStart, 0x1000);
LCI = InputBinary.getFirstLoadCommandInfo();
uint64_t EndAddress = 0;
uint64_t GapForDwarf = UINT64_MAX;
for (unsigned i = 0;; ++i) {
if (LCI.C.cmd == MachO::LC_SEGMENT)
transferSegmentAndSections(LCI, InputBinary.getSegmentLoadCommand(LCI),
InputBinary, Writer, SymtabStart,
StringStart + NewStringsSize - SymtabStart,
DwarfSegmentSize, GapForDwarf, EndAddress);
else if (LCI.C.cmd == MachO::LC_SEGMENT_64)
transferSegmentAndSections(LCI, InputBinary.getSegment64LoadCommand(LCI),
InputBinary, Writer, SymtabStart,
StringStart + NewStringsSize - SymtabStart,
DwarfSegmentSize, GapForDwarf, EndAddress);
if (i == Header.ncmds - 1)
break;
LCI = InputBinary.getNextLoadCommandInfo(LCI);
}
uint64_t DwarfVMAddr = RoundUpToAlignment(EndAddress, 0x1000);
uint64_t DwarfVMMax = Is64Bit ? UINT64_MAX : UINT32_MAX;
if (DwarfVMAddr + DwarfSegmentSize > DwarfVMMax ||
DwarfVMAddr + DwarfSegmentSize < DwarfVMAddr ) {
DwarfVMAddr = GapForDwarf;
if (DwarfVMAddr == UINT64_MAX)
warn("not enough VM space for the __DWARF segment.",
"output file streaming");
}
if (Is64Bit)
createDwarfSegment<MachO::segment_command_64, MachO::section_64>(
DwarfVMAddr, DwarfSegmentStart, DwarfSegmentSize, NumDwarfSections,
Layout, Writer);
else
createDwarfSegment<MachO::segment_command, MachO::section>(
DwarfVMAddr, DwarfSegmentStart, DwarfSegmentSize, NumDwarfSections,
Layout, Writer);
assert(OutFile->tell() == LoadCommandSize + HeaderSize);
Writer.WriteZeros(SymtabStart - (LoadCommandSize + HeaderSize));
assert(OutFile->tell() == SymtabStart);
if (ShouldEmitSymtab) {
Writer.WriteBytes(NewSymtab.str());
assert(OutFile->tell() == StringStart);
Writer.WriteZeros(1);
typedef NonRelocatableStringpool::MapTy MapTy;
for (auto *Entry = NewStrings.getFirstEntry(); Entry;
Entry = static_cast<MapTy::MapEntryTy *>(Entry->getValue().second))
Writer.WriteBytes(
StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
}
assert(OutFile->tell() == StringStart + NewStringsSize);
Writer.WriteZeros(DwarfSegmentStart - (StringStart + NewStringsSize));
assert(OutFile->tell() == DwarfSegmentStart);
for (const MCSectionData &SD : make_range(MCAsm.begin(), MCAsm.end())) {
if (SD.empty())
continue;
uint64_t Pos = OutFile->tell();
Writer.WriteZeros(RoundUpToAlignment(Pos, SD.getAlignment()) - Pos);
MCAsm.writeSectionData(&SD, Layout);
}
return true;
}
void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
MS->SwitchSection(MOFI->getDwarfInfoSection());
MC->setDwarfVersion(DwarfVersion);
}
void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
unsigned Version = Unit.getOrigUnit().getVersion();
switchToDebugInfoSection(Version);
Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
Asm->EmitInt16(Version);
Asm->EmitInt32(0);
Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
}
void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
MS->SwitchSection(MOFI->getDwarfAbbrevSection());
Asm->emitDwarfAbbrevs(Abbrevs);
}
void DwarfStreamer::emitDIE(DIE &Die) {
MS->SwitchSection(MOFI->getDwarfInfoSection());
Asm->emitDwarfDIE(Die);
}
void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
Asm->OutStreamer.SwitchSection(MOFI->getDwarfStrSection());
for (auto *Entry = Pool.getFirstEntry(); Entry;
Entry = Pool.getNextEntry(Entry))
Asm->OutStreamer.EmitBytes(
StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
}
void DwarfStreamer::emitAppleNamespaces(DwarfAccelTable &Table) {
Asm->OutStreamer.SwitchSection(MOFI->getDwarfAccelNamespaceSection());
Table.FinalizeTable(Asm.get(), "namespac");
auto *SectionBegin = Asm->GetTempSymbol("namespac_begin");
Asm->OutStreamer.EmitLabel(SectionBegin);
Table.emit(Asm.get(), SectionBegin, nullptr);
}
void DwarfStreamer::emitAppleNames(DwarfAccelTable &Table) {
Asm->OutStreamer.SwitchSection(MOFI->getDwarfAccelNamesSection());
Table.FinalizeTable(Asm.get(), "names");
auto *SectionBegin = Asm->GetTempSymbol("names_begin");
Asm->OutStreamer.EmitLabel(SectionBegin);
Table.emit(Asm.get(), SectionBegin, nullptr);
}
void DwarfStreamer::emitAppleTypes(DwarfAccelTable &Table) {
Asm->OutStreamer.SwitchSection(MOFI->getDwarfAccelTypesSection());
Table.FinalizeTable(Asm.get(), "types");
auto *SectionBegin = Asm->GetTempSymbol("types_begin");
Asm->OutStreamer.EmitLabel(SectionBegin);
Table.emit(Asm.get(), SectionBegin, nullptr);
}
void DwarfStreamer::emitAppleObjc(DwarfAccelTable &Table) {
Asm->OutStreamer.SwitchSection(MOFI->getDwarfAccelObjCSection());
Table.FinalizeTable(Asm.get(), "objc");
auto *SectionBegin = Asm->GetTempSymbol("objc_begin");
Asm->OutStreamer.EmitLabel(SectionBegin);
Table.emit(Asm.get(), SectionBegin, nullptr);
}
void DwarfStreamer::emitDebugInlined(
const std::map<std::pair<uint32_t, uint32_t>,
std::vector<std::pair<uint32_t, uint64_t>>> &Inlined) {
if (Inlined.empty())
return;
Asm->OutStreamer.SwitchSection(
MC->getMachOSection("__DWARF", "__debug_inlined", MachO::S_ATTR_DEBUG,
SectionKind::getMetadata()));
MCSymbol *BeginLabel = Asm->GetTempSymbol("inlined_begin");
MCSymbol *EndLabel = Asm->GetTempSymbol("inlined_end");
Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
Asm->OutStreamer.EmitLabel(BeginLabel);
Asm->EmitInt16(2);
int AddressSize = Asm->getDataLayout().getPointerSize();
Asm->EmitInt8(AddressSize);
for (const auto &InlineFunction : Inlined) {
Asm->EmitInt32(InlineFunction.first.second);
Asm->EmitInt32(InlineFunction.first.first);
Asm->EmitULEB128(InlineFunction.second.size());
for (const auto &InlinePoint : InlineFunction.second) {
Asm->EmitInt32(InlinePoint.first);
MS->EmitIntValue(InlinePoint.second, AddressSize);
}
}
Asm->OutStreamer.EmitLabel(EndLabel);
}
void DwarfStreamer::emitRangesEntries(
int64_t UnitPcOffset, uint64_t OrigLowPc,
FunctionIntervals::const_iterator FuncRange,
const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
unsigned AddressSize) {
MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
for (const auto &Range : Entries) {
if (Range.isBaseAddressSelectionEntry(AddressSize)) {
warn("unsupported base address selection operation",
"emitting debug_ranges");
break;
}
if (Range.StartAddress == Range.EndAddress)
continue;
if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
Range.EndAddress + OrigLowPc <= FuncRange.stop()))
warn("inconsistent range data.", "emitting debug_ranges");
MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
RangesSectionSize += 2 * AddressSize;
}
MS->EmitIntValue(0, AddressSize);
MS->EmitIntValue(0, AddressSize);
RangesSectionSize += 2 * AddressSize;
}
void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
bool DoDebugRanges) {
unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
std::vector<std::pair<uint64_t, uint64_t>> Ranges;
const auto &FunctionRanges = Unit.getFunctionRanges();
for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
Range != End; ++Range)
Ranges.push_back(std::make_pair(Range.start() + Range.value(),
Range.stop() + Range.value()));
std::sort(Ranges.begin(), Ranges.end());
if (!Ranges.empty()) {
MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
MCSymbol *BeginLabel = Asm->GetTempSymbol("Barange", Unit.getUniqueID());
MCSymbol *EndLabel = Asm->GetTempSymbol("Earange", Unit.getUniqueID());
unsigned HeaderSize =
sizeof(int32_t) + sizeof(int16_t) + sizeof(int32_t) + sizeof(int8_t) + sizeof(int8_t);
unsigned TupleSize = AddressSize * 2;
unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); Asm->OutStreamer.EmitLabel(BeginLabel);
Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); Asm->EmitInt32(Unit.getStartOffset()); Asm->EmitInt8(AddressSize); Asm->EmitInt8(0);
Asm->OutStreamer.EmitFill(Padding, 0x0);
for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
++Range) {
uint64_t RangeStart = Range->first;
MS->EmitIntValue(RangeStart, AddressSize);
while ((Range + 1) != End && Range->second == (Range + 1)->first)
++Range;
MS->EmitIntValue(Range->second - RangeStart, AddressSize);
}
Asm->OutStreamer.EmitIntValue(0, AddressSize);
Asm->OutStreamer.EmitIntValue(0, AddressSize);
Asm->OutStreamer.EmitLabel(EndLabel);
}
if (!DoDebugRanges)
return;
MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
int64_t PcOffset = -Unit.getLowPc();
for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
MS->EmitIntValue(Range->first + PcOffset, AddressSize);
while (Range + 1 != End && Range->second == (Range + 1)->first)
++Range;
MS->EmitIntValue(Range->second + PcOffset, AddressSize);
RangesSectionSize += 2 * AddressSize;
}
MS->EmitIntValue(0, AddressSize);
MS->EmitIntValue(0, AddressSize);
RangesSectionSize += 2 * AddressSize;
}
void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
DWARFContext &Dwarf) {
const std::vector<std::pair<DIEInteger *, int64_t>> &Attributes =
Unit.getLocationAttributes();
if (Attributes.empty())
return;
MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
const DWARFSection &InputSec = Dwarf.getLocSection();
DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
DWARFUnit &OrigUnit = Unit.getOrigUnit();
const auto *OrigUnitDie = OrigUnit.getCompileUnitDIE(false);
int64_t UnitPcOffset = 0;
uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
if (OrigLowPc != -1ULL)
UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
for (const auto &Attr : Attributes) {
uint32_t Offset = Attr.first->getValue();
Attr.first->setValue(LocSectionSize);
int64_t LocPcOffset = Attr.second + UnitPcOffset;
while (Data.isValidOffset(Offset)) {
uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
uint64_t High = Data.getUnsigned(&Offset, AddressSize);
if (Low == 0 && High == 0) {
LocSectionSize += 2 * AddressSize;
Asm->OutStreamer.EmitIntValue(0, AddressSize);
Asm->OutStreamer.EmitIntValue(0, AddressSize);
break;
}
uint64_t Length = Data.getU16(&Offset);
if (Low != High) {
Asm->OutStreamer.EmitIntValue(Low + LocPcOffset, AddressSize);
Asm->OutStreamer.EmitIntValue(High + LocPcOffset, AddressSize);
Asm->OutStreamer.EmitIntValue(Length, 2);
Asm->OutStreamer.EmitBytes(
StringRef(InputSec.Data.substr(Offset, Length)));
LocSectionSize += 2 * AddressSize + Length + 2;
}
Offset += Length;
}
}
}
void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParameters Params,
StringRef PrologueBytes,
unsigned MinInstLength,
std::vector<DWARFDebugLine::Row> &Rows,
unsigned PointerSize) {
MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
MCSymbol *LineStartSym = MC->CreateTempSymbol();
MCSymbol *LineEndSym = MC->CreateTempSymbol();
Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
Asm->OutStreamer.EmitLabel(LineStartSym);
MS->EmitBytes(PrologueBytes);
LineSectionSize += PrologueBytes.size() + 4;
SmallString<128> EncodingBuffer;
raw_svector_ostream EncodingOS(EncodingBuffer);
if (Rows.empty()) {
MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
MS->EmitBytes(EncodingOS.str());
LineSectionSize += EncodingBuffer.size();
MS->EmitLabel(LineEndSym);
return;
}
unsigned FileNum = 1;
unsigned LastLine = 1;
unsigned Column = 0;
unsigned IsStatement = 1;
unsigned Isa = 0;
uint64_t Address = -1ULL;
unsigned RowsSinceLastSequence = 0;
for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
auto &Row = Rows[Idx];
int64_t AddressDelta;
if (Address == -1ULL) {
MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
MS->EmitULEB128IntValue(PointerSize + 1);
MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
MS->EmitIntValue(Row.Address, PointerSize);
LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
AddressDelta = 0;
} else {
AddressDelta = (Row.Address - Address) / MinInstLength;
}
if (FileNum != Row.File) {
FileNum = Row.File;
MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
MS->EmitULEB128IntValue(FileNum);
LineSectionSize += 1 + getULEB128Size(FileNum);
}
if (Column != Row.Column) {
Column = Row.Column;
MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
MS->EmitULEB128IntValue(Column);
LineSectionSize += 1 + getULEB128Size(Column);
}
if (Isa != Row.Isa) {
Isa = Row.Isa;
MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
MS->EmitULEB128IntValue(Isa);
LineSectionSize += 1 + getULEB128Size(Isa);
}
if (IsStatement != Row.IsStmt) {
IsStatement = Row.IsStmt;
MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
LineSectionSize += 1;
}
if (Row.BasicBlock) {
MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
LineSectionSize += 1;
}
if (Row.PrologueEnd) {
MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
LineSectionSize += 1;
}
if (Row.EpilogueBegin) {
MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
LineSectionSize += 1;
}
int64_t LineDelta = int64_t(Row.Line) - LastLine;
if (!Row.EndSequence) {
MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
MS->EmitBytes(EncodingOS.str());
LineSectionSize += EncodingBuffer.size();
EncodingBuffer.resize(0);
EncodingOS.resync();
Address = Row.Address;
LastLine = Row.Line;
RowsSinceLastSequence++;
} else {
if (LineDelta) {
MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
MS->EmitSLEB128IntValue(LineDelta);
LineSectionSize += 1 + getSLEB128Size(LineDelta);
}
if (AddressDelta) {
MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
MS->EmitULEB128IntValue(AddressDelta);
LineSectionSize += 1 + getULEB128Size(AddressDelta);
}
MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
MS->EmitBytes(EncodingOS.str());
LineSectionSize += EncodingBuffer.size();
EncodingBuffer.resize(0);
EncodingOS.resync();
Address = -1ULL;
LastLine = FileNum = IsStatement = 1;
RowsSinceLastSequence = Column = Isa = 0;
}
}
if (RowsSinceLastSequence) {
MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
MS->EmitBytes(EncodingOS.str());
LineSectionSize += EncodingBuffer.size();
EncodingBuffer.resize(0);
EncodingOS.resync();
}
MS->EmitLabel(LineEndSym);
}
static void emitSectionContents(const object::ObjectFile &Obj, StringRef SecName,
MCStreamer *MS) {
StringRef Contents;
if (auto Sec = getSectionByName(Obj, SecName))
if (!Sec->getContents(Contents))
MS->EmitBytes(Contents);
}
void DwarfStreamer::translateLineTable(DataExtractor Data, uint32_t Offset,
LinkOptions &Options) {
MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
StringRef Contents = Data.getData();
unsigned UnitLength = Data.getU32(&Offset);
unsigned UnitEnd = Offset + UnitLength;
MCSymbol *BeginLabel = MC->CreateTempSymbol();
MCSymbol *EndLabel = MC->CreateTempSymbol();
unsigned Version = Data.getU16(&Offset);
if (Version > 5) {
warn("Unsupported line table version. Dropping contents.",
"Unobfsucating line table");
return;
}
Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
Asm->OutStreamer.EmitLabel(BeginLabel);
Asm->EmitInt16(Version);
LineSectionSize += 6;
MCSymbol *HeaderBeginLabel = MC->CreateTempSymbol();
MCSymbol *HeaderEndLabel = MC->CreateTempSymbol();
Asm->EmitLabelDifference(HeaderEndLabel, HeaderBeginLabel, 4);
Asm->OutStreamer.EmitLabel(HeaderBeginLabel);
Offset += 4;
LineSectionSize += 4;
uint32_t AfterHeaderLengthOffset = Offset;
Offset += (Version >= 4) ? 5 : 4;
unsigned OpcodeBase = Data.getU8(&Offset);
Offset += OpcodeBase - 1;
Asm->OutStreamer.EmitBytes(Contents.slice(AfterHeaderLengthOffset, Offset));
LineSectionSize += Offset - AfterHeaderLengthOffset;
while (const char *Dir = Data.getCStr(&Offset)) {
if (Dir[0] == 0)
break;
StringRef Translated = Options.Translator(Dir);
Asm->OutStreamer.EmitBytes(Translated);
Asm->EmitInt8(0);
LineSectionSize += Translated.size() + 1;
}
Asm->EmitInt8(0);
LineSectionSize += 1;
while (const char *File = Data.getCStr(&Offset)) {
if (File[0] == 0)
break;
StringRef Translated = Options.Translator(File);
Asm->OutStreamer.EmitBytes(Translated);
Asm->EmitInt8(0);
LineSectionSize += Translated.size() + 1;
uint32_t OffsetBeforeLEBs = Offset;
Asm->EmitULEB128(Data.getULEB128(&Offset));
Asm->EmitULEB128(Data.getULEB128(&Offset));
Asm->EmitULEB128(Data.getULEB128(&Offset));
LineSectionSize += Offset - OffsetBeforeLEBs;
}
Asm->EmitInt8(0);
LineSectionSize += 1;
Asm->OutStreamer.EmitLabel(HeaderEndLabel);
Asm->OutStreamer.EmitBytes(Contents.slice(Offset, UnitEnd));
LineSectionSize += UnitEnd - Offset;
Asm->OutStreamer.EmitLabel(EndLabel);
Offset = UnitEnd;
}
void DwarfStreamer::copyInvariantDebugSection(const object::ObjectFile &Obj,
LinkOptions &Options) {
if (!Options.Translator) {
MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
emitSectionContents(Obj, "debug_line", MS);
}
MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
emitSectionContents(Obj, "debug_loc", MS);
MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
emitSectionContents(Obj, "debug_ranges", MS);
MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
emitSectionContents(Obj, "debug_frame", MS);
MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
emitSectionContents(Obj, "debug_aranges", MS);
if (!Options.Minimize && isa<object::MachOObjectFile>(Obj)) {
Asm->OutStreamer.SwitchSection(
MC->getMachOSection("__DWARF", "__debug_inlined", MachO::S_ATTR_DEBUG,
SectionKind::getMetadata()));
emitSectionContents(Obj, "debug_inlined", MS);
}
}
void DwarfStreamer::emitPubSectionForUnit(
const MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
const std::vector<CompileUnit::AccelInfo> &Names) {
if (Names.empty())
return;
Asm->OutStreamer.SwitchSection(Sec);
MCSymbol *BeginLabel =
Asm->GetTempSymbol("pub" + SecName + "_begin", Unit.getUniqueID());
MCSymbol *EndLabel =
Asm->GetTempSymbol("pub" + SecName + "_end", Unit.getUniqueID());
bool HeaderEmitted = false;
for (const auto &Name : Names) {
if (Name.SkipPubSection)
continue;
if (!HeaderEmitted) {
Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); Asm->OutStreamer.EmitLabel(BeginLabel);
Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); Asm->EmitInt32(Unit.getStartOffset()); Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); HeaderEmitted = true;
}
Asm->EmitInt32(Name.Die->getOffset());
Asm->OutStreamer.EmitBytes(
StringRef(Name.Name.data(), Name.Name.size() + 1));
}
if (!HeaderEmitted)
return;
Asm->EmitInt32(0); Asm->OutStreamer.EmitLabel(EndLabel);
}
void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
"names", Unit, Unit.getPubnames());
}
void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
"types", Unit, Unit.getPubtypes());
}
void DwarfStreamer::emitCIE(StringRef CIEBytes) {
MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
MS->EmitBytes(CIEBytes);
FrameSectionSize += CIEBytes.size();
}
void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
uint64_t Address, StringRef FDEBytes) {
MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
MS->EmitIntValue(CIEOffset, 4);
MS->EmitIntValue(Address, AddrSize);
MS->EmitBytes(FDEBytes);
FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
}
void DwarfStreamer::emitSwiftModule(StringRef Buffer) {
auto Section = MC->getMachOSection("__DWARF", "__swift_ast",
MachO::S_ATTR_DEBUG,
SectionKind::getMetadata());
auto &ObjectStreamer = *static_cast<MCObjectStreamer *>(MS);
MCSectionData &SectData =
ObjectStreamer.getAssembler().getOrCreateSectionData(*Section);
SectData.setAlignment(1<<5);
MS->SwitchSection(Section);
MS->EmitBytes(Buffer);
}
static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
DwarfAccelTable::Atom(5, dwarf::DW_FORM_data1),
DwarfAccelTable::Atom(6, dwarf::DW_FORM_data4)};
class DwarfLinker {
public:
DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
: OutputFilename(OutputFilename), Options(Options),
BinHolder(Options.Verbose), CurrentDebugObject(nullptr),
StringPool(Options.Translator),
AppleNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
dwarf::DW_FORM_data4),
true, true),
AppleNamespaces(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
dwarf::DW_FORM_data4),
true, true),
AppleTypes(TypeAtoms, true, true),
AppleObjc(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
dwarf::DW_FORM_data4),
true, true), LastCIEOffset(0) {}
~DwarfLinker() {
for (auto *Abbrev : Abbreviations)
delete Abbrev;
}
bool link(const DebugMap &);
private:
void startDebugObject(DWARFContext &, DebugMapObject &);
void endDebugObject();
const DebugMapObject &getCurrentDMO() const { return *CurrentDebugObject; }
class RelocationManager {
struct ValidReloc {
uint32_t Offset;
uint32_t Size;
uint64_t Addend;
const DebugMapObject::DebugMapEntry *Mapping;
bool FromDebugMap;
ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
const DebugMapObject::DebugMapEntry *Mapping,
bool FromDebugMap)
: Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping),
FromDebugMap(FromDebugMap) {}
bool operator<(const ValidReloc &RHS) const {
return Offset < RHS.Offset;
}
};
DwarfLinker &Linker;
std::vector<ValidReloc> ValidRelocs;
unsigned NextValidReloc;
public:
RelocationManager(DwarfLinker &Linker)
: Linker(Linker), NextValidReloc(0) {}
bool hasValidRelocs() const { return !ValidRelocs.empty(); }
void resetValidRelocs() { NextValidReloc = 0; }
bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
const DebugMapObject &DMO);
bool findValidRelocs(const object::SectionRef &Section,
const object::ObjectFile &Obj,
const DebugMapObject &DMO);
bool findValidRelocsMachO(const object::SectionRef &Section,
const object::MachOObjectFile &Obj,
const DebugMapObject &DMO);
bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
CompileUnit::DIEInfo &Info);
bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
bool isLittleEndian);
};
void lookForDIEsToKeep(RelocationManager &RelocMgr,
const DWARFDebugInfoEntryMinimal &DIE,
const DebugMapObject &DMO, CompileUnit &CU,
unsigned Flags);
bool registerModuleReference(const DWARFDebugInfoEntryMinimal &CUDie,
const DWARFUnit &Unit, DebugMap &ModuleMap,
unsigned Indent = 0);
void loadClangModule(StringRef Filename, StringRef ModulePath,
DebugMap &ModuleMap, unsigned Indent = 0);
ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
DebugMapObject &Obj,
const DebugMap &Map);
enum TravesalFlags {
TF_Keep = 1 << 0, TF_InFunctionScope = 1 << 1, TF_DependencyWalk = 1 << 2, TF_ParentWalk = 1 << 3, TF_SkipPC = 1 << 4, TF_ODR = 1 << 5, TF_SkipSubprograms = 1 << 6, };
void keepDIEAndDependencies(RelocationManager &RelocMgr,
const DWARFDebugInfoEntryMinimal &DIE,
CompileUnit::DIEInfo &MyInfo,
const DebugMapObject &DMO, CompileUnit &CU,
bool UseODR);
unsigned shouldKeepDIE(RelocationManager &RelocMgr,
const DWARFDebugInfoEntryMinimal &DIE,
CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
unsigned Flags);
unsigned shouldKeepVariableDIE(RelocationManager &RelocMgr,
const DWARFDebugInfoEntryMinimal &DIE,
CompileUnit &Unit,
CompileUnit::DIEInfo &MyInfo, unsigned Flags);
unsigned shouldKeepSubprogramDIE(RelocationManager &RelocMgr,
const DWARFDebugInfoEntryMinimal &DIE,
CompileUnit &Unit,
CompileUnit::DIEInfo &MyInfo,
unsigned Flags);
unsigned shouldKeepLabelDIE(RelocationManager &RelocMgr,
const DWARFDebugInfoEntryMinimal &DIE,
CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
unsigned Flags);
class DIECloner {
DwarfLinker &Linker;
RelocationManager &RelocMgr;
BumpPtrAllocator &DIEAlloc;
std::unique_ptr<DWARFAcceleratorTable> ExtTypes;
MutableArrayRef<CompileUnit> CompileUnits;
LinkOptions Options;
public:
DIECloner(DwarfLinker &Linker, RelocationManager &RelocMgr,
BumpPtrAllocator &DIEAlloc,
MutableArrayRef<CompileUnit> CompileUnits,
LinkOptions &Options)
: Linker(Linker), RelocMgr(RelocMgr), DIEAlloc(DIEAlloc),
CompileUnits(CompileUnits), Options(Options) {}
DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
int64_t PcOffset, uint32_t OutOffset, unsigned Flags);
void cloneAllCompileUnits(DWARFContextInMemory &DwarfContext);
private:
void addObjCAccelerator(CompileUnit &Unit, const DIE *Die, const char *Name,
bool SkipPubSection);
typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
struct AttributesInfo {
const char *Name, *MangledName; uint32_t NameOffset, MangledNameOffset;
uint64_t LowPc; uint64_t OrigLowPc; uint64_t OrigHighPc; int64_t PCOffset;
StringRef NameWithoutTemplate;
uint32_t NameWithoutTemplateOffset;
bool HasLowPc; bool IsDeclaration;
AttributesInfo()
: Name(nullptr), MangledName(nullptr), NameOffset(0),
MangledNameOffset(0), LowPc(0), OrigLowPc(UINT64_MAX),
OrigHighPc(0), PCOffset(0), HasLowPc(false), IsDeclaration(false) {}
};
unsigned cloneAttribute(DIE &Die,
const DWARFDebugInfoEntryMinimal &InputDIE,
CompileUnit &U, const DWARFFormValue &Val,
const AttributeSpec AttrSpec, unsigned AttrSize,
AttributesInfo &AttrInfo);
unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
const DWARFFormValue &Val, const DWARFUnit &U,
AttributesInfo &Info);
unsigned cloneExtTypeRef(DIE &Die,
const DWARFDebugInfoEntryMinimal &InputDIE,
AttributeSpec AttrSpec, const DWARFFormValue &Val,
const DWARFUnit &U, AttributesInfo &Info);
unsigned
cloneDieReferenceAttribute(DIE &Die,
const DWARFDebugInfoEntryMinimal &InputDIE,
AttributeSpec AttrSpec, unsigned AttrSize,
const DWARFFormValue &Val, CompileUnit &Unit);
unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
const DWARFFormValue &Val, unsigned AttrSize);
unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
const DWARFFormValue &Val, CompileUnit &Unit,
AttributesInfo &Info);
unsigned cloneScalarAttribute(DIE &Die,
const DWARFDebugInfoEntryMinimal &InputDIE,
CompileUnit &U, AttributeSpec AttrSpec,
const DWARFFormValue &Val, unsigned AttrSize,
AttributesInfo &Info);
bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
AttributesInfo &Info, bool StripTemplate = false);
void copyAbbrev(const DWARFAbbreviationDeclaration &Abbrev, bool hasODR);
uint32_t hashFullyQualifiedName(const DWARFDebugInfoEntryMinimal *DIE,
CompileUnit &U, int RecurseDepth = 0);
unsigned resolveExtType(StringRef UID, const DWARFUnit &U);
};
void AssignAbbrev(DIEAbbrev &Abbrev);
FoldingSet<DIEAbbrev> AbbreviationsSet;
std::vector<DIEAbbrev *> Abbreviations;
void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
void generateUnitRanges(CompileUnit &Unit) const;
void patchLineTableForUnit(CompileUnit &Unit, const DebugMapObject &DMO,
DWARFContext &OrigDwarf);
void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
std::vector<DIELoc *> DIELocs;
std::vector<DIEBlock *> DIEBlocks;
BumpPtrAllocator DIEAlloc;
public:
void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
bool createStreamer(Triple TheTriple, StringRef InputFileName,
StringRef OutputFileName);
protected:
void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
unsigned AddrSize);
uint64_t SizeUnit(CompileUnit *Unit);
private:
std::string OutputFilename;
LinkOptions Options;
BinaryHolder BinHolder;
std::unique_ptr<DwarfStreamer> Streamer;
uint64_t OutputDebugInfoSize = 0;
unsigned UnitID;
DenseMap<DIE *, DeclContext *> DIEToDeclContext;
SmallVector<CompileUnit, 1> Units;
DebugMapObject *CurrentDebugObject;
NonRelocatableStringpool StringPool;
std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
DeclContext RootDeclContext;
DeclContext::Map DeclContexts;
std::vector<DIE *> DIEsToDelete;
StringMap<uint32_t> EmittedCIEs;
DwarfAccelTable AppleNames;
DwarfAccelTable AppleNamespaces;
DwarfAccelTable AppleTypes;
DwarfAccelTable AppleObjc;
uint32_t LastCIEOffset;
typedef std::pair<uint32_t, uint32_t> InlinedKey;
typedef std::pair<uint32_t, uint64_t> InlinedEntry;
typedef std::map<InlinedKey, std::vector<InlinedEntry>> InlinedMap;
InlinedMap Inlined;
struct ClangModule {
std::unique_ptr<BinaryHolder> BinaryHolder;
std::unique_ptr<DWARFContext> DwarfContext;
std::unique_ptr<CompileUnit> Unit;
std::unique_ptr<DWARFAcceleratorTable> AppleTypes;
};
StringMap<ClangModule> ClangModules;
BumpPtrAllocator ModuleDIEAlloc;
};
}
static CompileUnit *getUnitForOffset(MutableArrayRef<CompileUnit> &Units,
unsigned Offset) {
auto CU =
std::upper_bound(Units.begin(), Units.end(), Offset,
[](uint32_t LHS, const CompileUnit &RHS) {
return LHS < RHS.getOrigUnit().getNextUnitOffset();
});
return CU != Units.end() ? &*CU : nullptr;
}
static const DWARFDebugInfoEntryMinimal *
resolveDIEReference(MutableArrayRef<CompileUnit> Units, uint64_t RefOffset,
const DWARFUnit &Unit,
const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU,
const DwarfLinker &Linker) {
if ((RefCU = getUnitForOffset(Units, RefOffset)))
if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
return RefDie;
Linker.reportWarning("could not find referenced DIE", &Unit, &DIE);
return nullptr;
}
static const DWARFDebugInfoEntryMinimal *
resolveDIEReference(MutableArrayRef<CompileUnit> Units,
const DWARFFormValue &RefValue, const DWARFUnit &Unit,
const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU,
const DwarfLinker &Linker) {
assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
uint64_t RefOffset = *RefValue.getAsReference(&Unit);
return resolveDIEReference(Units, RefOffset, Unit, DIE, RefCU, Linker);
}
static std::pair<DeclContext *, DeclContext *>
updateDeclContext(DeclContext *Context,
const DWARFDebugInfoEntryMinimal *DIE,
CompileUnit &U,
NonRelocatableStringpool &StringPool,
DeclContext::Map &Contexts) {
if (!Context)
return std::make_pair(nullptr, nullptr);
switch (DIE->getTag()) {
default:
return std::make_pair(nullptr, nullptr);
case dwarf::DW_TAG_compile_unit:
return std::make_pair(Context, Context);
case dwarf::DW_TAG_subprogram:
if ((Context->getTag() == dwarf::DW_TAG_namespace ||
Context->getTag() == dwarf::DW_TAG_compile_unit) &&
!DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
dwarf::DW_AT_external, 0))
return std::make_pair(nullptr, nullptr);
case dwarf::DW_TAG_member:
case dwarf::DW_TAG_namespace:
case dwarf::DW_TAG_structure_type:
case dwarf::DW_TAG_class_type:
case dwarf::DW_TAG_union_type:
case dwarf::DW_TAG_enumeration_type:
case dwarf::DW_TAG_typedef:
case dwarf::DW_TAG_base_type:
case dwarf::DW_TAG_pointer_type:
case dwarf::DW_TAG_unspecified_type:
if (DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
dwarf::DW_AT_artificial, 0))
return std::make_pair(nullptr, nullptr);
break;
}
const char *Name = DIE->getName(&U.getOrigUnit(), DINameKind::LinkageName);
const char *ShortName = DIE->getName(&U.getOrigUnit(), DINameKind::ShortName);
StringRef NameRef;
StringRef ShortNameRef;
StringRef FileRef;
if (Name)
NameRef = StringPool.internString(Name);
else if (DIE->getTag() == dwarf::DW_TAG_namespace)
NameRef = StringPool.internString("(anonymous namespace)");
if (ShortName && ShortName != Name)
ShortNameRef = StringPool.internString(ShortName);
else
ShortNameRef = NameRef;
if (DIE->getTag() != dwarf::DW_TAG_class_type &&
DIE->getTag() != dwarf::DW_TAG_structure_type &&
DIE->getTag() != dwarf::DW_TAG_union_type &&
DIE->getTag() != dwarf::DW_TAG_enumeration_type && NameRef.empty())
return std::make_pair(nullptr, nullptr);
std::string File;
unsigned Line = 0;
unsigned ByteSize = 0;
if (U.hasODR()) {
ByteSize = DIE->getAttributeValueAsUnsignedConstant(
&U.getOrigUnit(), dwarf::DW_AT_byte_size, UINT64_MAX);
if (DIE->getTag() != dwarf::DW_TAG_namespace || !Name) {
if (unsigned FileNum = DIE->getAttributeValueAsUnsignedConstant(
&U.getOrigUnit(), dwarf::DW_AT_decl_file, 0))
if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
&U.getOrigUnit())) {
if (!Name && DIE->getTag() == dwarf::DW_TAG_namespace)
FileNum = 1;
if (LT->getFileNameByIndex(
FileNum, "",
DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
File)) {
Line = DIE->getAttributeValueAsUnsignedConstant(
&U.getOrigUnit(), dwarf::DW_AT_decl_line, 0);
#ifdef HAVE_REALPATH
if (const char *ResolvedPath = U.getResolvedPath(FileNum)) {
File = ResolvedPath;
} else {
char RealPath[PATH_MAX + 1];
RealPath[PATH_MAX] = 0;
if (::realpath(File.c_str(), RealPath))
File = RealPath;
U.setResolvedPath(FileNum, File);
}
#endif
FileRef = StringPool.internString(File);
}
}
}
}
if (Line || !NameRef.empty()) {
auto Res =
Context->getChild(Contexts, ShortNameRef, NameRef, FileRef, Line,
ByteSize, DIE->getTag(), U);
if (!Res.first)
return Res;
if ((DIE->getTag() == dwarf::DW_TAG_member ||
DIE->getTag() == dwarf::DW_TAG_subprogram) &&
Context->getTag() != dwarf::DW_TAG_structure_type &&
Context->getTag() != dwarf::DW_TAG_class_type)
Res.first->invalidate();
if (DIE->getTag() == dwarf::DW_TAG_union_type ||
DIE->getTag() == dwarf::DW_TAG_base_type ||
DIE->getTag() == dwarf::DW_TAG_pointer_type ||
DIE->getTag() == dwarf::DW_TAG_unspecified_type)
Res.first->invalidate();
return Res;
}
return std::make_pair(nullptr, nullptr);
}
void DeclContext::resetLastSeen(CompileUnit &U) {
DWARFUnit &OrigUnit = U.getOrigUnit();
uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
U.getInfo(FirstIdx).Ctxt = nullptr;
}
static bool isODRAttribute(uint16_t Attr) {
switch (Attr) {
default:
return false;
case dwarf::DW_AT_type:
case dwarf::DW_AT_containing_type:
case dwarf::DW_AT_specification:
case dwarf::DW_AT_abstract_origin:
case dwarf::DW_AT_import:
return true;
}
llvm_unreachable("Improper attribute.");
}
std::pair<DeclContext *, DeclContext *>
DeclContext::getChild(DeclContext::Map &Contexts, StringRef ShortName,
StringRef Name, StringRef File, unsigned Line,
unsigned ByteSize, uint16_t Tag, CompileUnit &U) {
uint32_t Hash = QualifiedNameHash;
Hash += Tag;
if (Parent)
Hash = DwarfAccelTable::HashDJB("::", Hash);
Hash = DwarfAccelTable::HashDJB( Name, Hash);
if (Tag == dwarf::DW_TAG_namespace && Name == "(anonymous namespace)")
Hash = DwarfAccelTable::HashDJB(File, Hash);
DeclContext *&Res = Contexts[Hash];
DeclContext *Ctxt = Res;
while (Ctxt &&
(Ctxt->Parent->QualifiedNameHash != QualifiedNameHash ||
Ctxt->Line != Line || Ctxt->ByteSize != ByteSize ||
Ctxt->Name.data() != Name.data() || Ctxt->File.data() != File.data()))
Ctxt = Ctxt->Collision;
if (!Ctxt) {
Ctxt = new DeclContext(Name, Hash, this, File, Line, ByteSize, Tag,
U.getUniqueID());
Ctxt->Collision = Res;
Res = Ctxt;
} else if (Ctxt->LastSeenCompileUnitID == U.getUniqueID() &&
Tag != dwarf::DW_TAG_namespace) {
Ctxt->resetLastSeen(U);
return std::make_pair(nullptr, Ctxt);
}
Ctxt->LastSeenCompileUnitID = U.getUniqueID();
return std::make_pair(Ctxt, Ctxt);
}
bool DwarfLinker::DIECloner::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
DWARFUnit &U, AttributesInfo &Info,
bool StripTemplate) {
bool GetNameOffset = false;
if (!Info.MangledName &&
(Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
std::tie(Info.MangledName, Info.MangledNameOffset) =
Linker.StringPool.getStringAndOffset(Info.MangledName);
if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName))) {
Info.Name = Linker.StringPool.internString(Info.Name).data();
GetNameOffset = true;
}
if (StripTemplate) {
if (Info.Name && Info.MangledName != Info.Name)
if (char *LessThan = strchr(Info.Name, '<')) {
Info.NameWithoutTemplate = StringRef(Info.Name, LessThan - Info.Name);
Info.NameWithoutTemplate =
Linker.StringPool.internString(Info.NameWithoutTemplate);
Info.NameWithoutTemplateOffset =
Linker.StringPool.getStringOffset(Info.NameWithoutTemplate);
}
}
if (GetNameOffset)
std::tie(Info.Name, Info.NameOffset) =
Linker.StringPool.getStringAndOffset(Info.Name);
return Info.Name || Info.MangledName;
}
void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
const DWARFDebugInfoEntryMinimal *DIE) const {
StringRef Context = "<debug map>";
if (CurrentDebugObject)
Context = CurrentDebugObject->getObjectFilename();
warn(Warning, Context);
if (!Options.Verbose || !DIE)
return;
errs() << " in DIE:\n";
DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 ,
6 );
}
bool DwarfLinker::createStreamer(Triple TheTriple, StringRef InputFilename,
StringRef OutputFilename) {
if (Options.NoOutput)
return true;
Streamer = make_unique<DwarfStreamer>();
return Streamer->init(TheTriple, OutputFilename, Options.Minimize);
}
static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
unsigned ParentIdx, CompileUnit &CU,
DeclContext *CurrentDeclContext,
NonRelocatableStringpool &StringPool,
DeclContext::Map &Contexts) {
unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
Info.ParentIdx = ParentIdx;
if (CU.hasODR()) {
auto Ctxt = updateDeclContext(CurrentDeclContext, DIE, CU, StringPool, Contexts);
if (Ctxt.first && Ctxt.first != CurrentDeclContext)
Ctxt.first->setLastSeenDIE(DIE);
Info.Ctxt = Ctxt.first;
CurrentDeclContext = Ctxt.second;
}
if (DIE->hasChildren())
for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
Child = Child->getSibling())
gatherDIEParents(Child, MyIdx, CU, CurrentDeclContext, StringPool,
Contexts);
}
static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
switch (Tag) {
default:
return false;
case dwarf::DW_TAG_subprogram:
case dwarf::DW_TAG_lexical_block:
case dwarf::DW_TAG_subroutine_type:
case dwarf::DW_TAG_structure_type:
case dwarf::DW_TAG_class_type:
case dwarf::DW_TAG_union_type:
return true;
}
llvm_unreachable("Invalid Tag");
}
void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Units.reserve(Dwarf.getNumCompileUnits());
for (const auto &Entry : Obj.symbols()) {
const auto &Mapping = Entry.getValue();
if (Mapping.Size && !Mapping.FromAnotherObjectFile)
Ranges[Mapping.ObjectAddress] = std::make_pair(
Mapping.ObjectAddress + Mapping.Size,
int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
}
}
void DwarfLinker::endDebugObject() {
Units.clear();
Ranges.clear();
DIEBlocks.clear();
DIELocs.clear();
DIEAlloc.Reset();
}
bool DwarfLinker::RelocationManager::findValidRelocsMachO(
const object::SectionRef &Section, const object::MachOObjectFile &Obj,
const DebugMapObject &DMO) {
StringRef Contents;
Section.getContents(Contents);
DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
bool FoundInterstingReloc = false;
for (const object::RelocationRef &Reloc : Section.relocations()) {
object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
uint64_t Offset64;
if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
Linker.reportWarning(" unsupported relocation in debug_info section.");
continue;
}
uint32_t Offset = Offset64;
uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
auto Sym = Reloc.getSymbol();
auto Section = Obj.getRelocationSection(Obj.getRelocation(Reloc.getRawDataRefImpl()));
StringRef SecName;
if (object::section_iterator(Section) != Obj.section_end())
Section.getName(SecName);
if (Sym != Obj.symbol_end()) {
StringRef SymbolName;
if (Sym->getName(SymbolName)) {
Linker.reportWarning("error getting relocation symbol name.");
continue;
}
if (const auto *Mapping = DMO.lookupSymbol(SymbolName)) {
if (Mapping->getValue().BinaryAddress == object::UnknownAddressOrSize)
continue;
ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping,
!Mapping->getValue().FromAnotherObjectFile);
FoundInterstingReloc |= !Mapping->getValue().FromAnotherObjectFile;
}
} else if (const auto *Mapping = DMO.lookupObjectAddress(Addend, SecName)) {
if (Mapping->getValue().BinaryAddress == object::UnknownAddressOrSize)
continue;
if (Mapping->getValue().ObjectAddress == Addend) {
ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping,
!Mapping->getValue().FromAnotherObjectFile);
FoundInterstingReloc |= !Mapping->getValue().FromAnotherObjectFile;
} else {
ValidRelocs.emplace_back(Offset64, RelocSize,
Addend - Mapping->getValue().ObjectAddress,
Mapping, false);
}
}
}
return FoundInterstingReloc;
}
bool DwarfLinker::RelocationManager::findValidRelocs(
const object::SectionRef &Section, const object::ObjectFile &Obj,
const DebugMapObject &DMO) {
bool FoundInterestingReloc = false;
if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
FoundInterestingReloc = findValidRelocsMachO(Section, *MachOObj, DMO);
else
Linker.reportWarning(Twine("unsupported object file type: ") +
Obj.getFileName());
if (!FoundInterestingReloc)
return false;
std::sort(ValidRelocs.begin(), ValidRelocs.end());
return true;
}
bool DwarfLinker::RelocationManager::findValidRelocsInDebugInfo(
const object::ObjectFile &Obj, const DebugMapObject &DMO) {
Optional<object::SectionRef> Section = getSectionByName(Obj, "debug_info");
if (Section)
return findValidRelocs(*Section, Obj, DMO);
return false;
}
bool DwarfLinker::RelocationManager::hasValidRelocation(
uint32_t StartOffset, uint32_t EndOffset, CompileUnit::DIEInfo &Info) {
assert(NextValidReloc == 0 ||
StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
if (NextValidReloc >= ValidRelocs.size())
return false;
uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
RelocOffset = ValidRelocs[++NextValidReloc].Offset;
if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
return false;
const auto &ValidReloc = ValidRelocs[NextValidReloc++];
if (!ValidReloc.FromDebugMap)
return false;
if (Linker.Options.Verbose)
outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
<< " "
<< format("\t%016" PRIx64 " => %016" PRIx64,
uint64_t(ValidReloc.Mapping->getValue().ObjectAddress),
uint64_t(ValidReloc.Mapping->getValue().BinaryAddress));
Info.AddrAdjust = int64_t(ValidReloc.Mapping->getValue().BinaryAddress) +
ValidReloc.Addend -
ValidReloc.Mapping->getValue().ObjectAddress;
Info.InDebugMap = true;
return true;
}
static std::pair<uint32_t, uint32_t>
getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
unsigned Offset, const DWARFUnit &Unit) {
DataExtractor Data = Unit.getDebugInfoExtractor();
for (unsigned i = 0; i < Idx; ++i)
DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
uint32_t End = Offset;
DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
return std::make_pair(Offset, End);
}
unsigned DwarfLinker::shouldKeepVariableDIE(
RelocationManager &RelocMgr, const DWARFDebugInfoEntryMinimal &DIE,
CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
if (!(Flags & TF_InFunctionScope) &&
Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
MyInfo.InDebugMap = true;
return Flags | TF_Keep;
}
uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
if (LocationIdx == -1U)
return Flags;
uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
const DWARFUnit &OrigUnit = Unit.getOrigUnit();
uint32_t LocationOffset, LocationEndOffset;
std::tie(LocationOffset, LocationEndOffset) =
getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
LocationEndOffset = LocationOffset;
DWARFFormValue Value(Abbrev->getFormByIndex(LocationIdx));
if ((!Value.isFormClass(DWARFFormValue::FC_Block) &&
!Value.isFormClass(DWARFFormValue::FC_Exprloc)) ||
!Value.extractValue(OrigUnit.getDebugInfoExtractor(), &LocationEndOffset,
&OrigUnit))
return Flags;
auto Loc = *Value.getAsBlock();
if ((Loc.size() == 10 && Loc[0] == dwarf::DW_OP_const8u &&
Loc[9] == dwarf::DW_OP_GNU_push_tls_address) ||
(Loc.size() == 6 && Loc[0] == dwarf::DW_OP_const4u &&
Loc[5] == dwarf::DW_OP_GNU_push_tls_address))
return Flags;
if (!RelocMgr.hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
(Flags & TF_InFunctionScope))
return Flags;
if (Options.Verbose)
DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 );
Unit.setHasInterestingContent();
return Flags | TF_Keep;
}
unsigned DwarfLinker::shouldKeepSubprogramDIE(
RelocationManager &RelocMgr, const DWARFDebugInfoEntryMinimal &DIE,
CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
Flags |= TF_InFunctionScope;
uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
if (LowPcIdx == -1U)
return Flags;
uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
DWARFUnit &OrigUnit = Unit.getOrigUnit();
uint32_t LowPcOffset, LowPcEndOffset;
std::tie(LowPcOffset, LowPcEndOffset) =
getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
uint64_t LowPc =
DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
assert(LowPc != -1ULL && "low_pc attribute is not an address.");
if (LowPc == -1ULL ||
!RelocMgr.hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
return Flags;
if (Options.Verbose)
DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 );
if (DIE.getTag() == dwarf::DW_TAG_label) {
if (Unit.hasLabelAt(LowPc))
return Flags;
if (OrigUnit.getCompileUnitDIE()->getAttributeValueAsAddress(&OrigUnit,
dwarf::DW_AT_high_pc,
UINT64_MAX) <= LowPc)
return Flags;
Unit.setHasInterestingContent();
Unit.addLabelLowPc(LowPc, MyInfo.AddrAdjust);
return Flags | TF_Keep;
}
Unit.setHasInterestingContent();
Flags |= TF_Keep;
DWARFFormValue HighPcValue;
if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
reportWarning("Function without high_pc. Range will be discarded.\n",
&OrigUnit, &DIE);
return Flags;
}
uint64_t HighPc;
if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
HighPc = *HighPcValue.getAsAddress(&OrigUnit);
} else {
assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
}
Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
return Flags;
}
unsigned DwarfLinker::shouldKeepDIE(RelocationManager &RelocMgr,
const DWARFDebugInfoEntryMinimal &DIE,
CompileUnit &Unit,
CompileUnit::DIEInfo &MyInfo,
unsigned Flags) {
switch (DIE.getTag()) {
case dwarf::DW_TAG_constant:
case dwarf::DW_TAG_variable:
return shouldKeepVariableDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
case dwarf::DW_TAG_label:
case dwarf::DW_TAG_subprogram:
return shouldKeepSubprogramDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
case dwarf::DW_TAG_module:
case dwarf::DW_TAG_imported_module:
case dwarf::DW_TAG_imported_declaration:
case dwarf::DW_TAG_imported_unit:
return Flags | TF_Keep;
}
return Flags;
}
void DwarfLinker::keepDIEAndDependencies(RelocationManager &RelocMgr,
const DWARFDebugInfoEntryMinimal &DIE,
CompileUnit::DIEInfo &MyInfo,
const DebugMapObject &DMO,
CompileUnit &CU, bool UseODR) {
const DWARFUnit &Unit = CU.getOrigUnit();
MyInfo.Keep = true;
unsigned AncestorIdx = MyInfo.ParentIdx;
while (!CU.getInfo(AncestorIdx).Keep) {
unsigned ODRFlag = UseODR ? TF_ODR : 0;
lookForDIEsToKeep(RelocMgr, *Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
}
DataExtractor Data = Unit.getDebugInfoExtractor();
const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
for (const auto &AttrSpec : Abbrev->attributes()) {
DWARFFormValue Val(AttrSpec.Form);
if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
continue;
}
Val.extractValue(Data, &Offset, &Unit);
CompileUnit *ReferencedCU;
if (const auto *RefDIE =
resolveDIEReference(Units, Val, Unit, DIE, ReferencedCU, *this)) {
uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
Info.Ctxt->getCanonicalDIEOffset() && Info.Ctxt->isValid() &&
isODRAttribute(AttrSpec.Attr))
continue;
unsigned ODRFlag = UseODR ? TF_ODR : 0;
lookForDIEsToKeep(RelocMgr, *RefDIE, DMO, *ReferencedCU,
TF_Keep | TF_DependencyWalk | ODRFlag);
}
}
}
void DwarfLinker::lookForDIEsToKeep(RelocationManager &RelocMgr,
const DWARFDebugInfoEntryMinimal &DIE,
const DebugMapObject &DMO, CompileUnit &CU,
unsigned Flags) {
unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
bool AlreadyKept = MyInfo.Keep;
if (153508 == DIE.getOffset())
(void)"SDFsdfsdfsdfsdfsdf";
if (Flags & TF_DependencyWalk) {
if (AlreadyKept)
return;
}
if (Flags & TF_SkipSubprograms) {
if (DIE.getTag() == dwarf::DW_TAG_subprogram &&
!DIE.getAttributeValueAsUnsignedConstant(&CU.getOrigUnit(),
dwarf::DW_AT_declaration, 0))
return;
Flags &= ~TF_SkipSubprograms;
}
if (!(Flags & TF_DependencyWalk))
Flags = shouldKeepDIE(RelocMgr, DIE, CU, MyInfo, Flags);
if (!AlreadyKept && (Flags & TF_Keep)) {
bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
keepDIEAndDependencies(RelocMgr, DIE, MyInfo, DMO, CU, UseOdr);
}
if (dieNeedsChildrenToBeMeaningful(DIE.getTag())) {
if (Flags & TF_ParentWalk &&
(DIE.getTag() == dwarf::DW_TAG_structure_type ||
DIE.getTag() == dwarf::DW_TAG_class_type ||
DIE.getTag() == dwarf::DW_TAG_union_type))
Flags |= TF_SkipSubprograms;
Flags &= ~TF_ParentWalk;
}
if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
return;
for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
Child = Child->getSibling())
lookForDIEsToKeep(RelocMgr, *Child, DMO, CU, Flags);
}
void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
FoldingSetNodeID ID;
Abbrev.Profile(ID);
void *InsertToken;
DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
if (InSet) {
Abbrev.setNumber(InSet->getNumber());
} else {
Abbreviations.push_back(
new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
for (const auto &Attr : Abbrev.getData())
Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
Abbrev.setNumber(Abbreviations.size());
Abbreviations.back()->setNumber(Abbreviations.size());
}
}
unsigned DwarfLinker::DIECloner::cloneStringAttribute(DIE &Die,
AttributeSpec AttrSpec,
const DWARFFormValue &Val,
const DWARFUnit &U,
AttributesInfo &Info) {
const char *String = *Val.getAsCString(&U);
if (AttrSpec.Form == dwarf::DW_FORM_string)
String = Linker.StringPool.internString(String).data();
if (AttrSpec.Form == dwarf::DW_FORM_strp || strlen(String) >= 3) {
unsigned Offset;
std::tie(String, Offset) = Linker.StringPool.getStringAndOffset(String);
if (AttrSpec.Attr == dwarf::DW_AT_name) {
Info.Name = String;
Info.NameOffset = Offset;
} else if (AttrSpec.Attr == dwarf::DW_AT_MIPS_linkage_name ||
AttrSpec.Attr == dwarf::DW_AT_linkage_name) {
Info.MangledName = String;
Info.MangledNameOffset = Offset;
}
Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
new (DIEAlloc) DIEInteger(Offset), &Linker.DIEsToDelete);
return 4;
} else {
assert(AttrSpec.Form == dwarf::DW_FORM_string);
DIEBlock *StringBlock = new (DIEAlloc) DIEBlock();
unsigned Length = 0;
Linker.DIEBlocks.push_back(StringBlock);
while (*String) {
StringBlock->addValue(dwarf::Attribute(0), dwarf::DW_FORM_data1,
new (DIEAlloc) DIEInteger(*String++));
++Length;
}
StringBlock->addValue(dwarf::Attribute(0), dwarf::DW_FORM_data1,
new (DIEAlloc) DIEInteger(0));
Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_string,
StringBlock, &Linker.DIEsToDelete);
return Length + 1;
}
}
static unsigned AccelLookupData4(DWARFAcceleratorTable Accel, StringRef Key) {
auto Entry = Accel.find(Key);
if (Entry != Accel.end())
for (auto Data : *Entry)
return *Data.getAsSignedConstant();
return -1U;
}
unsigned DwarfLinker::DIECloner::resolveExtType(StringRef UID,
const DWARFUnit &U) {
bool Verbose = Linker.Options.Verbose;
if (Verbose)
outs() << "Looking up " << UID << " in .apple_exttypes\n";
unsigned ModuleStr = AccelLookupData4(*ExtTypes, UID);
if (ModuleStr != -1U) {
if (const char *ModuleFile = U.getStringExtractor().getCStr(&ModuleStr)) {
if (Verbose)
outs() << " Looking up " << UID << " in " << ModuleFile << " ... ";
auto Module = Linker.ClangModules.find(ModuleFile);
if (Module != Linker.ClangModules.end()) {
unsigned Offset = AccelLookupData4(*Module->second.AppleTypes, UID);
if (Offset != -1U) {
auto &RefUnit = *Module->second.Unit;
if (auto RefDie = RefUnit.getOrigUnit().getDIEForOffset(Offset)) {
unsigned Idx = RefUnit.getOrigUnit().getDIEIndex(RefDie);
auto &RefInfo = RefUnit.getInfo(Idx);
if (RefInfo.Clone) {
unsigned CloneOffset = RefInfo.Clone->getOffset();
if (Verbose)
outs() << "found at offset " << CloneOffset << ".\n";
return CloneOffset + RefUnit.getStartOffset();
} else {
if (Verbose)
outs() << "Could not find cloned DIE.\n";
assert(false && "DIE not cloned");
}
} else if (Verbose)
outs() << "No index entry for type " << UID << " in " << ModuleFile
<< ".\n";
} else if (Verbose)
outs() << "Could not find type " << UID << " in " << ModuleFile
<< ".\n";
} else {
if (Verbose)
outs() << "Clang module " << ModuleFile << " was not imported.\n";
return 0;
}
} else if (Verbose)
outs() << "Could not find clang module string.\n";
} else if (Verbose)
outs() << "Could not find external type " << UID
<< " in .apple_exttypes.\n";
assert(false && "Unresolved external type reference. Corrupt DWARF input?");
return 0;
}
static unsigned getRefAddrSize(const DwarfStreamer &Streamer,
const DWARFUnit &U) {
return Streamer.getAsmPrinter().OutStreamer.getContext().getDwarfVersion() ==
2
? U.getAddressByteSize()
: 4;
}
unsigned DwarfLinker::DIECloner::cloneExtTypeRef(
DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
AttributeSpec AttrSpec, const DWARFFormValue &Val, const DWARFUnit &U,
AttributesInfo &Info) {
StringRef UID(*Val.getAsCString(&U));
if (unsigned Offset = resolveExtType(UID, U)) {
Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
new (DIEAlloc) DIEInteger(Offset), &Linker.DIEsToDelete);
return getRefAddrSize(*Linker.Streamer, U);
} else {
Linker.reportWarning(Twine("Could not resolve external type ") + UID, &U,
&InputDIE);
return 0;
}
}
unsigned DwarfLinker::DIECloner::cloneDieReferenceAttribute(
DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
CompileUnit &Unit) {
const DWARFUnit &U = Unit.getOrigUnit();
uint32_t Ref = *Val.getAsReference(&U);
DIE *NewRefDie = nullptr;
CompileUnit *RefUnit = nullptr;
const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
DeclContext *Ctxt = nullptr;
if (AttrSpec.Attr == dwarf::DW_AT_signature) {
Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
new (DIEAlloc) DIEInteger(*Val.getAsReference(&U)),
&Linker.DIEsToDelete);
return AttrSize;
}
if ( isODRAttribute(AttrSpec.Attr)) {
const auto *Type =
resolveDIEReference(CompileUnits, Val, U, InputDIE, RefUnit, Linker);
assert(Type);
auto &TypeInfo = RefUnit->getInfo(RefUnit->getOrigUnit().getDIEIndex(Type));
if (TypeInfo.Ctxt && TypeInfo.Ctxt->isValid()) {
if (uint32_t TypeOffset = TypeInfo.Ctxt->getCanonicalDIEOffset()) {
DIEInteger *Attr = new (DIEAlloc) DIEInteger(TypeOffset);
Die.addValue((dwarf::Attribute)AttrSpec.Attr, dwarf::DW_FORM_ref_addr,
Attr, &Linker.DIEsToDelete);
return getRefAddrSize(*Linker.Streamer, U);
}
Ctxt = TypeInfo.Ctxt;
}
}
if (!(RefUnit = getUnitForOffset(CompileUnits, Ref)) ||
!(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
if (!AttributeString)
AttributeString = "DW_AT_???";
Linker.reportWarning(Twine("Missing DIE for ref in attribute ") +
AttributeString + ". Dropping.",
&U, &InputDIE);
return 0;
}
unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
if (!RefInfo.Clone) {
assert(Ref > InputDIE.getOffset());
RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
}
NewRefDie = RefInfo.Clone;
if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
(Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
DIEInteger *Attr;
if (Ref < InputDIE.getOffset()) {
uint32_t NewRefOffset =
RefUnit->getStartOffset() + NewRefDie->getOffset();
Attr = new (DIEAlloc) DIEInteger(NewRefOffset);
} else {
Attr = new (DIEAlloc) DIEInteger(0xBADDEF);
Unit.noteForwardReference(NewRefDie, RefUnit, Ctxt, Attr);
}
Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr, Attr,
&Linker.DIEsToDelete);
return getRefAddrSize(*Linker.Streamer, U);
}
Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
new (DIEAlloc) DIEEntry(*NewRefDie), &Linker.DIEsToDelete);
return AttrSize;
}
unsigned DwarfLinker::DIECloner::cloneBlockAttribute(DIE &Die,
AttributeSpec AttrSpec,
const DWARFFormValue &Val,
unsigned AttrSize) {
DIE *Attr;
DIEValue *Value;
DIELoc *Loc = nullptr;
DIEBlock *Block = nullptr;
if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Loc = new (DIEAlloc) DIELoc();
Linker.DIELocs.push_back(Loc);
} else {
Block = new (DIEAlloc) DIEBlock();
Linker.DIEBlocks.push_back(Block);
}
Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
Value = Loc ? static_cast<DIEValue *>(Loc) : static_cast<DIEValue *>(Block);
ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
for (auto Byte : Bytes)
Attr->addValue(dwarf::Attribute(0), dwarf::DW_FORM_data1,
new (DIEAlloc) DIEInteger(Byte), &Linker.DIEsToDelete);
if (Linker.Streamer) {
if (Loc)
Loc->ComputeSize(&Linker.Streamer->getAsmPrinter());
else
Block->ComputeSize(&Linker.Streamer->getAsmPrinter());
}
Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Value, &Linker.DIEsToDelete);
return AttrSize;
}
unsigned DwarfLinker::DIECloner::cloneAddressAttribute(
DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
CompileUnit &Unit, AttributesInfo &Info) {
uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
if (LLVM_UNLIKELY(Linker.Options.Update)) {
if (AttrSpec.Attr == dwarf::DW_AT_low_pc)
Info.HasLowPc = true;
Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
new (DIEAlloc) DIEInteger(Addr), &Linker.DIEsToDelete);
return Unit.getOrigUnit().getAddressByteSize();
}
if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
if (Die.getTag() == dwarf::DW_TAG_subprogram ||
Die.getTag() == dwarf::DW_TAG_label)
; else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
Addr = Unit.getLowPc() == UINT64_MAX
? (Info.OrigLowPc != UINT64_MAX ? Info.OrigLowPc : Addr)
: Unit.getLowPc();
} else
Addr = (Info.OrigLowPc != UINT64_MAX ? Info.OrigLowPc : Addr) +
Info.PCOffset;
Info.HasLowPc = true;
Info.LowPc = Addr;
} else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
if (Die.getTag() == dwarf::DW_TAG_compile_unit)
Addr = Unit.getHighPc() ? Unit.getHighPc()
: (Info.OrigHighPc ? Info.OrigHighPc : Addr);
else
Addr = (Info.OrigLowPc != UINT64_MAX? Info.OrigHighPc : Addr) + Info.PCOffset;
}
Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
new (DIEAlloc) DIEInteger(Addr), &Linker.DIEsToDelete);
return Unit.getOrigUnit().getAddressByteSize();
}
unsigned DwarfLinker::DIECloner::cloneScalarAttribute(
DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
AttributesInfo &Info) {
uint64_t Value;
if (LLVM_UNLIKELY(Linker.Options.Update)) {
if (auto OptionalValue = Val.getAsUnsignedConstant())
Value = *OptionalValue;
else if (auto OptionalValue = Val.getAsSignedConstant())
Value = *OptionalValue;
else if (auto OptionalValue = Val.getAsSectionOffset())
Value = *OptionalValue;
else {
Linker.reportWarning(
"Unsupported scalar attribute form. Dropping attribute.",
&Unit.getOrigUnit(), &InputDIE);
return 0;
}
if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
Info.IsDeclaration = true;
Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
new (DIEAlloc) DIEInteger(Value), &Linker.DIEsToDelete);
return AttrSize;
}
if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
Die.getTag() == dwarf::DW_TAG_compile_unit) {
if (Unit.getLowPc() == -1ULL)
return 0;
Value = Unit.getHighPc() - Unit.getLowPc();
} else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Value = *Val.getAsSectionOffset();
else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
Value = *Val.getAsSignedConstant();
else if (auto OptionalValue = Val.getAsUnsignedConstant())
Value = *OptionalValue;
else {
Linker.reportWarning(
"Unsupported scalar attribute form. Dropping attribute.",
&Unit.getOrigUnit(), &InputDIE);
return 0;
}
DIEInteger *Attr = new (DIEAlloc) DIEInteger(Value);
if (AttrSpec.Attr == dwarf::DW_AT_ranges)
Unit.noteRangeAttribute(Die, Attr);
else if (AttrSpec.Attr == dwarf::DW_AT_location ||
AttrSpec.Attr == dwarf::DW_AT_frame_base)
Unit.noteLocationAttribute(Attr, Info.PCOffset);
else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
Info.IsDeclaration = true;
Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Attr, &Linker.DIEsToDelete);
return AttrSize;
}
unsigned DwarfLinker::DIECloner::cloneAttribute(
DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
const DWARFFormValue &Val, const AttributeSpec AttrSpec, unsigned AttrSize,
AttributesInfo &Info) {
const DWARFUnit &U = Unit.getOrigUnit();
switch (AttrSpec.Form) {
case dwarf::DW_FORM_strp:
if (AttrSpec.Attr == dwarf::DW_AT_type ||
AttrSpec.Attr == dwarf::DW_AT_specification ||
AttrSpec.Attr == dwarf::DW_AT_import ||
AttrSpec.Attr == dwarf::DW_AT_friend)
return cloneExtTypeRef(
Die, InputDIE,
AttributeSpec(AttrSpec.Attr, dwarf::DW_FORM_ref_addr),
Val, U, Info);
case dwarf::DW_FORM_string:
return cloneStringAttribute(Die, AttrSpec, Val, U, Info);
case dwarf::DW_FORM_ref_addr:
case dwarf::DW_FORM_ref1:
case dwarf::DW_FORM_ref2:
case dwarf::DW_FORM_ref4:
case dwarf::DW_FORM_ref8:
case dwarf::DW_FORM_ref_sig8:
return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Unit);
case dwarf::DW_FORM_block:
case dwarf::DW_FORM_block1:
case dwarf::DW_FORM_block2:
case dwarf::DW_FORM_block4:
case dwarf::DW_FORM_exprloc:
return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
case dwarf::DW_FORM_addr:
return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
case dwarf::DW_FORM_data1:
case dwarf::DW_FORM_data2:
case dwarf::DW_FORM_data4:
case dwarf::DW_FORM_data8:
case dwarf::DW_FORM_udata:
case dwarf::DW_FORM_sdata:
case dwarf::DW_FORM_sec_offset:
case dwarf::DW_FORM_flag:
case dwarf::DW_FORM_flag_present:
return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
Info);
default:
Linker.reportWarning(
"Unsupported attribute form in cloneAttribute. Dropping.", &U,
&InputDIE);
}
return 0;
}
bool DwarfLinker::RelocationManager::applyValidRelocs(
MutableArrayRef<char> Data, uint32_t BaseOffset, bool isLittleEndian) {
assert((NextValidReloc == 0 ||
BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
"BaseOffset should only be increasing.");
if (NextValidReloc >= ValidRelocs.size())
return false;
while (NextValidReloc < ValidRelocs.size() &&
ValidRelocs[NextValidReloc].Offset < BaseOffset)
++NextValidReloc;
bool Applied = false;
uint64_t EndOffset = BaseOffset + Data.size();
while (NextValidReloc < ValidRelocs.size() &&
ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
ValidRelocs[NextValidReloc].Offset < EndOffset) {
const auto &ValidReloc = ValidRelocs[NextValidReloc++];
assert(ValidReloc.Offset - BaseOffset < Data.size());
assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
char Buf[8];
uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
Value += ValidReloc.Addend;
for (unsigned i = 0; i != ValidReloc.Size; ++i) {
unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
Buf[i] = uint8_t(Value >> (Index * 8));
}
assert(ValidReloc.Size <= sizeof(Buf));
memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
Applied = true;
}
return Applied;
}
static bool isTypeTag(uint16_t Tag) {
switch (Tag) {
case dwarf::DW_TAG_array_type:
case dwarf::DW_TAG_class_type:
case dwarf::DW_TAG_enumeration_type:
case dwarf::DW_TAG_pointer_type:
case dwarf::DW_TAG_reference_type:
case dwarf::DW_TAG_string_type:
case dwarf::DW_TAG_structure_type:
case dwarf::DW_TAG_subroutine_type:
case dwarf::DW_TAG_typedef:
case dwarf::DW_TAG_union_type:
case dwarf::DW_TAG_ptr_to_member_type:
case dwarf::DW_TAG_set_type:
case dwarf::DW_TAG_subrange_type:
case dwarf::DW_TAG_base_type:
case dwarf::DW_TAG_const_type:
case dwarf::DW_TAG_constant:
case dwarf::DW_TAG_file_type:
case dwarf::DW_TAG_namelist:
case dwarf::DW_TAG_packed_type:
case dwarf::DW_TAG_volatile_type:
case dwarf::DW_TAG_restrict_type:
case dwarf::DW_TAG_interface_type:
case dwarf::DW_TAG_unspecified_type:
case dwarf::DW_TAG_shared_type:
return true;
default:
break;
}
return false;
}
static bool isObjCSelector(const char *Name) {
return Name && (Name[0] == '-' || Name[0] == '+') && (Name[1] == '[');
}
void DwarfLinker::DIECloner::addObjCAccelerator(CompileUnit &Unit,
const DIE *Die,
const char *Name,
bool SkipPubSection) {
assert(isObjCSelector(Name) && "not an objc selector");
StringRef ClassNameStart(Name + 2);
size_t FirstSpace = ClassNameStart.find(' ');
if (FirstSpace == StringRef::npos)
return;
StringRef SelectorStart(ClassNameStart.data() + FirstSpace + 1);
if (!SelectorStart.size())
return;
StringRef Selector(SelectorStart.data(), SelectorStart.size() - 1);
StringRef SelectorStr = Linker.StringPool.internString(Selector);
Unit.addNameAccelerator(Die, SelectorStr.data(),
Linker.StringPool.getStringOffset(SelectorStr),
SkipPubSection);
StringRef ClassName(ClassNameStart.data(), FirstSpace);
StringRef ClassNameStr = Linker.StringPool.internString(ClassName);
Unit.addObjCAccelerator(Die, ClassNameStr.data(),
Linker.StringPool.getStringOffset(ClassNameStr),
SkipPubSection);
if (ClassName[ClassName.size() - 1] == ')') {
size_t OpenParens = ClassName.find('(');
if (OpenParens != StringRef::npos) {
StringRef ClassNameNoCategory(ClassName.data(), OpenParens);
StringRef ClassNameNoCategoryStr =
Linker.StringPool.internString(ClassNameNoCategory);
Unit.addObjCAccelerator(
Die, ClassNameNoCategoryStr.data(),
Linker.StringPool.getStringOffset(ClassNameNoCategoryStr),
SkipPubSection);
std::string MethodNameNoCategory(Name, OpenParens + 2);
MethodNameNoCategory.append(SelectorStart);
StringRef MethodNameNoCategoryStr =
Linker.StringPool.internString(MethodNameNoCategory);
Unit.addNameAccelerator(
Die, MethodNameNoCategoryStr.data(),
Linker.StringPool.getStringOffset(MethodNameNoCategoryStr),
SkipPubSection);
}
}
}
DIE *DwarfLinker::DIECloner::cloneDIE(
const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
int64_t PCOffset, uint32_t OutOffset, unsigned Flags) {
DWARFUnit &U = Unit.getOrigUnit();
unsigned Idx = U.getDIEIndex(&InputDIE);
CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
if (!Info.Keep)
return nullptr;
uint32_t Offset = InputDIE.getOffset();
DIE *Die = Info.Clone;
if (!Die)
Die = Info.Clone = new (DIEAlloc) DIE(dwarf::Tag(InputDIE.getTag()));
assert(Die->getTag() == InputDIE.getTag());
Die->setOffset(OutOffset);
if (Unit.hasODR() && Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
!Info.Ctxt->getCanonicalDIEOffset()) {
Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
}
DataExtractor Data = U.getDebugInfoExtractor();
uint32_t NextOffset =
(Idx + 1 < U.getNumDIEs())
? U.getDIEAtIndex(Idx + 1)->getOffset()
: U.getNextUnitOffset();
AttributesInfo AttrInfo;
SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
if (RelocMgr.applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
AttrInfo.OrigLowPc =
InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_low_pc, 0);
AttrInfo.OrigHighPc =
InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
}
Offset = 0;
const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
Offset += getULEB128Size(Abbrev->getCode());
if (Die->getTag() == dwarf::DW_TAG_subprogram)
PCOffset = Info.AddrAdjust;
AttrInfo.PCOffset = PCOffset;
if (Abbrev->getTag() == dwarf::DW_TAG_subprogram)
Flags |= TF_InFunctionScope;
if (Abbrev->getTag() == dwarf::DW_TAG_subprogram && !Info.InDebugMap)
Flags |= TF_SkipPC;
bool skipLocation =
(!(Flags & TF_InFunctionScope) &&
Abbrev->getTag() == dwarf::DW_TAG_variable && !Info.InDebugMap) ||
(Flags & TF_SkipPC);
if (LLVM_UNLIKELY(Options.Update)) {
skipLocation = false;
Flags &= ~TF_SkipPC;
}
bool Copied = false;
for (const auto &AttrSpec : Abbrev->attributes()) {
DWARFFormValue Val(AttrSpec.Form);
if (((Flags & TF_SkipPC) && (AttrSpec.Attr == dwarf::DW_AT_low_pc ||
AttrSpec.Attr == dwarf::DW_AT_high_pc ||
AttrSpec.Attr == dwarf::DW_AT_ranges)) ||
(skipLocation && (AttrSpec.Attr == dwarf::DW_AT_location ||
AttrSpec.Attr == dwarf::DW_AT_frame_base) &&
!Val.isFormClass(DWARFFormValue::FC_Block))) {
DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &U);
if (!Copied) {
copyAbbrev(*InputDIE.getAbbreviationDeclarationPtr(), Unit.hasODR());
Copied = true;
}
continue;
}
uint32_t AttrSize = Offset;
Val.extractValue(Data, &Offset, &U);
AttrSize = Offset - AttrSize;
OutOffset +=
cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
}
uint16_t Tag = InputDIE.getTag();
if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
Tag != dwarf::DW_TAG_compile_unit &&
Tag != dwarf::DW_TAG_label &&
getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo,
Tag != dwarf::DW_TAG_inlined_subroutine)) {
if (AttrInfo.MangledName &&
AttrInfo.MangledNameOffset != AttrInfo.NameOffset)
Unit.addNameAccelerator(Die, AttrInfo.MangledName,
AttrInfo.MangledNameOffset,
Tag == dwarf::DW_TAG_inlined_subroutine);
if (Tag == dwarf::DW_TAG_inlined_subroutine && AttrInfo.MangledName &&
!LLVM_UNLIKELY(Options.Update)) {
uint32_t NameOffset = AttrInfo.NameOffset;
if (AttrInfo.NameOffset == AttrInfo.MangledNameOffset)
NameOffset = 0;
Linker.Inlined[std::make_pair(NameOffset, AttrInfo.MangledNameOffset)]
.push_back(std::make_pair(Die->getOffset() + Unit.getStartOffset(),
AttrInfo.LowPc));
}
if (AttrInfo.Name) {
if (Tag != dwarf::DW_TAG_inlined_subroutine) {
if (!AttrInfo.NameWithoutTemplate.empty())
Unit.addNameAccelerator(Die, AttrInfo.NameWithoutTemplate.data(),
AttrInfo.NameWithoutTemplateOffset,
true );
}
Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
Tag == dwarf::DW_TAG_inlined_subroutine);
}
if (isObjCSelector(AttrInfo.Name))
addObjCAccelerator(Unit, Die, AttrInfo.Name, true );
} else if (Tag == dwarf::DW_TAG_namespace) {
if (!AttrInfo.Name) {
AttrInfo.Name = "(anonymous namespace)";
AttrInfo.NameOffset = Linker.StringPool.getStringOffset(AttrInfo.Name);
}
Unit.addNamespaceAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
} else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo) &&
AttrInfo.Name && AttrInfo.Name[0]) {
uint32_t Hash = hashFullyQualifiedName(&InputDIE, Unit);
uint64_t RuntimeLang = InputDIE.getAttributeValueAsUnsignedConstant(
&U, dwarf::DW_AT_APPLE_runtime_class, 0);
bool ObjCClassIsImplementation =
(RuntimeLang == dwarf::DW_LANG_ObjC ||
RuntimeLang == dwarf::DW_LANG_ObjC_plus_plus) &&
InputDIE.getAttributeValueAsUnsignedConstant(
&U, dwarf::DW_AT_APPLE_objc_complete_type, 0);
Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
ObjCClassIsImplementation, Hash);
}
DIEAbbrev &NewAbbrev = Die->getAbbrev();
if (InputDIE.hasChildren())
NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
Linker.AssignAbbrev(Die->getAbbrev());
OutOffset += getULEB128Size(Die->getAbbrevNumber());
if (!Abbrev->hasChildren()) {
Die->setSize(OutOffset - Die->getOffset());
return Die;
}
for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
Child = Child->getSibling())
if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset, Flags)) {
Die->addChild(Clone);
OutOffset = Clone->getOffset() + Clone->getSize();
}
OutOffset += sizeof(int8_t);
Die->setSize(OutOffset - Die->getOffset());
return Die;
}
void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
DWARFContext &OrigDwarf) const {
DWARFDebugRangeList RangeList;
const auto &FunctionRanges = Unit.getFunctionRanges();
unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
OrigDwarf.isLittleEndian(), AddressSize);
auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
DWARFUnit &OrigUnit = Unit.getOrigUnit();
const auto *OrigUnitDie = OrigUnit.getCompileUnitDIE(false);
uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
int64_t UnitPcOffset = 0;
if (OrigLowPc != -1ULL)
UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
uint32_t Offset = RangeAttribute->getValue();
RangeAttribute->setValue(Streamer->getRangesSectionSize());
RangeList.extract(RangeExtractor, &Offset);
const auto &Entries = RangeList.getEntries();
if (!Entries.empty()) {
const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
if (CurrRange == InvalidRange ||
First.StartAddress + OrigLowPc < CurrRange.start() ||
First.StartAddress + OrigLowPc >= CurrRange.stop()) {
CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
if (CurrRange == InvalidRange ||
CurrRange.start() > First.StartAddress + OrigLowPc) {
reportWarning("no mapping for range.");
continue;
}
}
}
Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
AddressSize);
}
}
void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
DIEInteger *Attr = Unit.getUnitRangesAttribute();
if (Attr)
Attr->setValue(Streamer->getRangesSectionSize());
Streamer->emitUnitRangesEntries(Unit, Attr != nullptr);
}
static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
std::vector<DWARFDebugLine::Row> &Rows) {
if (Seq.size() <= 1)
return;
if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
Rows.insert(Rows.end(), Seq.begin(), Seq.end());
Seq.clear();
return;
}
auto InsertPoint = std::lower_bound(
Rows.begin(), Rows.end(), Seq.front(),
[](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
return LHS.Address < RHS.Address;
});
if (InsertPoint != Rows.end() &&
InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
*InsertPoint = Seq.front();
Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
} else {
Rows.insert(InsertPoint, Seq.begin(), Seq.end());
}
Seq.clear();
}
void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
const DebugMapObject &DMO,
DWARFContext &OrigDwarf) {
const DWARFDebugInfoEntryMinimal *CUDie =
Unit.getOrigUnit().getCompileUnitDIE();
uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
&Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
if (StmtList == -1ULL)
return;
if (auto *OutputDIE = Unit.getOutputUnitDIE()) {
const auto &Abbrev = OutputDIE->getAbbrev().getData();
auto Stmt = std::find_if(
Abbrev.begin(), Abbrev.end(), [](const DIEAbbrevData &AbbrevData) {
return AbbrevData.getAttribute() == dwarf::DW_AT_stmt_list;
});
assert(Stmt < Abbrev.end() && "Didn't find DW_AT_stmt_list in cloned DIE!");
DIEInteger *StmtAttr =
cast<DIEInteger>(OutputDIE->getValues()[Stmt - Abbrev.begin()]);
StmtAttr->setValue(Streamer->getLineSectionSize());
}
uint32_t StmtOffset = StmtList;
StringRef LineData = OrigDwarf.getLineSection().Data;
DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
Unit.getOrigUnit().getAddressByteSize());
if (Options.Translator)
return Streamer->translateLineTable(LineExtractor, StmtList, Options);
DWARFDebugLine::LineTable LineTable;
LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
&StmtOffset);
std::vector<DWARFDebugLine::Row> NewRows;
NewRows.reserve(LineTable.Rows.size());
std::vector<DWARFDebugLine::Row> Seq;
std::pair<uint64_t, uint64_t> InvalidRange = {-1ULL, -1ULL};
auto CurrRange = InvalidRange;
uint64_t PCOffset = -1ULL;
for (auto &Row : LineTable.Rows) {
if (CurrRange == InvalidRange || Row.Address < CurrRange.first ||
Row.Address > CurrRange.second ||
(Row.Address == CurrRange.second && !Row.EndSequence)) {
bool InPrevRangeInclusive =
CurrRange != InvalidRange && Row.Address == CurrRange.second;
uint64_t StopAddress =
CurrRange == InvalidRange ? -1ULL : CurrRange.second + PCOffset;
bool CurrRangeValid = false;
CurrRange = InvalidRange;
auto Range = Ranges.lower_bound(Row.Address);
if (Range != Ranges.end()) {
if (Range != Ranges.begin() &&
(Range->first > Row.Address ||
(Row.EndSequence &&
std::prev(Range)->second.first == Row.Address)))
--Range;
if (Range->first <= Row.Address &&
(Range->second.first > Row.Address ||
(Row.EndSequence && Range->second.first == Row.Address))) {
if (Row.EndSequence || StopAddress == -1ULL)
StopAddress = Row.Address + Range->second.second;
CurrRange = {Range->first, Range->second.first};
PCOffset = Range->second.second;
CurrRangeValid = true;
}
}
if (StopAddress != -1ULL && !Seq.empty()) {
Seq.emplace_back(Seq.empty() ? Row : Seq.back());
Seq.back().Address = StopAddress;
Seq.back().EndSequence = 1;
Seq.back().PrologueEnd = 0;
Seq.back().BasicBlock = 0;
Seq.back().EpilogueBegin = 0;
if (!CurrRangeValid && InPrevRangeInclusive)
Seq.back().IsStmt = Row.IsStmt;
insertLineSequence(Seq, NewRows);
}
if (!CurrRangeValid)
continue;
if (Row.Address == CurrRange.second)
continue;
}
if (Row.EndSequence && Seq.empty())
continue;
Row.Address += PCOffset;
Seq.emplace_back(Row);
if (Row.EndSequence)
insertLineSequence(Seq, NewRows);
}
uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
if (LineTable.Prologue.Version != 2 ||
LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
LineTable.Prologue.OpcodeBase > 13)
reportWarning("line table parameters mismatch. Cannot emit.");
else {
MCDwarfLineTableParameters Params;
Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
Params.DWARF2LineBase = LineTable.Prologue.LineBase;
Params.DWARF2LineRange = LineTable.Prologue.LineRange;
Streamer->emitLineTableForUnit(Params,
LineData.slice(StmtList + 4, PrologueEnd),
LineTable.Prologue.MinInstLength, NewRows,
Unit.getOrigUnit().getAddressByteSize());
}
}
void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
for (const auto &Namespace : Unit.getNamespaces())
AppleNamespaces.AddName(Namespace.Name, Namespace.NameOffset,
Namespace.Die->getOffset() + Unit.getStartOffset());
if (!Options.Minimize)
Streamer->emitPubNamesForUnit(Unit);
for (const auto &Pubname : Unit.getPubnames())
AppleNames.AddName(Pubname.Name, Pubname.NameOffset,
Pubname.Die->getOffset() + Unit.getStartOffset());
if (!Options.Minimize)
Streamer->emitPubTypesForUnit(Unit);
for (const auto &Pubtype : Unit.getPubtypes())
AppleTypes.AddName(Pubtype.Name, Pubtype.NameOffset,
Pubtype.Die->getOffset() + Unit.getStartOffset())
.addAtom<uint16_t>(Pubtype.Die->getTag())
.addAtom<uint8_t>(Pubtype.ObjCClassIsImplementation
? dwarf::DW_FLAG_type_implementation
: 0)
.addAtom<uint32_t>(Pubtype.QualifiedNameHash);
for (const auto &ObjC : Unit.getObjC())
AppleObjc.AddName(ObjC.Name, ObjC.NameOffset,
ObjC.Die->getOffset() + Unit.getStartOffset());
}
void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
DWARFContext &OrigDwarf,
unsigned AddrSize) {
StringRef FrameData = OrigDwarf.getDebugFrameSection();
if (FrameData.empty())
return;
DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
uint32_t InputOffset = 0;
DenseMap<uint32_t, StringRef> LocalCIES;
bool HasInterestingContent = false;
for (auto &Unit : Units)
if (Unit.hasInterestingContent()) {
HasInterestingContent = true;
break;
}
if (!HasInterestingContent)
return;
while (Data.isValidOffset(InputOffset)) {
uint32_t EntryOffset = InputOffset;
uint32_t InitialLength = Data.getU32(&InputOffset);
if (InitialLength == 0xFFFFFFFF)
return reportWarning("Dwarf64 bits no supported");
uint32_t CIEId = Data.getU32(&InputOffset);
if (CIEId == 0xFFFFFFFF) {
StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
LocalCIES[EntryOffset] = CIEData;
InputOffset += InitialLength - 4;
continue;
}
uint64_t Loc;
switch (AddrSize) {
case 4:
Loc = Data.getU32(&InputOffset);
break;
case 8:
Loc = Data.getU64(&InputOffset);
break;
default:
return reportWarning("Unsuported address size.");
}
auto Range = Ranges.upper_bound(Loc);
if (Range != Ranges.begin())
--Range;
if (Range == Ranges.end() || Range->first > Loc ||
Range->second.first <= Loc) {
InputOffset = EntryOffset + InitialLength + 4;
continue;
}
StringRef CIEData = LocalCIES[CIEId];
if (CIEData.empty())
return reportWarning("Inconsistent debug_frame content. Dropping.");
auto IteratorInserted = EmittedCIEs.insert(
std::make_pair(CIEData, Streamer->getFrameSectionSize()));
if (IteratorInserted.second ||
LastCIEOffset != IteratorInserted.first->getValue()) {
IteratorInserted.first->getValue() = LastCIEOffset = Streamer->getFrameSectionSize();
Streamer->emitCIE(CIEData);
}
Streamer->emitFDE(
IteratorInserted.first->getValue(), AddrSize,
Loc + Range->second.second,
FrameData.substr(InputOffset, InitialLength - (4 + AddrSize)));
InputOffset += InitialLength - (4 + AddrSize);
}
}
void DwarfLinker::DIECloner::copyAbbrev(
const DWARFAbbreviationDeclaration &Abbrev, bool hasODR) {
DIEAbbrev Copy((dwarf::Tag)Abbrev.getTag(),
(dwarf::Form)Abbrev.hasChildren());
for (const auto &Attr : Abbrev.attributes()) {
uint16_t Form = Attr.Form;
if (hasODR && isODRAttribute(Attr.Attr))
Form = dwarf::DW_FORM_ref_addr;
Copy.AddAttribute(dwarf::Attribute(Attr.Attr), dwarf::Form(Form));
}
Linker.AssignAbbrev(Copy);
}
uint32_t DwarfLinker::DIECloner::hashFullyQualifiedName(
const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &U, int RecurseDepth) {
const char *Name = nullptr;
DWARFUnit *OrigUnit = &U.getOrigUnit();
CompileUnit *CU = &U;
uint64_t Ref;
do {
if (const char *CurrentName =
DIE->getName(&U.getOrigUnit(), DINameKind::ShortName))
Name = CurrentName;
Ref = DIE->getAttributeValueAsReference(&U.getOrigUnit(),
dwarf::DW_AT_specification, 0);
if (!Ref)
Ref = DIE->getAttributeValueAsReference(&U.getOrigUnit(),
dwarf::DW_AT_abstract_origin, 0);
if (Ref) {
CompileUnit *RefCU;
if (auto *RefDIE = resolveDIEReference(CompileUnits, Ref, U.getOrigUnit(),
*DIE, RefCU, Linker)) {
CU = RefCU;
OrigUnit = &RefCU->getOrigUnit();
DIE = RefDIE;
}
}
} while (Ref);
unsigned Idx = OrigUnit->getDIEIndex(DIE);
if (!Name && DIE->getTag() == dwarf::DW_TAG_namespace)
Name = "(anonymous namespace)";
if (CU->getInfo(Idx).ParentIdx == 0 ||
CU->getOrigUnit().getDIEAtIndex(CU->getInfo(Idx).ParentIdx)->getTag() == dwarf::DW_TAG_module)
return DwarfAccelTable::HashDJB(
Name ? Name : "", DwarfAccelTable::HashDJB(RecurseDepth ? "" : "::"));
return DwarfAccelTable::HashDJB(
(Name ? Name : ""),
DwarfAccelTable::HashDJB(
(Name ? "::" : ""),
hashFullyQualifiedName(
OrigUnit->getDIEAtIndex(CU->getInfo(Idx).ParentIdx), *CU,
++RecurseDepth)));
}
static DWARFAcceleratorTable *getAccelTable(DWARFContextInMemory &DwarfContext,
const DWARFSection &Section) {
DataExtractor AccelSection(Section.Data, DwarfContext.isLittleEndian(), 0);
DataExtractor StrData(DwarfContext.getStringSection(),
DwarfContext.isLittleEndian(), 0);
auto Table = new DWARFAcceleratorTable(AccelSection, StrData, Section.Relocs);
Table->extract();
return Table;
}
bool DwarfLinker::registerModuleReference(
const DWARFDebugInfoEntryMinimal &CUDie, const DWARFUnit &Unit,
DebugMap &ModuleMap, unsigned Indent) {
std::string PCMfile =
CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_GNU_dwo_name, "");
if (PCMfile.empty())
return false;
std::string PCMpath =
CUDie.getAttributeValueAsString(&Unit, dwarf::DW_AT_comp_dir, "");
if (Options.Verbose) {
outs().indent(Indent);
outs() << "Found clang module reference " << PCMfile;
}
if (ClangModules.count(PCMfile)) {
if (Options.Verbose)
outs() << " [skipping].\n";
return true;
}
if (Options.Verbose)
outs() << " [following].\n";
ClangModules.insert({PCMfile, ClangModule()});
loadClangModule(PCMfile, PCMpath, ModuleMap, Indent + 2);
return true;
}
ErrorOr<const object::ObjectFile &>
DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
const DebugMap &Map) {
auto ErrOrObjs =
BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
if (std::error_code EC = ErrOrObjs.getError())
reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
if (std::error_code EC = ErrOrObj.getError())
reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
return ErrOrObj;
}
void DwarfLinker::loadClangModule(StringRef Filename, StringRef ModulePath,
DebugMap &ModuleMap,
unsigned Indent) {
SmallString<80> Path(Options.PrependPath);
if (sys::path::is_relative(Filename))
sys::path::append(Path, ModulePath, Filename);
else
sys::path::append(Path, Filename);
auto *ObjHolder = new BinaryHolder(Options.Verbose);
auto &Obj = ModuleMap.addDebugMapObject(Path, sys::TimeValue::MinTime());
auto ErrOrObj = loadObject(*ObjHolder, Obj, ModuleMap);
if (!ErrOrObj) {
ClangModules.erase(ClangModules.find(Filename));
return;
}
CompileUnit *Unit = nullptr;
auto *DwarfContext = new DWARFContextInMemory(*ErrOrObj);
RelocationManager RelocMgr(*this);
for (const auto &CU : DwarfContext->compile_units()) {
auto *CUDie = CU->getCompileUnitDIE(false);
if (false && Options.Verbose) {
outs().indent(Indent);
outs() << "Input compilation unit:";
CUDie->dump(outs(), CU.get(), 0, Indent);
}
if (!registerModuleReference(*CUDie, *CU, ModuleMap, Indent)) {
if (Unit) {
errs() << Filename << ": Clang modules are expected to have exactly"
<< " 1 compile unit.\n";
exitDsymutil(1);
}
Unit = new CompileUnit(*CU, UnitID++, !Options.NoODR, Obj);
Unit->setHasInterestingContent();
gatherDIEParents(CUDie, 0, *Unit, &RootDeclContext, StringPool,
DeclContexts);
Unit->markEverythingAsKept();
}
}
if (Options.Verbose) {
outs().indent(Indent);
outs() << "cloning .debug_info from " << Filename << "\n";
}
ClangModule &CM = ClangModules.find(Filename)->second;
CM.BinaryHolder.reset(ObjHolder);
CM.DwarfContext.reset(DwarfContext);
CM.AppleTypes.reset(
getAccelTable(*DwarfContext, DwarfContext->getAppleTypesSection()));
CM.Unit.reset(Unit);
DIECloner(*this, RelocMgr, ModuleDIEAlloc,
MutableArrayRef<CompileUnit>(*Unit), Options)
.cloneAllCompileUnits(*DwarfContext);
}
void DwarfLinker::DIECloner::cloneAllCompileUnits(
DWARFContextInMemory &DwarfContext) {
if (!Linker.Streamer)
return;
ExtTypes.reset(
getAccelTable(DwarfContext, DwarfContext.getAppleExternalTypesSection()));
for (auto &CurrentUnit : CompileUnits) {
const auto *InputDIE = CurrentUnit.getOrigUnit().getCompileUnitDIE();
Linker.Streamer->switchToDebugInfoSection(
CurrentUnit.getOrigUnit().getVersion());
CurrentUnit.setStartOffset(Linker.OutputDebugInfoSize);
DIE *OutputDIE = nullptr;
if (CurrentUnit.hasInterestingContent() || CompileUnits.size() != 1)
OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 ,
11 , 0);
CurrentUnit.setOutputUnitDIE(OutputDIE);
if (OutputDIE || CompileUnits.size() != 1)
Linker.OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
if (Linker.Options.NoOutput)
continue;
if ((!Linker.Options.Update || Linker.Options.Translator) &&
(OutputDIE || CompileUnits.size() != 1))
Linker.patchLineTableForUnit(CurrentUnit, Linker.getCurrentDMO(),
DwarfContext);
if (!OutputDIE)
continue;
Linker.emitAcceleratorEntriesForUnit(CurrentUnit);
if (Linker.Options.Update)
continue;
Linker.patchRangesForUnit(CurrentUnit, DwarfContext);
Linker.Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
}
if (Linker.Options.NoOutput)
return;
for (auto &CurrentUnit : CompileUnits) {
if (!Linker.Options.Update)
Linker.generateUnitRanges(CurrentUnit);
CurrentUnit.fixupForwardReferences();
if (CurrentUnit.getOutputUnitDIE() || CompileUnits.size() != 1)
Linker.Streamer->emitCompileUnitHeader(CurrentUnit);
if (!CurrentUnit.getOutputUnitDIE())
continue;
Linker.Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
}
}
bool DwarfLinker::link(const DebugMap &Map) {
if (Map.begin() == Map.end() && !Options.Update)
errs() << "warning: no debug symbols in executable (-arch "
<< Map.getTriple().getArchName() << ")\n";
if (!createStreamer(Map.getTriple(), Map.getBinaryPath(), OutputFilename))
return false;
OutputDebugInfoSize = 0;
UnitID = 0;
DebugMap ModuleMap(Map.getTriple(), Map.getBinaryPath());
for (const auto &Obj : Map.objects()) {
CurrentDebugObject = Obj.get();
if (Options.Verbose)
outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename()
<< " (timestamp: " << Obj->getTimestamp().seconds() << ")\n";
if (Obj->isSwiftModule()) {
StringRef File = Obj->getObjectFilename();
auto ErrorOrMem = MemoryBuffer::getFile(File);
if (!ErrorOrMem) {
errs() << "Warning: Could not open " << File << "\n";
continue;
}
sys::fs::file_status Stat;
if (auto errc = sys::fs::status(File, Stat)) {
errs() << "Warning: " << errc.message() << "\n";
continue;
}
if (Stat.getLastModificationTime() != Obj->getTimestamp()) {
errs() << "Warning: Timestamp mismatch for " << File << "\n";
continue;
}
Streamer->emitSwiftModule((*ErrorOrMem)->getBuffer());
continue;
}
if (Obj->getWarnings().size() && Obj->empty()) {
Streamer->switchToDebugInfoSection( 2);
DIE *CUDie = new (DIEAlloc) DIE(dwarf::DW_TAG_compile_unit);
CUDie->setOffset(11);
StringRef Producer = StringPool.internString( "dsymutil from dwarf_utilities-132 (Apple Inc.)");
StringRef File = StringPool.internString(Obj->getObjectFilename());
CUDie->addValue(
dwarf::Attribute(dwarf::DW_AT_producer), dwarf::DW_FORM_strp,
new (DIEAlloc) DIEInteger(StringPool.getStringOffset(Producer)),
&DIEsToDelete);
DIEBlock *String = new (DIEAlloc) DIEBlock();
DIEBlocks.push_back(String);
for (auto &C : File)
String->addValue(dwarf::Attribute(0), dwarf::DW_FORM_data1,
new (DIEAlloc) DIEInteger(C));
String->addValue(dwarf::Attribute(0), dwarf::DW_FORM_data1,
new (DIEAlloc) DIEInteger(0));
CUDie->addValue(dwarf::Attribute(dwarf::DW_AT_name),
dwarf::DW_FORM_string, String, &DIEsToDelete);
for (const auto &Warning : Obj->getWarnings()) {
CUDie->addChild(new (DIEAlloc) DIE(dwarf::DW_TAG_constant));
DIE &ConstDie = CUDie->getChildren().back();
ConstDie.addValue(
dwarf::Attribute(dwarf::DW_AT_name), dwarf::DW_FORM_strp,
new (DIEAlloc)
DIEInteger(StringPool.getStringOffset("dsymutil_warning")),
&DIEsToDelete);
ConstDie.addValue(dwarf::Attribute(dwarf::DW_AT_artificial),
dwarf::DW_FORM_flag, new (DIEAlloc) DIEInteger(1),
&DIEsToDelete);
ConstDie.addValue(dwarf::Attribute(dwarf::DW_AT_const_value),
dwarf::DW_FORM_strp,
new (DIEAlloc) DIEInteger(StringPool.getStringOffset(
StringPool.internString(Warning))),
&DIEsToDelete);
}
unsigned Size = 4 + File.size() + 1 +
CUDie->getChildren().size() * (4 + 1 + 4) +
1 ;
AssignAbbrev(CUDie->getAbbrev());
Size += getULEB128Size(CUDie->getAbbrev().getNumber());
for (auto &Child : CUDie->getChildren()) {
AssignAbbrev(Child.getAbbrev());
Size += getULEB128Size(Child.getAbbrev().getNumber());
}
CUDie->setSize(Size);
auto &Asm = Streamer->getAsmPrinter();
Asm.EmitInt32(11 + CUDie->getSize() - 4);
Asm.EmitInt16(2);
Asm.EmitInt32(0);
Asm.EmitInt8(Asm.getDataLayout().getPointerSize());
Streamer->emitDIE(*CUDie);
OutputDebugInfoSize += 11 + Size;
continue;
}
auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
if (!ErrOrObj)
continue;
RelocationManager RelocMgr(*this);
if (!Options.Update &&
!RelocMgr.findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
if (Options.Verbose)
outs() << "No valid relocations found. Skipping.\n";
continue;
}
DWARFContextInMemory DwarfContext(*ErrOrObj);
startDebugObject(DwarfContext, *Obj);
for (const auto &CU : DwarfContext.compile_units()) {
auto *CUDie = CU->getCompileUnitDIE(false);
if (Options.Verbose) {
outs() << "Input compilation unit:";
CUDie->dump(outs(), CU.get(), 0);
}
if (!registerModuleReference(*CUDie, *CU, ModuleMap)) {
bool CanUseODR = !Options.NoODR && !Options.Update;
Units.emplace_back(*CU, UnitID++, CanUseODR, *Obj);
gatherDIEParents(CUDie, 0, Units.back(), &RootDeclContext, StringPool,
DeclContexts);
}
}
if (Options.Update) {
for (auto &Unit : Units)
Unit.markEverythingAsKept();
Streamer->copyInvariantDebugSection(*ErrOrObj, Options);
} else {
for (auto &CurrentUnit : Units)
lookForDIEsToKeep(RelocMgr,
*CurrentUnit.getOrigUnit().getCompileUnitDIE(), *Obj,
CurrentUnit, 0);
}
RelocMgr.resetValidRelocs();
if (RelocMgr.hasValidRelocs() || Options.Update)
DIECloner(*this, RelocMgr, DIEAlloc, Units, Options)
.cloneAllCompileUnits(DwarfContext);
if (RelocMgr.hasValidRelocs() && !Options.NoOutput && !Units.empty() &&
!Options.Update)
patchFrameInfoForObject(*Obj, DwarfContext,
Units[0].getOrigUnit().getAddressByteSize());
DIEToDeclContext.clear();
Units.clear();
for (auto *Die : DIEsToDelete) {
Die->getChildren().clearAndLeakNodesUnsafely();
Die->~DIE();
}
DIEsToDelete.resize(0);
DIEAlloc.Reset();
if (Options.Verbose) {
outs() << "DebugInfo is currently " << OutputDebugInfoSize / (1024 * 1024)
<< "MB\n";
}
endDebugObject();
}
if (!Options.NoOutput) {
Streamer->emitAbbrevs(Abbreviations);
Streamer->emitStrings(StringPool);
Streamer->emitAppleNames(AppleNames);
Streamer->emitAppleNamespaces(AppleNamespaces);
Streamer->emitAppleTypes(AppleTypes);
Streamer->emitAppleObjc(AppleObjc);
if (!Options.Minimize && !Options.Update)
Streamer->emitDebugInlined(Inlined);
}
return Options.NoOutput ? true : Streamer->finish(Map, Options.Translator);
}
bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
const LinkOptions &Options) {
DwarfLinker Linker(OutputFilename, Options);
return Linker.link(DM);
}
}
}