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