1 //===-EDDisassembler.cpp - LLVM Enhanced Disassembler ---------------------===//
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 // This file implements the Enhanced Disassembly library's disassembler class.
11 // The disassembler is responsible for vending individual instructions according
12 // to a given architecture and disassembly syntax.
14 //===----------------------------------------------------------------------===//
16 #include "EDDisassembler.h"
19 #include "llvm/ADT/OwningPtr.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCDisassembler.h"
24 #include "llvm/MC/MCExpr.h"
25 #include "llvm/MC/MCInst.h"
26 #include "llvm/MC/MCInstPrinter.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCParser/AsmLexer.h"
29 #include "llvm/MC/MCParser/AsmParser.h"
30 #include "llvm/MC/MCParser/MCAsmParser.h"
31 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/MemoryObject.h"
34 #include "llvm/Support/SourceMgr.h"
35 #include "llvm/Target/TargetAsmLexer.h"
36 #include "llvm/Target/TargetAsmParser.h"
37 #include "llvm/Target/TargetRegistry.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSelect.h"
43 #include "../../lib/Target/X86/X86GenEDInfo.inc"
47 #include "../../lib/Target/ARM/ARMGenEDInfo.inc"
52 bool EDDisassembler::sInitialized = false;
53 EDDisassembler::DisassemblerMap_t EDDisassembler::sDisassemblers;
56 Triple::ArchType Arch;
61 static struct InfoMap infomap[] = {
63 { Triple::x86, "i386-unknown-unknown", instInfoX86 },
64 { Triple::x86_64, "x86_64-unknown-unknown", instInfoX86 },
67 { Triple::arm, "arm-unknown-unknown", instInfoARM },
68 { Triple::thumb, "thumb-unknown-unknown", instInfoARM },
70 { Triple::InvalidArch, NULL, NULL }
73 /// infoFromArch - Returns the InfoMap corresponding to a given architecture,
74 /// or NULL if there is an error
76 /// @arg arch - The Triple::ArchType for the desired architecture
77 static const InfoMap *infoFromArch(Triple::ArchType arch) {
78 unsigned int infoIndex;
80 for (infoIndex = 0; infomap[infoIndex].String != NULL; ++infoIndex) {
81 if (arch == infomap[infoIndex].Arch)
82 return &infomap[infoIndex];
88 /// getLLVMSyntaxVariant - gets the constant to use to get an assembly printer
89 /// for the desired assembly syntax, suitable for passing to
90 /// Target::createMCInstPrinter()
92 /// @arg arch - The target architecture
93 /// @arg syntax - The assembly syntax in sd form
94 static int getLLVMSyntaxVariant(Triple::ArchType arch,
95 EDAssemblySyntax_t syntax) {
99 // Mappings below from X86AsmPrinter.cpp
100 case kEDAssemblySyntaxX86ATT:
101 if (arch == Triple::x86 || arch == Triple::x86_64)
105 case kEDAssemblySyntaxX86Intel:
106 if (arch == Triple::x86 || arch == Triple::x86_64)
110 case kEDAssemblySyntaxARMUAL:
111 if (arch == Triple::arm || arch == Triple::thumb)
118 #define BRINGUP_TARGET(tgt) \
119 LLVMInitialize##tgt##TargetInfo(); \
120 LLVMInitialize##tgt##Target(); \
121 LLVMInitialize##tgt##AsmPrinter(); \
122 LLVMInitialize##tgt##AsmParser(); \
123 LLVMInitialize##tgt##Disassembler();
125 void EDDisassembler::initialize() {
139 #undef BRINGUP_TARGET
141 EDDisassembler *EDDisassembler::getDisassembler(Triple::ArchType arch,
142 EDAssemblySyntax_t syntax) {
147 EDDisassembler::DisassemblerMap_t::iterator i = sDisassemblers.find(key);
149 if (i != sDisassemblers.end()) {
152 EDDisassembler* sdd = new EDDisassembler(key);
158 sDisassemblers[key] = sdd;
166 EDDisassembler *EDDisassembler::getDisassembler(StringRef str,
167 EDAssemblySyntax_t syntax) {
170 return getDisassembler(triple.getArch(), syntax);
173 EDDisassembler::EDDisassembler(CPUKey &key) :
176 ErrorStream(nulls()),
178 const InfoMap *infoMap = infoFromArch(key.Arch);
183 InstInfos = infoMap->Info;
185 const char *triple = infoMap->String;
187 LLVMSyntaxVariant = getLLVMSyntaxVariant(key.Arch, key.Syntax);
189 if (LLVMSyntaxVariant < 0)
192 std::string tripleString(triple);
193 std::string errorString;
195 Tgt = TargetRegistry::lookupTarget(tripleString,
201 std::string featureString;
203 OwningPtr<const TargetMachine>
204 targetMachine(Tgt->createTargetMachine(tripleString,
207 const TargetRegisterInfo *registerInfo = targetMachine->getRegisterInfo();
212 initMaps(*registerInfo);
214 AsmInfo.reset(Tgt->createAsmInfo(tripleString));
219 Disassembler.reset(Tgt->createMCDisassembler());
224 InstString.reset(new std::string);
225 InstStream.reset(new raw_string_ostream(*InstString));
226 InstPrinter.reset(Tgt->createMCInstPrinter(LLVMSyntaxVariant, *AsmInfo));
231 GenericAsmLexer.reset(new AsmLexer(*AsmInfo));
232 SpecificAsmLexer.reset(Tgt->createAsmLexer(*AsmInfo));
233 SpecificAsmLexer->InstallLexer(*GenericAsmLexer);
235 InstInfos = infoMap->Info;
237 initMaps(*targetMachine->getRegisterInfo());
242 EDDisassembler::~EDDisassembler() {
248 /// EDMemoryObject - a subclass of MemoryObject that allows use of a callback
249 /// as provided by the sd interface. See MemoryObject.
250 class EDMemoryObject : public llvm::MemoryObject {
252 EDByteReaderCallback Callback;
255 EDMemoryObject(EDByteReaderCallback callback,
256 void *arg) : Callback(callback), Arg(arg) { }
257 ~EDMemoryObject() { }
258 uint64_t getBase() const { return 0x0; }
259 uint64_t getExtent() const { return (uint64_t)-1; }
260 int readByte(uint64_t address, uint8_t *ptr) const {
264 if (Callback(ptr, address, Arg))
272 EDInst *EDDisassembler::createInst(EDByteReaderCallback byteReader,
275 EDMemoryObject memoryObject(byteReader, arg);
277 MCInst* inst = new MCInst;
280 if (!Disassembler->getInstruction(*inst,
288 const InstInfo *thisInstInfo;
290 thisInstInfo = &InstInfos[inst->getOpcode()];
292 EDInst* sdInst = new EDInst(inst, byteSize, *this, thisInstInfo);
297 void EDDisassembler::initMaps(const TargetRegisterInfo ®isterInfo) {
298 unsigned numRegisters = registerInfo.getNumRegs();
299 unsigned registerIndex;
301 for (registerIndex = 0; registerIndex < numRegisters; ++registerIndex) {
302 const char* registerName = registerInfo.get(registerIndex).Name;
304 RegVec.push_back(registerName);
305 RegRMap[registerName] = registerIndex;
314 stackPointers.insert(registerIDWithName("SP"));
315 stackPointers.insert(registerIDWithName("ESP"));
316 stackPointers.insert(registerIDWithName("RSP"));
318 programCounters.insert(registerIDWithName("IP"));
319 programCounters.insert(registerIDWithName("EIP"));
320 programCounters.insert(registerIDWithName("RIP"));
326 stackPointers.insert(registerIDWithName("SP"));
328 programCounters.insert(registerIDWithName("PC"));
334 const char *EDDisassembler::nameWithRegisterID(unsigned registerID) const {
335 if (registerID >= RegVec.size())
338 return RegVec[registerID].c_str();
341 unsigned EDDisassembler::registerIDWithName(const char *name) const {
342 regrmap_t::const_iterator iter = RegRMap.find(std::string(name));
343 if (iter == RegRMap.end())
346 return (*iter).second;
349 bool EDDisassembler::registerIsStackPointer(unsigned registerID) {
350 return (stackPointers.find(registerID) != stackPointers.end());
353 bool EDDisassembler::registerIsProgramCounter(unsigned registerID) {
354 return (programCounters.find(registerID) != programCounters.end());
357 int EDDisassembler::printInst(std::string &str, MCInst &inst) {
358 PrinterMutex.acquire();
360 InstPrinter->printInst(&inst, *InstStream);
365 PrinterMutex.release();
370 int EDDisassembler::parseInst(SmallVectorImpl<MCParsedAsmOperand*> &operands,
371 SmallVectorImpl<AsmToken> &tokens,
372 const std::string &str) {
385 const char *cStr = str.c_str();
386 MemoryBuffer *buf = MemoryBuffer::getMemBuffer(cStr, cStr + strlen(cStr));
392 sourceMgr.AddNewSourceBuffer(buf, SMLoc()); // ownership of buf handed over
393 MCContext context(*AsmInfo);
394 OwningPtr<MCStreamer> streamer(createNullStreamer(context));
395 AsmParser genericParser(sourceMgr, context, *streamer, *AsmInfo);
396 OwningPtr<TargetAsmParser> TargetParser(Tgt->createAsmParser(genericParser));
398 AsmToken OpcodeToken = genericParser.Lex();
399 genericParser.Lex(); // consume next token, because specificParser expects us to
401 if (OpcodeToken.is(AsmToken::Identifier)) {
402 instName = OpcodeToken.getString();
403 instLoc = OpcodeToken.getLoc();
404 if (TargetParser->ParseInstruction(instName, instLoc, operands))
410 ParserMutex.acquire();
413 GenericAsmLexer->setBuffer(buf);
415 while (SpecificAsmLexer->Lex(),
416 SpecificAsmLexer->isNot(AsmToken::Eof) &&
417 SpecificAsmLexer->isNot(AsmToken::EndOfStatement)) {
418 if (SpecificAsmLexer->is(AsmToken::Error)) {
422 tokens.push_back(SpecificAsmLexer->getTok());
426 ParserMutex.release();
431 int EDDisassembler::llvmSyntaxVariant() const {
432 return LLVMSyntaxVariant;