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