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

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