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 while (SkipToToken(Str)) {
120 // Handled by higher level
121 if (Str[0] == '[' || Str[0] == ']')
122 return false;
123
124 // Get the current token.
125 size_t Next = Str.find_first_of(Chars: " \t\n\r,#[]");
126 StringRef Value = Str.substr(Start: 0, N: Next);
127
128 // Convert to a byte and add to the byte vector.
129 unsigned ByteVal;
130 if (HexBytes) {
131 if (Next < 2) {
132 SM.PrintMessage(Loc: SMLoc::getFromPointer(Ptr: Value.data()),
133 Kind: SourceMgr::DK_Error, Msg: "expected two hex digits");
134 Str = Str.substr(Start: Next);
135 return true;
136 }
137 Next = 2;
138 unsigned C0 = hexDigitValue(C: Value[0]);
139 unsigned C1 = hexDigitValue(C: Value[1]);
140 if (C0 == -1u || C1 == -1u) {
141 SM.PrintMessage(Loc: SMLoc::getFromPointer(Ptr: Value.data()),
142 Kind: SourceMgr::DK_Error, Msg: "invalid input token");
143 Str = Str.substr(Start: Next);
144 return true;
145 }
146 ByteVal = C0 * 16 + C1;
147 } else if (Value.getAsInteger(Radix: 0, Result&: ByteVal) || ByteVal > 255) {
148 // If we have an error, print it and skip to the end of line.
149 SM.PrintMessage(Loc: SMLoc::getFromPointer(Ptr: Value.data()), Kind: SourceMgr::DK_Error,
150 Msg: "invalid input token");
151 Str = Str.substr(Start: Str.find(C: '\n'));
152 ByteArray.first.clear();
153 ByteArray.second.clear();
154 continue;
155 }
156
157 ByteArray.first.push_back(x: ByteVal);
158 ByteArray.second.push_back(x: Value.data());
159 Str = Str.substr(Start: Next);
160 }
161
162 return false;
163}
164
165int Disassembler::disassemble(const Target &T, MCSubtargetInfo &STI,
166 MCStreamer &Streamer, MemoryBuffer &Buffer,
167 SourceMgr &SM, MCContext &Ctx, bool HexBytes,
168 unsigned NumBenchmarkRuns) {
169 const Triple &TheTriple = STI.getTargetTriple();
170
171 std::unique_ptr<const MCDisassembler> DisAsm(
172 T.createMCDisassembler(STI, Ctx));
173 if (!DisAsm) {
174 errs() << "error: no disassembler for target " << TheTriple.str() << '\n';
175 return -1;
176 }
177
178 bool ErrorOccurred = false;
179
180 // Convert the input to a vector for disassembly.
181 ByteArrayTy ByteArray;
182 StringRef Str = Buffer.getBuffer();
183 bool InAtomicBlock = false;
184
185 while (SkipToToken(Str)) {
186 ByteArray.first.clear();
187 ByteArray.second.clear();
188
189 if (Str[0] == '[') {
190 if (InAtomicBlock) {
191 SM.PrintMessage(Loc: SMLoc::getFromPointer(Ptr: Str.data()), Kind: SourceMgr::DK_Error,
192 Msg: "nested atomic blocks make no sense");
193 ErrorOccurred = true;
194 }
195 InAtomicBlock = true;
196 Str = Str.drop_front();
197 continue;
198 } else if (Str[0] == ']') {
199 if (!InAtomicBlock) {
200 SM.PrintMessage(Loc: SMLoc::getFromPointer(Ptr: Str.data()), Kind: SourceMgr::DK_Error,
201 Msg: "attempt to close atomic block without opening");
202 ErrorOccurred = true;
203 }
204 InAtomicBlock = false;
205 Str = Str.drop_front();
206 continue;
207 }
208
209 // It's a real token, get the bytes and emit them
210 ErrorOccurred |= byteArrayFromString(ByteArray, Str, SM, HexBytes);
211
212 if (!ByteArray.first.empty())
213 ErrorOccurred |= printInsts(DisAsm: *DisAsm, Bytes: ByteArray, SM, Streamer,
214 InAtomicBlock, STI, NumBenchmarkRuns);
215 }
216
217 if (InAtomicBlock) {
218 SM.PrintMessage(Loc: SMLoc::getFromPointer(Ptr: Str.data()), Kind: SourceMgr::DK_Error,
219 Msg: "unclosed atomic block");
220 ErrorOccurred = true;
221 }
222
223 return ErrorOccurred;
224}
225