Added the enhanced disassembly library's implementation and
[oota-llvm.git] / tools / ed / EDDisassembler.cpp
1 //===-EDDisassembler.cpp - LLVM Enhanced Disassembler ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
14 //===----------------------------------------------------------------------===//
15
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"
38
39 #include "EDDisassembler.h"
40 #include "EDInst.h"
41
42 #include "../../lib/Target/X86/X86GenEDInfo.inc"
43
44 using namespace llvm;
45
46 bool EDDisassembler::sInitialized = false;
47 EDDisassembler::DisassemblerMap_t EDDisassembler::sDisassemblers;
48
49 struct InfoMap {
50   Triple::ArchType Arch;
51   const char *String;
52   const InstInfo *Info;
53 };
54
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        }
59 };
60
61 /// infoFromArch - Returns the InfoMap corresponding to a given architecture,
62 ///   or NULL if there is an error
63 ///
64 /// @arg arch - The Triple::ArchType for the desired architecture
65 static const InfoMap *infoFromArch(Triple::ArchType arch) {
66   unsigned int infoIndex;
67   
68   for (infoIndex = 0; infomap[infoIndex].String != NULL; ++infoIndex) {
69     if(arch == infomap[infoIndex].Arch)
70       return &infomap[infoIndex];
71   }
72   
73   return NULL;
74 }
75
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()
79 ///
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) {
84   switch (syntax) {
85   default:
86     return -1;
87   // Mappings below from X86AsmPrinter.cpp
88   case kEDAssemblySyntaxX86ATT:
89     if (arch == Triple::x86 || arch == Triple::x86_64)
90       return 0;
91     else
92       return -1;
93   case kEDAssemblySyntaxX86Intel:
94     if (arch == Triple::x86 || arch == Triple::x86_64)
95       return 1;
96     else
97       return -1;
98   }
99 }
100
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();
107
108 void EDDisassembler::initialize() {
109   if (sInitialized)
110     return;
111   
112   sInitialized = true;
113   
114   BRINGUP_TARGET(X86)
115 }
116
117 #undef BRINGUP_TARGET
118
119 EDDisassembler *EDDisassembler::getDisassembler(Triple::ArchType arch,
120                                                 EDAssemblySyntax_t syntax) {
121   CPUKey key;
122   key.Arch = arch;
123   key.Syntax = syntax;
124   
125   EDDisassembler::DisassemblerMap_t::iterator i = sDisassemblers.find(key);
126   
127   if (i != sDisassemblers.end()) {
128     return i->second;
129   }
130   else {
131     EDDisassembler* sdd = new EDDisassembler(key);
132     if(!sdd->valid()) {
133       delete sdd;
134       return NULL;
135     }
136     
137     sDisassemblers[key] = sdd;
138     
139     return sdd;
140   }
141   
142   return NULL;
143 }
144
145 EDDisassembler *EDDisassembler::getDisassembler(StringRef str,
146                                                 EDAssemblySyntax_t syntax) {
147   Triple triple(str);
148   
149   return getDisassembler(triple.getArch(), syntax);
150 }
151
152 namespace {
153   class EDAsmParser : public MCAsmParser {
154     AsmLexer Lexer;
155     MCContext Context;
156     OwningPtr<MCStreamer> Streamer;
157   public:
158     // Mandatory functions
159     EDAsmParser(const MCAsmInfo &MAI) : Lexer(MAI) {
160       Streamer.reset(createNullStreamer(Context));
161     }
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))
172         return true;
173       Res = MCConstantExpr::Create(token.getIntVal(), Context);
174       return false;
175     }
176     bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
177       assert(0 && "I can't ParseParenExpression()s!");
178     }
179     bool ParseAbsoluteExpression(int64_t &Res) {
180       assert(0 && "I can't ParseAbsoluteExpression()s!");
181     }
182     
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
190     ///             instruction name
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)) {
196         return -1;
197       }
198       name = tok.getString();
199       loc = tok.getLoc();
200       return 0;
201     }
202   };
203 }
204
205 EDDisassembler::EDDisassembler(CPUKey &key) : 
206   Valid(false), ErrorString(), ErrorStream(ErrorString), Key(key) {
207   const InfoMap *infoMap = infoFromArch(key.Arch);
208   
209   if (!infoMap)
210     return;
211   
212   const char *triple = infoMap->String;
213   
214   int syntaxVariant = getLLVMSyntaxVariant(key.Arch, key.Syntax);
215   
216   if (syntaxVariant < 0)
217     return;
218   
219   std::string tripleString(triple);
220   std::string errorString;
221   
222   Tgt = TargetRegistry::lookupTarget(tripleString, 
223                                      errorString);
224   
225   if (!Tgt)
226     return;
227   
228   std::string featureString;
229   
230   OwningPtr<const TargetMachine>
231     targetMachine(Tgt->createTargetMachine(tripleString,
232                                            featureString));
233   
234   const TargetRegisterInfo *registerInfo = targetMachine->getRegisterInfo();
235   
236   if (!registerInfo)
237     return;
238   
239   AsmInfo.reset(Tgt->createAsmInfo(tripleString));
240   
241   if (!AsmInfo)
242     return;
243   
244   Disassembler.reset(Tgt->createMCDisassembler());
245   
246   if (!Disassembler)
247     return;
248   
249   InstString.reset(new std::string);
250   InstStream.reset(new raw_string_ostream(*InstString));
251   
252   InstPrinter.reset(Tgt->createMCInstPrinter(syntaxVariant,
253                                                 *AsmInfo,
254                                                 *InstStream));
255   
256   if (!InstPrinter)
257     return;
258     
259   GenericAsmLexer.reset(new AsmLexer(*AsmInfo));
260   SpecificAsmLexer.reset(Tgt->createAsmLexer(*AsmInfo));
261   SpecificAsmLexer->InstallLexer(*GenericAsmLexer);
262                           
263   InstInfos = infoMap->Info;
264     
265   Valid = true;
266 }
267
268 EDDisassembler::~EDDisassembler() {
269   if(!valid())
270     return;
271 }
272
273 namespace {
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 {
277   private:
278     EDByteReaderCallback Callback;
279     void *Arg;
280   public:
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 {
287       if(!Callback)
288         return -1;
289       
290       if(Callback(ptr, address, Arg))
291         return -1;
292       
293       return 0;
294     }
295   };
296 }
297
298 EDInst *EDDisassembler::createInst(EDByteReaderCallback byteReader, 
299                                    uint64_t address, 
300                                    void *arg) {
301   EDMemoryObject memoryObject(byteReader, arg);
302   
303   MCInst* inst = new MCInst;
304   uint64_t byteSize;
305   
306   if (!Disassembler->getInstruction(*inst,
307                                     byteSize,
308                                     memoryObject,
309                                     address,
310                                     ErrorStream)) {
311     delete inst;
312     return NULL;
313   }
314   else {
315     const InstInfo *thisInstInfo = &InstInfos[inst->getOpcode()];
316     
317     EDInst* sdInst = new EDInst(inst, byteSize, *this, thisInstInfo);
318     return sdInst;
319   }
320 }
321
322 void EDDisassembler::initMaps(const TargetRegisterInfo &registerInfo) {
323   unsigned numRegisters = registerInfo.getNumRegs();
324   unsigned registerIndex;
325   
326   for (registerIndex = 0; registerIndex < numRegisters; ++registerIndex) {
327     const char* registerName = registerInfo.get(registerIndex).Name;
328     
329     RegVec.push_back(registerName);
330     RegRMap[registerName] = registerIndex;
331   }
332   
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"));
338     
339     programCounters.insert(registerIDWithName("IP"));
340     programCounters.insert(registerIDWithName("EIP"));
341     programCounters.insert(registerIDWithName("RIP"));
342   }
343 }
344
345 const char *EDDisassembler::nameWithRegisterID(unsigned registerID) const {
346   if (registerID >= RegVec.size())
347     return NULL;
348   else
349     return RegVec[registerID].c_str();
350 }
351
352 unsigned EDDisassembler::registerIDWithName(const char *name) const {
353   regrmap_t::const_iterator iter = RegRMap.find(std::string(name));
354   if (iter == RegRMap.end())
355     return 0;
356   else
357     return (*iter).second;
358 }
359
360 bool EDDisassembler::registerIsStackPointer(unsigned registerID) {
361   return (stackPointers.find(registerID) != stackPointers.end());
362 }
363
364 bool EDDisassembler::registerIsProgramCounter(unsigned registerID) {
365   return (programCounters.find(registerID) != programCounters.end());
366 }
367
368 int EDDisassembler::printInst(std::string& str,
369                               MCInst& inst) {
370   PrinterMutex.acquire();
371   
372   InstPrinter->printInst(&inst);
373   InstStream->flush();
374   str = *InstString;
375   InstString->clear();
376   
377   PrinterMutex.release();
378   
379   return 0;
380 }
381
382 int EDDisassembler::parseInst(SmallVectorImpl<MCParsedAsmOperand*> &operands,
383                               SmallVectorImpl<AsmToken> &tokens,
384                               const std::string &str) {
385   int ret = 0;
386   
387   const char *cStr = str.c_str();
388   MemoryBuffer *buf = MemoryBuffer::getMemBuffer(cStr, cStr + strlen(cStr));
389   
390   StringRef instName;
391   SMLoc instLoc;
392   
393   SourceMgr sourceMgr;
394   sourceMgr.AddNewSourceBuffer(buf, SMLoc()); // ownership of buf handed over
395   MCContext context;
396   OwningPtr<MCStreamer> streamer
397     (createNullStreamer(context));
398   AsmParser genericParser(sourceMgr, context, *streamer, *AsmInfo);
399   OwningPtr<TargetAsmParser> specificParser
400     (Tgt->createAsmParser(genericParser));
401   
402   AsmToken OpcodeToken = genericParser.Lex();
403   
404   if(OpcodeToken.is(AsmToken::Identifier)) {
405     instName = OpcodeToken.getString();
406     instLoc = OpcodeToken.getLoc();
407     if (specificParser->ParseInstruction(instName, instLoc, operands))
408       ret = -1;
409   }
410   else {
411     ret = -1;
412   }
413   
414   SmallVectorImpl<MCParsedAsmOperand*>::iterator oi;
415   
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());
420   }
421   
422   ParserMutex.acquire();
423   
424   if (!ret) {
425     GenericAsmLexer->setBuffer(buf);
426   
427     while (SpecificAsmLexer->Lex(),
428            SpecificAsmLexer->isNot(AsmToken::Eof) &&
429            SpecificAsmLexer->isNot(AsmToken::EndOfStatement)) {
430       if (SpecificAsmLexer->is(AsmToken::Error)) {
431         ret = -1;
432         break;
433       }
434       tokens.push_back(SpecificAsmLexer->getTok());
435     }
436   }
437
438   ParserMutex.release();
439   
440   return ret;
441 }
442
443 int EDDisassembler::llvmSyntaxVariant() const {
444   return LLVMSyntaxVariant;
445 }