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