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
29using namespace llvm;
30
31typedef std::pair<std::vector<unsigned char>, std::vector<const char *>>
32 ByteArrayTy;
33
34static 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(Instr&: Inst, Size, Bytes: Data.slice(N: Index), Address: Index, CStream&: nulls());
48 switch (S) {
49 case MCDisassembler::Fail:
50 SM.PrintMessage(Loc: SMLoc::getFromPointer(Ptr: Bytes.second[Index]),
51 Kind: SourceMgr::DK_Warning,
52 Msg: "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(Loc: SMLoc::getFromPointer(Ptr: Bytes.second[Index]),
64 Kind: SourceMgr::DK_Warning,
65 Msg: "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
77static 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(Chars: " \t\r\n,")) {
84 Str = Str.substr(Start: 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(Start: Str.find_first_of(C: '\n'));
91 continue;
92 }
93 return true;
94 }
95}
96
97
98static 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(Chars: " \t\n\r,#[]");
108 StringRef Value = Str.substr(Start: 0, N: Next);
109
110 // Convert to a byte and add to the byte vector.
111 unsigned ByteVal;
112 if (Value.getAsInteger(Radix: 0, Result&: ByteVal) || ByteVal > 255) {
113 // If we have an error, print it and skip to the end of line.
114 SM.PrintMessage(Loc: SMLoc::getFromPointer(Ptr: Value.data()), Kind: SourceMgr::DK_Error,
115 Msg: "invalid input token");
116 Str = Str.substr(Start: Str.find(C: '\n'));
117 ByteArray.first.clear();
118 ByteArray.second.clear();
119 continue;
120 }
121
122 ByteArray.first.push_back(x: ByteVal);
123 ByteArray.second.push_back(x: Value.data());
124 Str = Str.substr(Start: Next);
125 }
126
127 return false;
128}
129
130int 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(TT: 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: *MRI, TheTriple: Triple, Options: 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(NoExecStack: 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(Loc: SMLoc::getFromPointer(Ptr: Str.data()), Kind: SourceMgr::DK_Error,
173 Msg: "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(Loc: SMLoc::getFromPointer(Ptr: Str.data()), Kind: SourceMgr::DK_Error,
182 Msg: "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: *DisAsm, Bytes: ByteArray, SM, Streamer, InAtomicBlock, STI);
196 }
197
198 if (InAtomicBlock) {
199 SM.PrintMessage(Loc: SMLoc::getFromPointer(Ptr: Str.data()), Kind: SourceMgr::DK_Error,
200 Msg: "unclosed atomic block");
201 ErrorOccurred = true;
202 }
203
204 return ErrorOccurred;
205}
206

source code of llvm/tools/llvm-mc/Disassembler.cpp