Pass an ArrayRef to MCDisassembler::getInstruction.
[oota-llvm.git] / tools / llvm-mc / Disassembler.cpp
1 //===- Disassembler.cpp - Disassembler for hex strings --------------------===//
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 class implements the disassembler of strings of bytes written in
11 // hexadecimal, from standard input or from a file.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "Disassembler.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/MC/MCAsmInfo.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCDisassembler.h"
20 #include "llvm/MC/MCInst.h"
21 #include "llvm/MC/MCRegisterInfo.h"
22 #include "llvm/MC/MCStreamer.h"
23 #include "llvm/MC/MCSubtargetInfo.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/StringRefMemoryObject.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/TargetRegistry.h"
28 #include "llvm/Support/raw_ostream.h"
29
30 using namespace llvm;
31
32 typedef std::pair<std::vector<unsigned char>, std::vector<const char *>>
33     ByteArrayTy;
34
35 static bool PrintInsts(const MCDisassembler &DisAsm,
36                        const ByteArrayTy &Bytes,
37                        SourceMgr &SM, raw_ostream &Out,
38                        MCStreamer &Streamer, bool InAtomicBlock,
39                        const MCSubtargetInfo &STI) {
40   // Wrap the vector in a MemoryObject.
41   ArrayRef<uint8_t> Data(Bytes.first.data(), Bytes.first.size());
42
43   // Disassemble it to strings.
44   uint64_t Size;
45   uint64_t Index;
46
47   for (Index = 0; Index < Bytes.first.size(); Index += Size) {
48     MCInst Inst;
49
50     MCDisassembler::DecodeStatus S;
51     S = DisAsm.getInstruction(Inst, Size, Data.slice(Index), Index,
52                               /*REMOVE*/ nulls(), nulls());
53     switch (S) {
54     case MCDisassembler::Fail:
55       SM.PrintMessage(SMLoc::getFromPointer(Bytes.second[Index]),
56                       SourceMgr::DK_Warning,
57                       "invalid instruction encoding");
58       // Don't try to resynchronise the stream in a block
59       if (InAtomicBlock)
60         return true;
61
62       if (Size == 0)
63         Size = 1; // skip illegible bytes
64
65       break;
66
67     case MCDisassembler::SoftFail:
68       SM.PrintMessage(SMLoc::getFromPointer(Bytes.second[Index]),
69                       SourceMgr::DK_Warning,
70                       "potentially undefined instruction encoding");
71       // Fall through
72
73     case MCDisassembler::Success:
74       Streamer.EmitInstruction(Inst, STI);
75       break;
76     }
77   }
78
79   return false;
80 }
81
82 static bool SkipToToken(StringRef &Str) {
83   for (;;) {
84     if (Str.empty())
85       return false;
86
87     // Strip horizontal whitespace and commas.
88     if (size_t Pos = Str.find_first_not_of(" \t\r\n,")) {
89       Str = Str.substr(Pos);
90       continue;
91     }
92
93     // If this is the start of a comment, remove the rest of the line.
94     if (Str[0] == '#') {
95         Str = Str.substr(Str.find_first_of('\n'));
96       continue;
97     }
98     return true;
99   }
100 }
101
102
103 static bool ByteArrayFromString(ByteArrayTy &ByteArray,
104                                 StringRef &Str,
105                                 SourceMgr &SM) {
106   while (SkipToToken(Str)) {
107     // Handled by higher level
108     if (Str[0] == '[' || Str[0] == ']')
109       return false;
110
111     // Get the current token.
112     size_t Next = Str.find_first_of(" \t\n\r,#[]");
113     StringRef Value = Str.substr(0, Next);
114
115     // Convert to a byte and add to the byte vector.
116     unsigned ByteVal;
117     if (Value.getAsInteger(0, ByteVal) || ByteVal > 255) {
118       // If we have an error, print it and skip to the end of line.
119       SM.PrintMessage(SMLoc::getFromPointer(Value.data()), SourceMgr::DK_Error,
120                       "invalid input token");
121       Str = Str.substr(Str.find('\n'));
122       ByteArray.first.clear();
123       ByteArray.second.clear();
124       continue;
125     }
126
127     ByteArray.first.push_back(ByteVal);
128     ByteArray.second.push_back(Value.data());
129     Str = Str.substr(Next);
130   }
131
132   return false;
133 }
134
135 int Disassembler::disassemble(const Target &T,
136                               const std::string &Triple,
137                               MCSubtargetInfo &STI,
138                               MCStreamer &Streamer,
139                               MemoryBuffer &Buffer,
140                               SourceMgr &SM,
141                               raw_ostream &Out) {
142
143   std::unique_ptr<const MCRegisterInfo> MRI(T.createMCRegInfo(Triple));
144   if (!MRI) {
145     errs() << "error: no register info for target " << Triple << "\n";
146     return -1;
147   }
148
149   std::unique_ptr<const MCAsmInfo> MAI(T.createMCAsmInfo(*MRI, Triple));
150   if (!MAI) {
151     errs() << "error: no assembly info for target " << Triple << "\n";
152     return -1;
153   }
154
155   // Set up the MCContext for creating symbols and MCExpr's.
156   MCContext Ctx(MAI.get(), MRI.get(), nullptr);
157
158   std::unique_ptr<const MCDisassembler> DisAsm(
159     T.createMCDisassembler(STI, Ctx));
160   if (!DisAsm) {
161     errs() << "error: no disassembler for target " << Triple << "\n";
162     return -1;
163   }
164
165   // Set up initial section manually here
166   Streamer.InitSections(false);
167
168   bool ErrorOccurred = false;
169
170   // Convert the input to a vector for disassembly.
171   ByteArrayTy ByteArray;
172   StringRef Str = Buffer.getBuffer();
173   bool InAtomicBlock = false;
174
175   while (SkipToToken(Str)) {
176     ByteArray.first.clear();
177     ByteArray.second.clear();
178
179     if (Str[0] == '[') {
180       if (InAtomicBlock) {
181         SM.PrintMessage(SMLoc::getFromPointer(Str.data()), SourceMgr::DK_Error,
182                         "nested atomic blocks make no sense");
183         ErrorOccurred = true;
184       }
185       InAtomicBlock = true;
186       Str = Str.drop_front();
187       continue;
188     } else if (Str[0] == ']') {
189       if (!InAtomicBlock) {
190         SM.PrintMessage(SMLoc::getFromPointer(Str.data()), SourceMgr::DK_Error,
191                         "attempt to close atomic block without opening");
192         ErrorOccurred = true;
193       }
194       InAtomicBlock = false;
195       Str = Str.drop_front();
196       continue;
197     }
198
199     // It's a real token, get the bytes and emit them
200     ErrorOccurred |= ByteArrayFromString(ByteArray, Str, SM);
201
202     if (!ByteArray.first.empty())
203       ErrorOccurred |= PrintInsts(*DisAsm, ByteArray, SM, Out, Streamer,
204                                   InAtomicBlock, STI);
205   }
206
207   if (InAtomicBlock) {
208     SM.PrintMessage(SMLoc::getFromPointer(Str.data()), SourceMgr::DK_Error,
209                     "unclosed atomic block");
210     ErrorOccurred = true;
211   }
212
213   return ErrorOccurred;
214 }