#include "GraphBuilder.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/DebugInfo/Symbolize/SymbolizableModule.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCDisassembler/MCDisassembler.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/MC/MCInstrAnalysis.h"
#include "llvm/MC/MCInstrDesc.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/TargetRegistry.h"
#include "llvm/Object/Binary.h"
#include "llvm/Object/COFF.h"
#include "llvm/Object/ELFObjectFile.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/raw_ostream.h"
using Instr = llvm::cfi_verify::FileAnalysis::Instr;
namespace llvm {
namespace cfi_verify {
uint64_t SearchLengthForUndef;
uint64_t SearchLengthForConditionalBranch;
static cl::opt<uint64_t, true> SearchLengthForUndefArg(
"search-length-undef",
cl::desc("Specify the maximum amount of instructions "
"to inspect when searching for an undefined "
"instruction from a conditional branch."),
cl::location(SearchLengthForUndef), cl::init(2));
static cl::opt<uint64_t, true> SearchLengthForConditionalBranchArg(
"search-length-cb",
cl::desc("Specify the maximum amount of instructions "
"to inspect when searching for a conditional "
"branch from an indirect control flow."),
cl::location(SearchLengthForConditionalBranch), cl::init(20));
std::vector<uint64_t> GraphResult::flattenAddress(uint64_t Address) const {
std::vector<uint64_t> Addresses;
auto It = IntermediateNodes.find(Address);
Addresses.push_back(Address);
while (It != IntermediateNodes.end()) {
Addresses.push_back(It->second);
It = IntermediateNodes.find(It->second);
}
return Addresses;
}
void printPairToDOT(const FileAnalysis &Analysis, raw_ostream &OS,
uint64_t From, uint64_t To) {
OS << " \"" << format_hex(From, 2) << ": ";
Analysis.printInstruction(Analysis.getInstructionOrDie(From), OS);
OS << "\" -> \"" << format_hex(To, 2) << ": ";
Analysis.printInstruction(Analysis.getInstructionOrDie(To), OS);
OS << "\"\n";
}
void GraphResult::printToDOT(const FileAnalysis &Analysis,
raw_ostream &OS) const {
std::map<uint64_t, uint64_t> SortedIntermediateNodes(
IntermediateNodes.begin(), IntermediateNodes.end());
OS << "digraph graph_" << format_hex(BaseAddress, 2) << " {\n";
for (const auto &KV : SortedIntermediateNodes)
printPairToDOT(Analysis, OS, KV.first, KV.second);
for (auto &BranchNode : ConditionalBranchNodes) {
for (auto &V : {BranchNode.Target, BranchNode.Fallthrough})
printPairToDOT(Analysis, OS, BranchNode.Address, V);
}
OS << "}\n";
}
GraphResult GraphBuilder::buildFlowGraph(const FileAnalysis &Analysis,
object::SectionedAddress Address) {
GraphResult Result;
Result.BaseAddress = Address.Address;
DenseSet<uint64_t> OpenedNodes;
const auto &IndirectInstructions = Analysis.getIndirectInstructions();
if (IndirectInstructions.find(Address) == IndirectInstructions.end()) {
return Result;
}
buildFlowGraphImpl(Analysis, OpenedNodes, Result, Address.Address, 0);
return Result;
}
void GraphBuilder::buildFlowsToUndefined(const FileAnalysis &Analysis,
GraphResult &Result,
ConditionalBranchNode &BranchNode,
const Instr &BranchInstrMeta) {
assert(SearchLengthForUndef > 0 &&
"Search length for undefined flow must be greater than zero.");
uint64_t NextAddress = 0;
const Instr *NextMetaPtr;
if (BranchNode.Target && !BranchNode.Fallthrough) {
NextMetaPtr = Analysis.getNextInstructionSequential(BranchInstrMeta);
if (!NextMetaPtr) {
errs() << "Failed to get next instruction from "
<< format_hex(BranchNode.Address, 2) << ".\n";
return;
}
NextAddress = NextMetaPtr->VMAddress;
BranchNode.Fallthrough =
NextMetaPtr->VMAddress; } else if (BranchNode.Fallthrough && !BranchNode.Target) {
uint64_t Target;
if (!Analysis.getMCInstrAnalysis()->evaluateBranch(
BranchInstrMeta.Instruction, BranchInstrMeta.VMAddress,
BranchInstrMeta.InstructionSize, Target)) {
errs() << "Failed to get branch target for conditional branch at address "
<< format_hex(BranchInstrMeta.VMAddress, 2) << ".\n";
return;
}
NextMetaPtr = Analysis.getInstruction(Target);
if (!NextMetaPtr) {
errs() << "Failed to find instruction at address "
<< format_hex(Target, 2) << ".\n";
return;
}
NextAddress = Target;
BranchNode.Target =
NextMetaPtr->VMAddress; } else {
errs() << "ControlBranchNode supplied to buildFlowsToUndefined should "
"provide Target xor Fallthrough.\n";
return;
}
uint64_t CurrentAddress = NextAddress;
const Instr *CurrentMetaPtr = NextMetaPtr;
for (uint64_t i = 1; i < SearchLengthForUndef; ++i) {
if (Analysis.isCFITrap(*CurrentMetaPtr)) {
BranchNode.CFIProtection = true;
return;
}
NextMetaPtr = Analysis.getDefiniteNextInstruction(*CurrentMetaPtr);
if (!NextMetaPtr)
return;
NextAddress = NextMetaPtr->VMAddress;
Result.IntermediateNodes[CurrentAddress] = NextAddress;
CurrentMetaPtr = NextMetaPtr;
CurrentAddress = NextAddress;
}
if (Analysis.isCFITrap(*CurrentMetaPtr))
BranchNode.CFIProtection = true;
}
void GraphBuilder::buildFlowGraphImpl(const FileAnalysis &Analysis,
DenseSet<uint64_t> &OpenedNodes,
GraphResult &Result, uint64_t Address,
uint64_t Depth) {
if (Depth >= SearchLengthForConditionalBranch) {
Result.OrphanedNodes.push_back(Address);
return;
}
if (OpenedNodes.count(Address))
Result.OrphanedNodes.push_back(Address);
if (Result.IntermediateNodes.count(Address))
return;
const auto &InstrMetaPtr = Analysis.getInstruction(Address);
if (!InstrMetaPtr) {
errs() << "Failed to build flow graph for instruction at address "
<< format_hex(Address, 2) << ".\n";
Result.OrphanedNodes.push_back(Address);
return;
}
const auto &ChildMeta = *InstrMetaPtr;
OpenedNodes.insert(Address);
std::set<const Instr *> CFCrossRefs =
Analysis.getDirectControlFlowXRefs(ChildMeta);
bool HasValidCrossRef = false;
for (const auto *ParentMetaPtr : CFCrossRefs) {
assert(ParentMetaPtr && "CFCrossRefs returned nullptr.");
const auto &ParentMeta = *ParentMetaPtr;
const auto &ParentDesc =
Analysis.getMCInstrInfo()->get(ParentMeta.Instruction.getOpcode());
if (!ParentDesc.mayAffectControlFlow(ParentMeta.Instruction,
*Analysis.getRegisterInfo())) {
buildFlowGraphImpl(Analysis, OpenedNodes, Result, ParentMeta.VMAddress,
Depth + 1);
Result.IntermediateNodes[ParentMeta.VMAddress] = Address;
HasValidCrossRef = true;
continue;
}
if (ParentDesc.isCall()) {
Result.IntermediateNodes[ParentMeta.VMAddress] = Address;
Result.OrphanedNodes.push_back(ParentMeta.VMAddress);
continue;
}
uint64_t BranchTarget;
if (!Analysis.getMCInstrAnalysis()->evaluateBranch(
ParentMeta.Instruction, ParentMeta.VMAddress,
ParentMeta.InstructionSize, BranchTarget)) {
errs() << "Failed to evaluate branch target for instruction at address "
<< format_hex(ParentMeta.VMAddress, 2) << ".\n";
Result.IntermediateNodes[ParentMeta.VMAddress] = Address;
Result.OrphanedNodes.push_back(ParentMeta.VMAddress);
continue;
}
if (ParentDesc.isUnconditionalBranch()) {
if (BranchTarget != Address) {
errs() << "Control flow to " << format_hex(Address, 2)
<< ", but target resolution of "
<< format_hex(ParentMeta.VMAddress, 2)
<< " is not this address?\n";
Result.IntermediateNodes[ParentMeta.VMAddress] = Address;
Result.OrphanedNodes.push_back(ParentMeta.VMAddress);
continue;
}
buildFlowGraphImpl(Analysis, OpenedNodes, Result, ParentMeta.VMAddress,
Depth + 1);
Result.IntermediateNodes[ParentMeta.VMAddress] = Address;
HasValidCrossRef = true;
continue;
}
if (!ParentDesc.isConditionalBranch()) {
errs() << "Unknown control flow encountered when building graph at "
<< format_hex(Address, 2) << "\n.";
Result.IntermediateNodes[ParentMeta.VMAddress] = Address;
Result.OrphanedNodes.push_back(ParentMeta.VMAddress);
continue;
}
ConditionalBranchNode BranchNode;
BranchNode.Address = ParentMeta.VMAddress;
BranchNode.Target = 0;
BranchNode.Fallthrough = 0;
BranchNode.CFIProtection = false;
BranchNode.IndirectCFIsOnTargetPath = (BranchTarget == Address);
if (BranchTarget == Address)
BranchNode.Target = Address;
else
BranchNode.Fallthrough = Address;
HasValidCrossRef = true;
buildFlowsToUndefined(Analysis, Result, BranchNode, ParentMeta);
Result.ConditionalBranchNodes.push_back(BranchNode);
}
if (CFCrossRefs.empty()) {
const Instr *PrevInstr = Analysis.getPrevInstructionSequential(ChildMeta);
if (PrevInstr && Analysis.willTrapOnCFIViolation(*PrevInstr)) {
Result.IntermediateNodes[PrevInstr->VMAddress] = Address;
HasValidCrossRef = true;
}
}
if (!HasValidCrossRef)
Result.OrphanedNodes.push_back(Address);
OpenedNodes.erase(Address);
}
} }