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 "llvm/ADT/OwningPtr.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCDisassembler.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCStreamer.h"
25 #include "llvm/MC/MCParser/AsmLexer.h"
26 #include "llvm/MC/MCParser/AsmParser.h"
27 #include "llvm/MC/MCParser/MCAsmParser.h"
28 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/MemoryObject.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Target/TargetAsmLexer.h"
33 #include "llvm/Target/TargetAsmParser.h"
34 #include "llvm/Target/TargetRegistry.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
37 #include "llvm/Target/TargetSelect.h"
39 #include "EDDisassembler.h"
42 #include "../../lib/Target/X86/X86GenEDInfo.inc"
46 bool EDDisassembler::sInitialized = false;
47 EDDisassembler::DisassemblerMap_t EDDisassembler::sDisassemblers;
50 Triple::ArchType Arch;
55 static struct InfoMap infomap[] = {
56 { Triple::x86, "i386-unknown-unknown", instInfoX86 },
57 { Triple::x86_64, "x86_64-unknown-unknown", instInfoX86 },
58 { Triple::InvalidArch, NULL, NULL }
61 /// infoFromArch - Returns the InfoMap corresponding to a given architecture,
62 /// or NULL if there is an error
64 /// @arg arch - The Triple::ArchType for the desired architecture
65 static const InfoMap *infoFromArch(Triple::ArchType arch) {
66 unsigned int infoIndex;
68 for (infoIndex = 0; infomap[infoIndex].String != NULL; ++infoIndex) {
69 if(arch == infomap[infoIndex].Arch)
70 return &infomap[infoIndex];
76 /// getLLVMSyntaxVariant - gets the constant to use to get an assembly printer
77 /// for the desired assembly syntax, suitable for passing to
78 /// Target::createMCInstPrinter()
80 /// @arg arch - The target architecture
81 /// @arg syntax - The assembly syntax in sd form
82 static int getLLVMSyntaxVariant(Triple::ArchType arch,
83 EDAssemblySyntax_t syntax) {
87 // Mappings below from X86AsmPrinter.cpp
88 case kEDAssemblySyntaxX86ATT:
89 if (arch == Triple::x86 || arch == Triple::x86_64)
93 case kEDAssemblySyntaxX86Intel:
94 if (arch == Triple::x86 || arch == Triple::x86_64)
101 #define BRINGUP_TARGET(tgt) \
102 LLVMInitialize##tgt##TargetInfo(); \
103 LLVMInitialize##tgt##Target(); \
104 LLVMInitialize##tgt##AsmPrinter(); \
105 LLVMInitialize##tgt##AsmParser(); \
106 LLVMInitialize##tgt##Disassembler();
108 void EDDisassembler::initialize() {
117 #undef BRINGUP_TARGET
119 EDDisassembler *EDDisassembler::getDisassembler(Triple::ArchType arch,
120 EDAssemblySyntax_t syntax) {
125 EDDisassembler::DisassemblerMap_t::iterator i = sDisassemblers.find(key);
127 if (i != sDisassemblers.end()) {
131 EDDisassembler* sdd = new EDDisassembler(key);
137 sDisassemblers[key] = sdd;
145 EDDisassembler *EDDisassembler::getDisassembler(StringRef str,
146 EDAssemblySyntax_t syntax) {
149 return getDisassembler(triple.getArch(), syntax);
153 class EDAsmParser : public MCAsmParser {
156 OwningPtr<MCStreamer> Streamer;
158 // Mandatory functions
159 EDAsmParser(const MCAsmInfo &MAI) : Lexer(MAI) {
160 Streamer.reset(createNullStreamer(Context));
162 virtual ~EDAsmParser() { }
163 MCAsmLexer &getLexer() { return Lexer; }
164 MCContext &getContext() { return Context; }
165 MCStreamer &getStreamer() { return *Streamer; }
166 void Warning(SMLoc L, const Twine &Msg) { }
167 bool Error(SMLoc L, const Twine &Msg) { return true; }
168 const AsmToken &Lex() { return Lexer.Lex(); }
169 bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
170 AsmToken token = Lex();
171 if(token.isNot(AsmToken::Integer))
173 Res = MCConstantExpr::Create(token.getIntVal(), Context);
176 bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
177 assert(0 && "I can't ParseParenExpression()s!");
179 bool ParseAbsoluteExpression(int64_t &Res) {
180 assert(0 && "I can't ParseAbsoluteExpression()s!");
183 /// setBuffer - loads a buffer into the parser
184 /// @arg buf - The buffer to read tokens from
185 void setBuffer(const MemoryBuffer &buf) { Lexer.setBuffer(&buf); }
186 /// parseInstName - When the lexer is positioned befor an instruction
187 /// name (with possible intervening whitespace), reads past the name,
188 /// returning 0 on success and -1 on failure
189 /// @arg name - A reference to a string that is filled in with the
191 /// @arg loc - A reference to a location that is filled in with the
192 /// position of the instruction name
193 int parseInstName(StringRef &name, SMLoc &loc) {
194 AsmToken tok = Lexer.Lex();
195 if(tok.isNot(AsmToken::Identifier)) {
198 name = tok.getString();
205 EDDisassembler::EDDisassembler(CPUKey &key) :
206 Valid(false), ErrorString(), ErrorStream(ErrorString), Key(key) {
207 const InfoMap *infoMap = infoFromArch(key.Arch);
212 const char *triple = infoMap->String;
214 int syntaxVariant = getLLVMSyntaxVariant(key.Arch, key.Syntax);
216 if (syntaxVariant < 0)
219 std::string tripleString(triple);
220 std::string errorString;
222 Tgt = TargetRegistry::lookupTarget(tripleString,
228 std::string featureString;
230 OwningPtr<const TargetMachine>
231 targetMachine(Tgt->createTargetMachine(tripleString,
234 const TargetRegisterInfo *registerInfo = targetMachine->getRegisterInfo();
239 AsmInfo.reset(Tgt->createAsmInfo(tripleString));
244 Disassembler.reset(Tgt->createMCDisassembler());
249 InstString.reset(new std::string);
250 InstStream.reset(new raw_string_ostream(*InstString));
252 InstPrinter.reset(Tgt->createMCInstPrinter(syntaxVariant,
259 GenericAsmLexer.reset(new AsmLexer(*AsmInfo));
260 SpecificAsmLexer.reset(Tgt->createAsmLexer(*AsmInfo));
261 SpecificAsmLexer->InstallLexer(*GenericAsmLexer);
263 InstInfos = infoMap->Info;
268 EDDisassembler::~EDDisassembler() {
274 /// EDMemoryObject - a subclass of MemoryObject that allows use of a callback
275 /// as provided by the sd interface. See MemoryObject.
276 class EDMemoryObject : public llvm::MemoryObject {
278 EDByteReaderCallback Callback;
281 EDMemoryObject(EDByteReaderCallback callback,
282 void *arg) : Callback(callback), Arg(arg) { }
283 ~EDMemoryObject() { }
284 uint64_t getBase() const { return 0x0; }
285 uint64_t getExtent() const { return (uint64_t)-1; }
286 int readByte(uint64_t address, uint8_t *ptr) const {
290 if(Callback(ptr, address, Arg))
298 EDInst *EDDisassembler::createInst(EDByteReaderCallback byteReader,
301 EDMemoryObject memoryObject(byteReader, arg);
303 MCInst* inst = new MCInst;
306 if (!Disassembler->getInstruction(*inst,
315 const InstInfo *thisInstInfo = &InstInfos[inst->getOpcode()];
317 EDInst* sdInst = new EDInst(inst, byteSize, *this, thisInstInfo);
322 void EDDisassembler::initMaps(const TargetRegisterInfo ®isterInfo) {
323 unsigned numRegisters = registerInfo.getNumRegs();
324 unsigned registerIndex;
326 for (registerIndex = 0; registerIndex < numRegisters; ++registerIndex) {
327 const char* registerName = registerInfo.get(registerIndex).Name;
329 RegVec.push_back(registerName);
330 RegRMap[registerName] = registerIndex;
333 if (Key.Arch == Triple::x86 ||
334 Key.Arch == Triple::x86_64) {
335 stackPointers.insert(registerIDWithName("SP"));
336 stackPointers.insert(registerIDWithName("ESP"));
337 stackPointers.insert(registerIDWithName("RSP"));
339 programCounters.insert(registerIDWithName("IP"));
340 programCounters.insert(registerIDWithName("EIP"));
341 programCounters.insert(registerIDWithName("RIP"));
345 const char *EDDisassembler::nameWithRegisterID(unsigned registerID) const {
346 if (registerID >= RegVec.size())
349 return RegVec[registerID].c_str();
352 unsigned EDDisassembler::registerIDWithName(const char *name) const {
353 regrmap_t::const_iterator iter = RegRMap.find(std::string(name));
354 if (iter == RegRMap.end())
357 return (*iter).second;
360 bool EDDisassembler::registerIsStackPointer(unsigned registerID) {
361 return (stackPointers.find(registerID) != stackPointers.end());
364 bool EDDisassembler::registerIsProgramCounter(unsigned registerID) {
365 return (programCounters.find(registerID) != programCounters.end());
368 int EDDisassembler::printInst(std::string& str,
370 PrinterMutex.acquire();
372 InstPrinter->printInst(&inst);
377 PrinterMutex.release();
382 int EDDisassembler::parseInst(SmallVectorImpl<MCParsedAsmOperand*> &operands,
383 SmallVectorImpl<AsmToken> &tokens,
384 const std::string &str) {
387 const char *cStr = str.c_str();
388 MemoryBuffer *buf = MemoryBuffer::getMemBuffer(cStr, cStr + strlen(cStr));
394 sourceMgr.AddNewSourceBuffer(buf, SMLoc()); // ownership of buf handed over
396 OwningPtr<MCStreamer> streamer
397 (createNullStreamer(context));
398 AsmParser genericParser(sourceMgr, context, *streamer, *AsmInfo);
399 OwningPtr<TargetAsmParser> specificParser
400 (Tgt->createAsmParser(genericParser));
402 AsmToken OpcodeToken = genericParser.Lex();
404 if(OpcodeToken.is(AsmToken::Identifier)) {
405 instName = OpcodeToken.getString();
406 instLoc = OpcodeToken.getLoc();
407 if (specificParser->ParseInstruction(instName, instLoc, operands))
414 SmallVectorImpl<MCParsedAsmOperand*>::iterator oi;
416 for(oi = operands.begin(); oi != operands.end(); ++oi) {
417 printf("Operand start %p, end %p\n",
418 (*oi)->getStartLoc().getPointer(),
419 (*oi)->getEndLoc().getPointer());
422 ParserMutex.acquire();
425 GenericAsmLexer->setBuffer(buf);
427 while (SpecificAsmLexer->Lex(),
428 SpecificAsmLexer->isNot(AsmToken::Eof) &&
429 SpecificAsmLexer->isNot(AsmToken::EndOfStatement)) {
430 if (SpecificAsmLexer->is(AsmToken::Error)) {
434 tokens.push_back(SpecificAsmLexer->getTok());
438 ParserMutex.release();
443 int EDDisassembler::llvmSyntaxVariant() const {
444 return LLVMSyntaxVariant;