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