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