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