1 //===- FileAnalysis.cpp -----------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "FileAnalysis.h"
12 #include "llvm/BinaryFormat/ELF.h"
13 #include "llvm/MC/MCAsmInfo.h"
14 #include "llvm/MC/MCContext.h"
15 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
16 #include "llvm/MC/MCInst.h"
17 #include "llvm/MC/MCInstPrinter.h"
18 #include "llvm/MC/MCInstrAnalysis.h"
19 #include "llvm/MC/MCInstrDesc.h"
20 #include "llvm/MC/MCInstrInfo.h"
21 #include "llvm/MC/MCObjectFileInfo.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCSubtargetInfo.h"
24 #include "llvm/Object/Binary.h"
25 #include "llvm/Object/COFF.h"
26 #include "llvm/Object/ELFObjectFile.h"
27 #include "llvm/Object/ObjectFile.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Error.h"
31 #include "llvm/Support/FormatVariadic.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/TargetSelect.h"
35 #include "llvm/Support/raw_ostream.h"
39 using Instr = llvm::cfi_verify::FileAnalysis::Instr;
42 namespace cfi_verify {
44 Expected<FileAnalysis> FileAnalysis::Create(StringRef Filename) {
45 // Open the filename provided.
46 Expected<object::OwningBinary<object::Binary>> BinaryOrErr =
47 object::createBinary(Filename);
49 return BinaryOrErr.takeError();
51 // Construct the object and allow it to take ownership of the binary.
52 object::OwningBinary<object::Binary> Binary = std::move(BinaryOrErr.get());
53 FileAnalysis Analysis(std::move(Binary));
55 Analysis.Object = dyn_cast<object::ObjectFile>(Analysis.Binary.getBinary());
57 return make_error<UnsupportedDisassembly>("Failed to cast object");
59 Analysis.ObjectTriple = Analysis.Object->makeTriple();
60 Analysis.Features = Analysis.Object->getFeatures();
62 // Init the rest of the object.
63 if (auto InitResponse = Analysis.initialiseDisassemblyMembers())
64 return std::move(InitResponse);
66 if (auto SectionParseResponse = Analysis.parseCodeSections())
67 return std::move(SectionParseResponse);
69 return std::move(Analysis);
72 FileAnalysis::FileAnalysis(object::OwningBinary<object::Binary> Binary)
73 : Binary(std::move(Binary)) {}
75 FileAnalysis::FileAnalysis(const Triple &ObjectTriple,
76 const SubtargetFeatures &Features)
77 : ObjectTriple(ObjectTriple), Features(Features) {}
80 FileAnalysis::getPrevInstructionSequential(const Instr &InstrMeta) const {
81 std::map<uint64_t, Instr>::const_iterator KV =
82 Instructions.find(InstrMeta.VMAddress);
83 if (KV == Instructions.end() || KV == Instructions.begin())
86 if (!(--KV)->second.Valid)
93 FileAnalysis::getNextInstructionSequential(const Instr &InstrMeta) const {
94 std::map<uint64_t, Instr>::const_iterator KV =
95 Instructions.find(InstrMeta.VMAddress);
96 if (KV == Instructions.end() || ++KV == Instructions.end())
99 if (!KV->second.Valid)
105 bool FileAnalysis::usesRegisterOperand(const Instr &InstrMeta) const {
106 for (const auto &Operand : InstrMeta.Instruction) {
113 const Instr *FileAnalysis::getInstruction(uint64_t Address) const {
114 const auto &InstrKV = Instructions.find(Address);
115 if (InstrKV == Instructions.end())
118 return &InstrKV->second;
121 const Instr &FileAnalysis::getInstructionOrDie(uint64_t Address) const {
122 const auto &InstrKV = Instructions.find(Address);
123 assert(InstrKV != Instructions.end() && "Address doesn't exist.");
124 return InstrKV->second;
127 bool FileAnalysis::isCFITrap(const Instr &InstrMeta) const {
128 return MII->getName(InstrMeta.Instruction.getOpcode()) == "TRAP";
131 bool FileAnalysis::canFallThrough(const Instr &InstrMeta) const {
132 if (!InstrMeta.Valid)
135 if (isCFITrap(InstrMeta))
138 const auto &InstrDesc = MII->get(InstrMeta.Instruction.getOpcode());
139 if (InstrDesc.mayAffectControlFlow(InstrMeta.Instruction, *RegisterInfo))
140 return InstrDesc.isConditionalBranch();
146 FileAnalysis::getDefiniteNextInstruction(const Instr &InstrMeta) const {
147 if (!InstrMeta.Valid)
150 if (isCFITrap(InstrMeta))
153 const auto &InstrDesc = MII->get(InstrMeta.Instruction.getOpcode());
154 const Instr *NextMetaPtr;
155 if (InstrDesc.mayAffectControlFlow(InstrMeta.Instruction, *RegisterInfo)) {
156 if (InstrDesc.isConditionalBranch())
160 if (!MIA->evaluateBranch(InstrMeta.Instruction, InstrMeta.VMAddress,
161 InstrMeta.InstructionSize, Target))
164 NextMetaPtr = getInstruction(Target);
167 getInstruction(InstrMeta.VMAddress + InstrMeta.InstructionSize);
170 if (!NextMetaPtr || !NextMetaPtr->Valid)
176 std::set<const Instr *>
177 FileAnalysis::getDirectControlFlowXRefs(const Instr &InstrMeta) const {
178 std::set<const Instr *> CFCrossReferences;
179 const Instr *PrevInstruction = getPrevInstructionSequential(InstrMeta);
181 if (PrevInstruction && canFallThrough(*PrevInstruction))
182 CFCrossReferences.insert(PrevInstruction);
184 const auto &TargetRefsKV = StaticBranchTargetings.find(InstrMeta.VMAddress);
185 if (TargetRefsKV == StaticBranchTargetings.end())
186 return CFCrossReferences;
188 for (uint64_t SourceInstrAddress : TargetRefsKV->second) {
189 const auto &SourceInstrKV = Instructions.find(SourceInstrAddress);
190 if (SourceInstrKV == Instructions.end()) {
191 errs() << "Failed to find source instruction at address "
192 << format_hex(SourceInstrAddress, 2)
193 << " for the cross-reference to instruction at address "
194 << format_hex(InstrMeta.VMAddress, 2) << ".\n";
198 CFCrossReferences.insert(&SourceInstrKV->second);
201 return CFCrossReferences;
204 const std::set<uint64_t> &FileAnalysis::getIndirectInstructions() const {
205 return IndirectInstructions;
208 const MCRegisterInfo *FileAnalysis::getRegisterInfo() const {
209 return RegisterInfo.get();
212 const MCInstrInfo *FileAnalysis::getMCInstrInfo() const { return MII.get(); }
214 const MCInstrAnalysis *FileAnalysis::getMCInstrAnalysis() const {
218 Error FileAnalysis::initialiseDisassemblyMembers() {
219 std::string TripleName = ObjectTriple.getTriple();
222 std::string ErrorString;
225 TargetRegistry::lookupTarget(ArchName, ObjectTriple, ErrorString);
227 return make_error<UnsupportedDisassembly>(
228 (Twine("Couldn't find target \"") + ObjectTriple.getTriple() +
229 "\", failed with error: " + ErrorString).str());
231 RegisterInfo.reset(ObjectTarget->createMCRegInfo(TripleName));
233 return make_error<UnsupportedDisassembly>(
234 "Failed to initialise RegisterInfo.");
236 AsmInfo.reset(ObjectTarget->createMCAsmInfo(*RegisterInfo, TripleName));
238 return make_error<UnsupportedDisassembly>("Failed to initialise AsmInfo.");
240 SubtargetInfo.reset(ObjectTarget->createMCSubtargetInfo(
241 TripleName, MCPU, Features.getString()));
243 return make_error<UnsupportedDisassembly>(
244 "Failed to initialise SubtargetInfo.");
246 MII.reset(ObjectTarget->createMCInstrInfo());
248 return make_error<UnsupportedDisassembly>("Failed to initialise MII.");
250 Context.reset(new MCContext(AsmInfo.get(), RegisterInfo.get(), &MOFI));
253 ObjectTarget->createMCDisassembler(*SubtargetInfo, *Context));
256 return make_error<UnsupportedDisassembly>(
257 "No disassembler available for target");
259 MIA.reset(ObjectTarget->createMCInstrAnalysis(MII.get()));
261 Printer.reset(ObjectTarget->createMCInstPrinter(
262 ObjectTriple, AsmInfo->getAssemblerDialect(), *AsmInfo, *MII,
265 return Error::success();
268 Error FileAnalysis::parseCodeSections() {
269 for (const object::SectionRef &Section : Object->sections()) {
270 // Ensure only executable sections get analysed.
271 if (!(object::ELFSectionRef(Section).getFlags() & ELF::SHF_EXECINSTR))
274 StringRef SectionContents;
275 if (Section.getContents(SectionContents))
276 return make_error<StringError>("Failed to retrieve section contents",
277 inconvertibleErrorCode());
279 ArrayRef<uint8_t> SectionBytes((const uint8_t *)SectionContents.data(),
281 parseSectionContents(SectionBytes, Section.getAddress());
283 return Error::success();
286 void FileAnalysis::parseSectionContents(ArrayRef<uint8_t> SectionBytes,
287 uint64_t SectionAddress) {
290 uint64_t InstructionSize;
292 for (uint64_t Byte = 0; Byte < SectionBytes.size();) {
293 bool ValidInstruction =
294 Disassembler->getInstruction(Instruction, InstructionSize,
295 SectionBytes.drop_front(Byte), 0, nulls(),
296 outs()) == MCDisassembler::Success;
298 Byte += InstructionSize;
300 uint64_t VMAddress = SectionAddress + Byte - InstructionSize;
301 InstrMeta.Instruction = Instruction;
302 InstrMeta.VMAddress = VMAddress;
303 InstrMeta.InstructionSize = InstructionSize;
304 InstrMeta.Valid = ValidInstruction;
305 addInstruction(InstrMeta);
307 if (!ValidInstruction)
310 // Skip additional parsing for instructions that do not affect the control
312 const auto &InstrDesc = MII->get(Instruction.getOpcode());
313 if (!InstrDesc.mayAffectControlFlow(Instruction, *RegisterInfo))
317 if (MIA->evaluateBranch(Instruction, VMAddress, InstructionSize, Target)) {
318 // If the target can be evaluated, it's not indirect.
319 StaticBranchTargetings[Target].push_back(VMAddress);
323 if (!usesRegisterOperand(InstrMeta))
326 IndirectInstructions.insert(VMAddress);
330 void FileAnalysis::addInstruction(const Instr &Instruction) {
332 Instructions.insert(std::make_pair(Instruction.VMAddress, Instruction));
334 errs() << "Failed to add instruction at address "
335 << format_hex(Instruction.VMAddress, 2)
336 << ": Instruction at this address already exists.\n";
341 UnsupportedDisassembly::UnsupportedDisassembly(StringRef Text) : Text(Text) {}
343 char UnsupportedDisassembly::ID;
344 void UnsupportedDisassembly::log(raw_ostream &OS) const {
345 OS << "Could not initialise disassembler: " << Text;
348 std::error_code UnsupportedDisassembly::convertToErrorCode() const {
349 return std::error_code();
352 } // namespace cfi_verify