1//===-- lib/MC/Disassembler.cpp - Disassembler Public C Interface ---------===//
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#include "Disassembler.h"
10#include "llvm-c/Disassembler.h"
11#include "llvm/ADT/ArrayRef.h"
12#include "llvm/ADT/SmallVector.h"
13#include "llvm/MC/MCAsmInfo.h"
14#include "llvm/MC/MCContext.h"
15#include "llvm/MC/MCDisassembler/MCDisassembler.h"
16#include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
17#include "llvm/MC/MCDisassembler/MCSymbolizer.h"
18#include "llvm/MC/MCInst.h"
19#include "llvm/MC/MCInstPrinter.h"
20#include "llvm/MC/MCInstrInfo.h"
21#include "llvm/MC/MCRegisterInfo.h"
22#include "llvm/MC/MCSchedule.h"
23#include "llvm/MC/MCSubtargetInfo.h"
24#include "llvm/MC/MCTargetOptions.h"
25#include "llvm/MC/TargetRegistry.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/FormattedStream.h"
28#include "llvm/Support/raw_ostream.h"
29#include "llvm/TargetParser/Triple.h"
30#include <cassert>
31#include <cstring>
32
33using namespace llvm;
34
35// LLVMCreateDisasm() creates a disassembler for the TripleName. Symbolic
36// disassembly is supported by passing a block of information in the DisInfo
37// parameter and specifying the TagType and callback functions as described in
38// the header llvm-c/Disassembler.h . The pointer to the block and the
39// functions can all be passed as NULL. If successful, this returns a
40// disassembler context. If not, it returns NULL.
41//
42LLVMDisasmContextRef
43LLVMCreateDisasmCPUFeatures(const char *TT, const char *CPU,
44 const char *Features, void *DisInfo, int TagType,
45 LLVMOpInfoCallback GetOpInfo,
46 LLVMSymbolLookupCallback SymbolLookUp) {
47 Triple TheTriple(TT);
48
49 // Get the target.
50 std::string Error;
51 const Target *TheTarget = TargetRegistry::lookupTarget(TheTriple, Error);
52 if (!TheTarget)
53 return nullptr;
54
55 std::unique_ptr<const MCRegisterInfo> MRI(
56 TheTarget->createMCRegInfo(TT: TheTriple));
57 if (!MRI)
58 return nullptr;
59
60 MCTargetOptions MCOptions;
61 // Get the assembler info needed to setup the MCContext.
62 std::unique_ptr<const MCAsmInfo> MAI(
63 TheTarget->createMCAsmInfo(MRI: *MRI, TheTriple, Options: MCOptions));
64 if (!MAI)
65 return nullptr;
66
67 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
68 if (!MII)
69 return nullptr;
70
71 std::unique_ptr<const MCSubtargetInfo> STI(
72 TheTarget->createMCSubtargetInfo(TheTriple, CPU, Features));
73 if (!STI)
74 return nullptr;
75
76 // Set up the MCContext for creating symbols and MCExpr's.
77 std::unique_ptr<MCContext> Ctx(new MCContext(TheTriple, *MAI, *MRI, *STI));
78 if (!Ctx)
79 return nullptr;
80
81 // Set up disassembler.
82 std::unique_ptr<MCDisassembler> DisAsm(
83 TheTarget->createMCDisassembler(STI: *STI, Ctx&: *Ctx));
84 if (!DisAsm)
85 return nullptr;
86
87 std::unique_ptr<MCRelocationInfo> RelInfo(
88 TheTarget->createMCRelocationInfo(TT: TheTriple, Ctx&: *Ctx));
89 if (!RelInfo)
90 return nullptr;
91
92 std::unique_ptr<MCSymbolizer> Symbolizer(
93 TheTarget->createMCSymbolizer(TT: TheTriple, GetOpInfo, SymbolLookUp, DisInfo,
94 Ctx: Ctx.get(), RelInfo: std::move(RelInfo)));
95 DisAsm->setSymbolizer(std::move(Symbolizer));
96
97 // Set up the instruction printer.
98 int AsmPrinterVariant = MAI->getAssemblerDialect();
99 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
100 T: Triple(TT), SyntaxVariant: AsmPrinterVariant, MAI: *MAI, MII: *MII, MRI: *MRI));
101 if (!IP)
102 return nullptr;
103
104 LLVMDisasmContext *DC = new LLVMDisasmContext(
105 TT, DisInfo, TagType, GetOpInfo, SymbolLookUp, TheTarget, std::move(MAI),
106 std::move(MRI), std::move(STI), std::move(MII), std::move(Ctx),
107 std::move(DisAsm), std::move(IP));
108 if (!DC)
109 return nullptr;
110
111 DC->setCPU(CPU);
112 return DC;
113}
114
115LLVMDisasmContextRef
116LLVMCreateDisasmCPU(const char *TT, const char *CPU, void *DisInfo, int TagType,
117 LLVMOpInfoCallback GetOpInfo,
118 LLVMSymbolLookupCallback SymbolLookUp) {
119 return LLVMCreateDisasmCPUFeatures(TT, CPU, Features: "", DisInfo, TagType, GetOpInfo,
120 SymbolLookUp);
121}
122
123LLVMDisasmContextRef LLVMCreateDisasm(const char *TT, void *DisInfo,
124 int TagType, LLVMOpInfoCallback GetOpInfo,
125 LLVMSymbolLookupCallback SymbolLookUp) {
126 return LLVMCreateDisasmCPUFeatures(TT, CPU: "", Features: "", DisInfo, TagType, GetOpInfo,
127 SymbolLookUp);
128}
129
130//
131// LLVMDisasmDispose() disposes of the disassembler specified by the context.
132//
133void LLVMDisasmDispose(LLVMDisasmContextRef DCR){
134 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
135 delete DC;
136}
137
138/// Emits the comments that are stored in \p DC comment stream.
139/// Each comment in the comment stream must end with a newline.
140static void emitComments(LLVMDisasmContext *DC,
141 formatted_raw_ostream &FormattedOS) {
142 // Flush the stream before taking its content.
143 StringRef Comments = DC->CommentsToEmit.str();
144 // Get the default information for printing a comment.
145 const MCAsmInfo *MAI = DC->getAsmInfo();
146 StringRef CommentBegin = MAI->getCommentString();
147 unsigned CommentColumn = MAI->getCommentColumn();
148 bool IsFirst = true;
149 while (!Comments.empty()) {
150 if (!IsFirst)
151 FormattedOS << '\n';
152 // Emit a line of comments.
153 FormattedOS.PadToColumn(NewCol: CommentColumn);
154 size_t Position = Comments.find(C: '\n');
155 FormattedOS << CommentBegin << ' ' << Comments.substr(Start: 0, N: Position);
156 // Move after the newline character.
157 Comments = Comments.substr(Start: Position+1);
158 IsFirst = false;
159 }
160 FormattedOS.flush();
161
162 // Tell the comment stream that the vector changed underneath it.
163 DC->CommentsToEmit.clear();
164}
165
166/// Emits latency information in DC->CommentStream for \p Inst, based
167/// on the information available in \p DC.
168static void emitLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
169 const MCSubtargetInfo *STI = DC->getSubtargetInfo();
170 const MCInstrInfo *MCII = DC->getInstrInfo();
171 const MCSchedModel &SCModel = STI->getSchedModel();
172 int Latency = SCModel.computeInstrLatency(STI: *STI, MCII: *MCII, Inst);
173
174 // Report only interesting latencies.
175 if (Latency < 2)
176 return;
177
178 DC->CommentStream << "Latency: " << Latency << '\n';
179}
180
181//
182// LLVMDisasmInstruction() disassembles a single instruction using the
183// disassembler context specified in the parameter DC. The bytes of the
184// instruction are specified in the parameter Bytes, and contains at least
185// BytesSize number of bytes. The instruction is at the address specified by
186// the PC parameter. If a valid instruction can be disassembled its string is
187// returned indirectly in OutString which whos size is specified in the
188// parameter OutStringSize. This function returns the number of bytes in the
189// instruction or zero if there was no valid instruction. If this function
190// returns zero the caller will have to pick how many bytes they want to step
191// over by printing a .byte, .long etc. to continue.
192//
193size_t LLVMDisasmInstruction(LLVMDisasmContextRef DCR, uint8_t *Bytes,
194 uint64_t BytesSize, uint64_t PC, char *OutString,
195 size_t OutStringSize){
196 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
197 // Wrap the pointer to the Bytes, BytesSize and PC in a MemoryObject.
198 ArrayRef<uint8_t> Data(Bytes, BytesSize);
199
200 uint64_t Size;
201 MCInst Inst;
202 const MCDisassembler *DisAsm = DC->getDisAsm();
203 MCInstPrinter *IP = DC->getIP();
204 MCDisassembler::DecodeStatus S;
205 SmallVector<char, 64> InsnStr;
206 raw_svector_ostream Annotations(InsnStr);
207 S = DisAsm->getInstruction(Instr&: Inst, Size, Bytes: Data, Address: PC, CStream&: Annotations);
208 switch (S) {
209 case MCDisassembler::Fail:
210 case MCDisassembler::SoftFail:
211 // FIXME: Do something different for soft failure modes?
212 return 0;
213
214 case MCDisassembler::Success: {
215 StringRef AnnotationsStr = Annotations.str();
216
217 SmallVector<char, 64> InsnStr;
218 raw_svector_ostream OS(InsnStr);
219 formatted_raw_ostream FormattedOS(OS);
220
221 if (DC->getOptions() & LLVMDisassembler_Option_Color) {
222 FormattedOS.enable_colors(enable: true);
223 IP->setUseColor(true);
224 }
225
226 IP->printInst(MI: &Inst, Address: PC, Annot: AnnotationsStr, STI: *DC->getSubtargetInfo(),
227 OS&: FormattedOS);
228
229 if (DC->getOptions() & LLVMDisassembler_Option_PrintLatency)
230 emitLatency(DC, Inst);
231
232 emitComments(DC, FormattedOS);
233
234 assert(OutStringSize != 0 && "Output buffer cannot be zero size");
235 size_t OutputSize = std::min(a: OutStringSize-1, b: InsnStr.size());
236 std::memcpy(dest: OutString, src: InsnStr.data(), n: OutputSize);
237 OutString[OutputSize] = '\0'; // Terminate string.
238
239 return Size;
240 }
241 }
242 llvm_unreachable("Invalid DecodeStatus!");
243}
244
245//
246// LLVMSetDisasmOptions() sets the disassembler's options. It returns 1 if it
247// can set all the Options and 0 otherwise.
248//
249int LLVMSetDisasmOptions(LLVMDisasmContextRef DCR, uint64_t Options){
250 if (Options & LLVMDisassembler_Option_UseMarkup){
251 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
252 MCInstPrinter *IP = DC->getIP();
253 IP->setUseMarkup(true);
254 DC->addOptions(LLVMDisassembler_Option_UseMarkup);
255 Options &= ~LLVMDisassembler_Option_UseMarkup;
256 }
257 if (Options & LLVMDisassembler_Option_PrintImmHex){
258 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
259 MCInstPrinter *IP = DC->getIP();
260 IP->setPrintImmHex(true);
261 DC->addOptions(LLVMDisassembler_Option_PrintImmHex);
262 Options &= ~LLVMDisassembler_Option_PrintImmHex;
263 }
264 if (Options & LLVMDisassembler_Option_AsmPrinterVariant){
265 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
266 // Try to set up the new instruction printer.
267 const MCAsmInfo *MAI = DC->getAsmInfo();
268 const MCInstrInfo *MII = DC->getInstrInfo();
269 const MCRegisterInfo *MRI = DC->getRegisterInfo();
270 int AsmPrinterVariant = MAI->getAssemblerDialect();
271 AsmPrinterVariant = AsmPrinterVariant == 0 ? 1 : 0;
272 MCInstPrinter *IP = DC->getTarget()->createMCInstPrinter(
273 T: Triple(DC->getTripleName()), SyntaxVariant: AsmPrinterVariant, MAI: *MAI, MII: *MII, MRI: *MRI);
274 if (IP) {
275 DC->setIP(IP);
276 DC->addOptions(LLVMDisassembler_Option_AsmPrinterVariant);
277 Options &= ~LLVMDisassembler_Option_AsmPrinterVariant;
278 }
279 }
280 if (Options & LLVMDisassembler_Option_SetInstrComments) {
281 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
282 MCInstPrinter *IP = DC->getIP();
283 IP->setCommentStream(DC->CommentStream);
284 DC->addOptions(LLVMDisassembler_Option_SetInstrComments);
285 Options &= ~LLVMDisassembler_Option_SetInstrComments;
286 }
287 if (Options & LLVMDisassembler_Option_PrintLatency) {
288 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
289 DC->addOptions(LLVMDisassembler_Option_PrintLatency);
290 Options &= ~LLVMDisassembler_Option_PrintLatency;
291 }
292 if (Options & LLVMDisassembler_Option_Color) {
293 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
294 DC->addOptions(LLVMDisassembler_Option_Color);
295 Options &= ~LLVMDisassembler_Option_Color;
296 }
297 return (Options == 0);
298}
299