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