xref: /freebsd/contrib/llvm-project/llvm/tools/llvm-mc/Disassembler.cpp (revision e64bea71c21eb42e97aa615188ba91f6cce0d36d)
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/StringExtras.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/MCObjectFileInfo.h"
21 #include "llvm/MC/MCRegisterInfo.h"
22 #include "llvm/MC/MCStreamer.h"
23 #include "llvm/MC/MCSubtargetInfo.h"
24 #include "llvm/MC/TargetRegistry.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/TargetParser/Triple.h"
29 
30 using namespace llvm;
31 
32 typedef std::pair<std::vector<unsigned char>, std::vector<const char *>>
33     ByteArrayTy;
34 
PrintInsts(const MCDisassembler & DisAsm,const ByteArrayTy & Bytes,SourceMgr & SM,MCStreamer & Streamer,bool InAtomicBlock,const MCSubtargetInfo & STI)35 static bool PrintInsts(const MCDisassembler &DisAsm, const ByteArrayTy &Bytes,
36                        SourceMgr &SM, MCStreamer &Streamer, bool InAtomicBlock,
37                        const MCSubtargetInfo &STI) {
38   ArrayRef<uint8_t> Data(Bytes.first);
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     if (STI.getTargetTriple().getArch() == Triple::hexagon)
49       S = DisAsm.getInstructionBundle(Inst, Size, Data.slice(Index), Index,
50                                       nulls());
51     else
52       S = DisAsm.getInstruction(Inst, Size, Data.slice(Index), Index, 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       [[fallthrough]];
72 
73     case MCDisassembler::Success:
74       Streamer.emitInstruction(Inst, STI);
75       break;
76     }
77   }
78 
79   return false;
80 }
81 
SkipToToken(StringRef & Str)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 
byteArrayFromString(ByteArrayTy & ByteArray,StringRef & Str,SourceMgr & SM,bool HexBytes)102 static bool byteArrayFromString(ByteArrayTy &ByteArray, StringRef &Str,
103                                 SourceMgr &SM, bool HexBytes) {
104   while (SkipToToken(Str)) {
105     // Handled by higher level
106     if (Str[0] == '[' || Str[0] == ']')
107       return false;
108 
109     // Get the current token.
110     size_t Next = Str.find_first_of(" \t\n\r,#[]");
111     StringRef Value = Str.substr(0, Next);
112 
113     // Convert to a byte and add to the byte vector.
114     unsigned ByteVal;
115     if (HexBytes) {
116       if (Next < 2) {
117         SM.PrintMessage(SMLoc::getFromPointer(Value.data()),
118                         SourceMgr::DK_Error, "expected two hex digits");
119         Str = Str.substr(Next);
120         return true;
121       }
122       Next = 2;
123       unsigned C0 = hexDigitValue(Value[0]);
124       unsigned C1 = hexDigitValue(Value[1]);
125       if (C0 == -1u || C1 == -1u) {
126         SM.PrintMessage(SMLoc::getFromPointer(Value.data()),
127                         SourceMgr::DK_Error, "invalid input token");
128         Str = Str.substr(Next);
129         return true;
130       }
131       ByteVal = C0 * 16 + C1;
132     } else if (Value.getAsInteger(0, ByteVal) || ByteVal > 255) {
133       // If we have an error, print it and skip to the end of line.
134       SM.PrintMessage(SMLoc::getFromPointer(Value.data()), SourceMgr::DK_Error,
135                       "invalid input token");
136       Str = Str.substr(Str.find('\n'));
137       ByteArray.first.clear();
138       ByteArray.second.clear();
139       continue;
140     }
141 
142     ByteArray.first.push_back(ByteVal);
143     ByteArray.second.push_back(Value.data());
144     Str = Str.substr(Next);
145   }
146 
147   return false;
148 }
149 
disassemble(const Target & T,const std::string & Triple,MCSubtargetInfo & STI,MCStreamer & Streamer,MemoryBuffer & Buffer,SourceMgr & SM,MCContext & Ctx,const MCTargetOptions & MCOptions,bool HexBytes)150 int Disassembler::disassemble(const Target &T, const std::string &Triple,
151                               MCSubtargetInfo &STI, MCStreamer &Streamer,
152                               MemoryBuffer &Buffer, SourceMgr &SM,
153                               MCContext &Ctx, const MCTargetOptions &MCOptions,
154                               bool HexBytes) {
155   std::unique_ptr<const MCRegisterInfo> MRI(T.createMCRegInfo(Triple));
156   if (!MRI) {
157     errs() << "error: no register info for target " << Triple << "\n";
158     return -1;
159   }
160 
161   std::unique_ptr<const MCAsmInfo> MAI(
162       T.createMCAsmInfo(*MRI, Triple, MCOptions));
163   if (!MAI) {
164     errs() << "error: no assembly info for target " << Triple << "\n";
165     return -1;
166   }
167 
168   std::unique_ptr<const MCDisassembler> DisAsm(
169     T.createMCDisassembler(STI, Ctx));
170   if (!DisAsm) {
171     errs() << "error: no disassembler for target " << Triple << "\n";
172     return -1;
173   }
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, HexBytes);
208 
209     if (!ByteArray.first.empty())
210       ErrorOccurred |=
211           PrintInsts(*DisAsm, ByteArray, SM, Streamer, 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 }
222