1 //===-- llvm-mc.cpp - Machine Code Hacking Driver ---------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This utility is a simple driver that allows command line hacking on machine
12 //===----------------------------------------------------------------------===//
14 #include "Disassembler.h"
15 #include "llvm/MC/MCAsmBackend.h"
16 #include "llvm/MC/MCAsmInfo.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCInstPrinter.h"
20 #include "llvm/MC/MCInstrInfo.h"
21 #include "llvm/MC/MCObjectFileInfo.h"
22 #include "llvm/MC/MCObjectWriter.h"
23 #include "llvm/MC/MCParser/AsmLexer.h"
24 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
25 #include "llvm/MC/MCRegisterInfo.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/MC/MCTargetOptionsCommandFlags.h"
29 #include "llvm/MC/TargetRegistry.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Compression.h"
32 #include "llvm/Support/FileUtilities.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/InitLLVM.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/TargetSelect.h"
38 #include "llvm/Support/ToolOutputFile.h"
39 #include "llvm/Support/WithColor.h"
40 #include "llvm/TargetParser/Host.h"
44 static mc::RegisterMCTargetOptionsFlags MOF
;
46 static cl::OptionCategory
MCCategory("MC Options");
48 static cl::opt
<std::string
> InputFilename(cl::Positional
,
49 cl::desc("<input file>"),
50 cl::init("-"), cl::cat(MCCategory
));
52 static cl::list
<std::string
>
53 DisassemblerOptions("M", cl::desc("Disassembler options"),
56 static cl::opt
<std::string
> OutputFilename("o", cl::desc("Output filename"),
57 cl::value_desc("filename"),
58 cl::init("-"), cl::cat(MCCategory
));
60 static cl::opt
<std::string
> SplitDwarfFile("split-dwarf-file",
61 cl::desc("DWO output filename"),
62 cl::value_desc("filename"),
65 static cl::opt
<bool> ShowEncoding("show-encoding",
66 cl::desc("Show instruction encodings"),
69 static cl::opt
<DebugCompressionType
> CompressDebugSections(
70 "compress-debug-sections", cl::ValueOptional
,
71 cl::init(DebugCompressionType::None
),
72 cl::desc("Choose DWARF debug sections compression:"),
73 cl::values(clEnumValN(DebugCompressionType::None
, "none", "No compression"),
74 clEnumValN(DebugCompressionType::Zlib
, "zlib", "Use zlib"),
75 clEnumValN(DebugCompressionType::Zstd
, "zstd", "Use zstd")),
79 ShowInst("show-inst", cl::desc("Show internal instruction representation"),
83 ShowInstOperands("show-inst-operands",
84 cl::desc("Show instructions operands as parsed"),
87 static cl::opt
<unsigned>
88 OutputAsmVariant("output-asm-variant",
89 cl::desc("Syntax variant to use for output printing"),
93 PrintImmHex("print-imm-hex", cl::init(false),
94 cl::desc("Prefer hex format for immediate values"),
97 static cl::list
<std::string
>
98 DefineSymbol("defsym",
99 cl::desc("Defines a symbol to be an integer constant"),
100 cl::cat(MCCategory
));
103 PreserveComments("preserve-comments",
104 cl::desc("Preserve Comments in outputted assembly"),
105 cl::cat(MCCategory
));
107 static cl::opt
<unsigned> CommentColumn("comment-column",
108 cl::desc("Asm comments indentation"),
111 enum OutputFileType
{
116 static cl::opt
<OutputFileType
>
117 FileType("filetype", cl::init(OFT_AssemblyFile
),
118 cl::desc("Choose an output file type:"),
119 cl::values(clEnumValN(OFT_AssemblyFile
, "asm",
120 "Emit an assembly ('.s') file"),
121 clEnumValN(OFT_Null
, "null",
122 "Don't emit anything (for timing purposes)"),
123 clEnumValN(OFT_ObjectFile
, "obj",
124 "Emit a native object ('.o') file")),
125 cl::cat(MCCategory
));
127 static cl::list
<std::string
> IncludeDirs("I",
128 cl::desc("Directory of include files"),
129 cl::value_desc("directory"),
130 cl::Prefix
, cl::cat(MCCategory
));
132 static cl::opt
<std::string
>
134 cl::desc("Target arch to assemble for, "
135 "see -version for available targets"),
136 cl::cat(MCCategory
));
138 static cl::opt
<std::string
>
140 cl::desc("Target triple to assemble for, "
141 "see -version for available targets"),
142 cl::cat(MCCategory
));
144 static cl::opt
<std::string
>
146 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
147 cl::value_desc("cpu-name"), cl::init(""), cl::cat(MCCategory
));
149 static cl::list
<std::string
>
150 MAttrs("mattr", cl::CommaSeparated
,
151 cl::desc("Target specific attributes (-mattr=help for details)"),
152 cl::value_desc("a1,+a2,-a3,..."), cl::cat(MCCategory
));
154 static cl::opt
<bool> PIC("position-independent",
155 cl::desc("Position independent"), cl::init(false),
156 cl::cat(MCCategory
));
159 LargeCodeModel("large-code-model",
160 cl::desc("Create cfi directives that assume the code might "
161 "be more than 2gb away"),
162 cl::cat(MCCategory
));
165 NoInitialTextSection("n",
166 cl::desc("Don't assume assembly file starts "
167 "in the text section"),
168 cl::cat(MCCategory
));
171 GenDwarfForAssembly("g",
172 cl::desc("Generate dwarf debugging info for assembly "
174 cl::cat(MCCategory
));
176 static cl::opt
<std::string
>
177 DebugCompilationDir("fdebug-compilation-dir",
178 cl::desc("Specifies the debug info's compilation dir"),
179 cl::cat(MCCategory
));
181 static cl::list
<std::string
> DebugPrefixMap(
182 "fdebug-prefix-map", cl::desc("Map file source paths in debug info"),
183 cl::value_desc("= separated key-value pairs"), cl::cat(MCCategory
));
185 static cl::opt
<std::string
> MainFileName(
187 cl::desc("Specifies the name we should consider the input file"),
188 cl::cat(MCCategory
));
190 static cl::opt
<bool> LexMasmIntegers(
192 cl::desc("Enable binary and hex masm integers (0b110 and 0ABCh)"),
193 cl::cat(MCCategory
));
195 static cl::opt
<bool> LexMasmHexFloats(
197 cl::desc("Enable MASM-style hex float initializers (3F800000r)"),
198 cl::cat(MCCategory
));
200 static cl::opt
<bool> LexMotorolaIntegers(
202 cl::desc("Enable binary and hex Motorola integers (%110 and $ABC)"),
203 cl::cat(MCCategory
));
205 static cl::opt
<bool> NoExecStack("no-exec-stack",
206 cl::desc("File doesn't need an exec stack"),
207 cl::cat(MCCategory
));
217 static cl::opt
<ActionType
> Action(
218 cl::desc("Action to perform:"), cl::init(AC_Assemble
),
219 cl::values(clEnumValN(AC_AsLex
, "as-lex", "Lex tokens from a .s file"),
220 clEnumValN(AC_Assemble
, "assemble",
221 "Assemble a .s file (default)"),
222 clEnumValN(AC_Disassemble
, "disassemble",
223 "Disassemble strings of hex bytes"),
224 clEnumValN(AC_MDisassemble
, "mdis",
225 "Marked up disassembly of strings of hex bytes"),
226 clEnumValN(AC_CDisassemble
, "cdis",
227 "Colored disassembly of strings of hex bytes")),
228 cl::cat(MCCategory
));
230 static const Target
*GetTarget(const char *ProgName
) {
231 // Figure out the target triple.
232 if (TripleName
.empty())
233 TripleName
= sys::getDefaultTargetTriple();
234 Triple
TheTriple(Triple::normalize(TripleName
));
236 // Get the target specific parser.
238 const Target
*TheTarget
= TargetRegistry::lookupTarget(ArchName
, TheTriple
,
241 WithColor::error(errs(), ProgName
) << Error
;
245 // Update the triple name and return the found target.
246 TripleName
= TheTriple
.getTriple();
250 static std::unique_ptr
<ToolOutputFile
> GetOutputStream(StringRef Path
,
251 sys::fs::OpenFlags Flags
) {
253 auto Out
= std::make_unique
<ToolOutputFile
>(Path
, EC
, Flags
);
255 WithColor::error() << EC
.message() << '\n';
262 static std::string DwarfDebugFlags
;
263 static void setDwarfDebugFlags(int argc
, char **argv
) {
264 if (!getenv("RC_DEBUG_OPTIONS"))
266 for (int i
= 0; i
< argc
; i
++) {
267 DwarfDebugFlags
+= argv
[i
];
269 DwarfDebugFlags
+= " ";
273 static std::string DwarfDebugProducer
;
274 static void setDwarfDebugProducer() {
275 if(!getenv("DEBUG_PRODUCER"))
277 DwarfDebugProducer
+= getenv("DEBUG_PRODUCER");
280 static int AsLexInput(SourceMgr
&SrcMgr
, MCAsmInfo
&MAI
,
284 Lexer
.setBuffer(SrcMgr
.getMemoryBuffer(SrcMgr
.getMainFileID())->getBuffer());
287 while (Lexer
.Lex().isNot(AsmToken::Eof
)) {
288 Lexer
.getTok().dump(OS
);
290 if (Lexer
.getTok().getKind() == AsmToken::Error
)
297 static int fillCommandLineSymbols(MCAsmParser
&Parser
) {
298 for (auto &I
: DefineSymbol
) {
299 auto Pair
= StringRef(I
).split('=');
300 auto Sym
= Pair
.first
;
301 auto Val
= Pair
.second
;
303 if (Sym
.empty() || Val
.empty()) {
304 WithColor::error() << "defsym must be of the form: sym=value: " << I
309 if (Val
.getAsInteger(0, Value
)) {
310 WithColor::error() << "value is not an integer: " << Val
<< "\n";
313 Parser
.getContext().setSymbolValue(Parser
.getStreamer(), Sym
, Value
);
318 static int AssembleInput(const char *ProgName
, const Target
*TheTarget
,
319 SourceMgr
&SrcMgr
, MCContext
&Ctx
, MCStreamer
&Str
,
320 MCAsmInfo
&MAI
, MCSubtargetInfo
&STI
,
321 MCInstrInfo
&MCII
, MCTargetOptions
const &MCOptions
) {
322 std::unique_ptr
<MCAsmParser
> Parser(
323 createMCAsmParser(SrcMgr
, Ctx
, Str
, MAI
));
324 std::unique_ptr
<MCTargetAsmParser
> TAP(
325 TheTarget
->createMCAsmParser(STI
, *Parser
, MCII
, MCOptions
));
328 WithColor::error(errs(), ProgName
)
329 << "this target does not support assembly parsing.\n";
333 int SymbolResult
= fillCommandLineSymbols(*Parser
);
336 Parser
->setShowParsedOperands(ShowInstOperands
);
337 Parser
->setTargetParser(*TAP
);
338 Parser
->getLexer().setLexMasmIntegers(LexMasmIntegers
);
339 Parser
->getLexer().setLexMasmHexFloats(LexMasmHexFloats
);
340 Parser
->getLexer().setLexMotorolaIntegers(LexMotorolaIntegers
);
342 int Res
= Parser
->Run(NoInitialTextSection
);
347 int main(int argc
, char **argv
) {
348 InitLLVM
X(argc
, argv
);
350 // Initialize targets and assembly printers/parsers.
351 llvm::InitializeAllTargetInfos();
352 llvm::InitializeAllTargetMCs();
353 llvm::InitializeAllAsmParsers();
354 llvm::InitializeAllDisassemblers();
356 // Register the target printer for --version.
357 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion
);
359 cl::HideUnrelatedOptions({&MCCategory
, &getColorCategory()});
360 cl::ParseCommandLineOptions(argc
, argv
, "llvm machine code playground\n");
361 MCTargetOptions MCOptions
= mc::InitMCTargetOptionsFromFlags();
362 MCOptions
.CompressDebugSections
= CompressDebugSections
.getValue();
363 MCOptions
.ShowMCInst
= ShowInst
;
364 MCOptions
.AsmVerbose
= true;
365 MCOptions
.MCUseDwarfDirectory
= MCTargetOptions::EnableDwarfDirectory
;
367 setDwarfDebugFlags(argc
, argv
);
368 setDwarfDebugProducer();
370 const char *ProgName
= argv
[0];
371 const Target
*TheTarget
= GetTarget(ProgName
);
374 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
375 // construct the Triple object.
376 Triple
TheTriple(TripleName
);
378 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufferPtr
=
379 MemoryBuffer::getFileOrSTDIN(InputFilename
, /*IsText=*/true);
380 if (std::error_code EC
= BufferPtr
.getError()) {
381 WithColor::error(errs(), ProgName
)
382 << InputFilename
<< ": " << EC
.message() << '\n';
385 MemoryBuffer
*Buffer
= BufferPtr
->get();
389 // Tell SrcMgr about this buffer, which is what the parser will pick up.
390 SrcMgr
.AddNewSourceBuffer(std::move(*BufferPtr
), SMLoc());
392 // Record the location of the include directories so that the lexer can find
394 SrcMgr
.setIncludeDirs(IncludeDirs
);
396 std::unique_ptr
<MCRegisterInfo
> MRI(TheTarget
->createMCRegInfo(TripleName
));
397 assert(MRI
&& "Unable to create target register info!");
399 std::unique_ptr
<MCAsmInfo
> MAI(
400 TheTarget
->createMCAsmInfo(*MRI
, TripleName
, MCOptions
));
401 assert(MAI
&& "Unable to create target asm info!");
403 if (CompressDebugSections
!= DebugCompressionType::None
) {
404 if (const char *Reason
= compression::getReasonIfUnsupported(
405 compression::formatFor(CompressDebugSections
))) {
406 WithColor::error(errs(), ProgName
)
407 << "--compress-debug-sections: " << Reason
;
411 MAI
->setPreserveAsmComments(PreserveComments
);
412 MAI
->setCommentColumn(CommentColumn
);
414 // Package up features to be passed to target/subtarget
415 std::string FeaturesStr
;
417 SubtargetFeatures Features
;
418 for (unsigned i
= 0; i
!= MAttrs
.size(); ++i
)
419 Features
.AddFeature(MAttrs
[i
]);
420 FeaturesStr
= Features
.getString();
423 std::unique_ptr
<MCSubtargetInfo
> STI(
424 TheTarget
->createMCSubtargetInfo(TripleName
, MCPU
, FeaturesStr
));
425 assert(STI
&& "Unable to create subtarget info!");
427 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
428 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
429 MCContext
Ctx(TheTriple
, MAI
.get(), MRI
.get(), STI
.get(), &SrcMgr
,
431 std::unique_ptr
<MCObjectFileInfo
> MOFI(
432 TheTarget
->createMCObjectFileInfo(Ctx
, PIC
, LargeCodeModel
));
433 Ctx
.setObjectFileInfo(MOFI
.get());
435 Ctx
.setGenDwarfForAssembly(GenDwarfForAssembly
);
436 // Default to 4 for dwarf version.
437 unsigned DwarfVersion
= MCOptions
.DwarfVersion
? MCOptions
.DwarfVersion
: 4;
438 if (DwarfVersion
< 2 || DwarfVersion
> 5) {
439 errs() << ProgName
<< ": Dwarf version " << DwarfVersion
440 << " is not supported." << '\n';
443 Ctx
.setDwarfVersion(DwarfVersion
);
444 if (MCOptions
.Dwarf64
) {
445 // The 64-bit DWARF format was introduced in DWARFv3.
446 if (DwarfVersion
< 3) {
448 << ": the 64-bit DWARF format is not supported for DWARF versions "
452 // 32-bit targets don't support DWARF64, which requires 64-bit relocations.
453 if (MAI
->getCodePointerSize() < 8) {
455 << ": the 64-bit DWARF format is only supported for 64-bit "
459 // If needsDwarfSectionOffsetDirective is true, we would eventually call
460 // MCStreamer::emitSymbolValue() with IsSectionRelative = true, but that
461 // is supported only for 4-byte long references.
462 if (MAI
->needsDwarfSectionOffsetDirective()) {
463 errs() << ProgName
<< ": the 64-bit DWARF format is not supported for "
464 << TheTriple
.normalize() << "\n";
467 Ctx
.setDwarfFormat(dwarf::DWARF64
);
469 if (!DwarfDebugFlags
.empty())
470 Ctx
.setDwarfDebugFlags(StringRef(DwarfDebugFlags
));
471 if (!DwarfDebugProducer
.empty())
472 Ctx
.setDwarfDebugProducer(StringRef(DwarfDebugProducer
));
473 if (!DebugCompilationDir
.empty())
474 Ctx
.setCompilationDir(DebugCompilationDir
);
476 // If no compilation dir is set, try to use the current directory.
477 SmallString
<128> CWD
;
478 if (!sys::fs::current_path(CWD
))
479 Ctx
.setCompilationDir(CWD
);
481 for (const auto &Arg
: DebugPrefixMap
) {
482 const auto &KV
= StringRef(Arg
).split('=');
483 Ctx
.addDebugPrefixMapEntry(std::string(KV
.first
), std::string(KV
.second
));
485 if (!MainFileName
.empty())
486 Ctx
.setMainFileName(MainFileName
);
487 if (GenDwarfForAssembly
)
488 Ctx
.setGenDwarfRootFile(InputFilename
, Buffer
->getBuffer());
490 sys::fs::OpenFlags Flags
= (FileType
== OFT_AssemblyFile
)
491 ? sys::fs::OF_TextWithCRLF
493 std::unique_ptr
<ToolOutputFile
> Out
= GetOutputStream(OutputFilename
, Flags
);
497 std::unique_ptr
<ToolOutputFile
> DwoOut
;
498 if (!SplitDwarfFile
.empty()) {
499 if (FileType
!= OFT_ObjectFile
) {
500 WithColor::error() << "dwo output only supported with object files\n";
503 DwoOut
= GetOutputStream(SplitDwarfFile
, sys::fs::OF_None
);
508 std::unique_ptr
<buffer_ostream
> BOS
;
509 raw_pwrite_stream
*OS
= &Out
->os();
510 std::unique_ptr
<MCStreamer
> Str
;
512 std::unique_ptr
<MCInstrInfo
> MCII(TheTarget
->createMCInstrInfo());
513 assert(MCII
&& "Unable to create instruction info!");
515 MCInstPrinter
*IP
= nullptr;
516 if (FileType
== OFT_AssemblyFile
) {
517 IP
= TheTarget
->createMCInstPrinter(Triple(TripleName
), OutputAsmVariant
,
522 << "unable to create instruction printer for target triple '"
523 << TheTriple
.normalize() << "' with assembly variant "
524 << OutputAsmVariant
<< ".\n";
528 for (StringRef Opt
: DisassemblerOptions
)
529 if (!IP
->applyTargetSpecificCLOption(Opt
)) {
530 WithColor::error() << "invalid disassembler option '" << Opt
<< "'\n";
534 // Set the display preference for hex vs. decimal immediates.
535 IP
->setPrintImmHex(PrintImmHex
);
537 // Set up the AsmStreamer.
538 std::unique_ptr
<MCCodeEmitter
> CE
;
540 CE
.reset(TheTarget
->createMCCodeEmitter(*MCII
, Ctx
));
542 std::unique_ptr
<MCAsmBackend
> MAB(
543 TheTarget
->createMCAsmBackend(*STI
, *MRI
, MCOptions
));
544 auto FOut
= std::make_unique
<formatted_raw_ostream
>(*OS
);
545 Str
.reset(TheTarget
->createAsmStreamer(Ctx
, std::move(FOut
), IP
,
546 std::move(CE
), std::move(MAB
)));
548 } else if (FileType
== OFT_Null
) {
549 Str
.reset(TheTarget
->createNullStreamer(Ctx
));
551 assert(FileType
== OFT_ObjectFile
&& "Invalid file type!");
553 if (!Out
->os().supportsSeeking()) {
554 BOS
= std::make_unique
<buffer_ostream
>(Out
->os());
558 MCCodeEmitter
*CE
= TheTarget
->createMCCodeEmitter(*MCII
, Ctx
);
559 MCAsmBackend
*MAB
= TheTarget
->createMCAsmBackend(*STI
, *MRI
, MCOptions
);
560 Str
.reset(TheTarget
->createMCObjectStreamer(
561 TheTriple
, Ctx
, std::unique_ptr
<MCAsmBackend
>(MAB
),
562 DwoOut
? MAB
->createDwoObjectWriter(*OS
, DwoOut
->os())
563 : MAB
->createObjectWriter(*OS
),
564 std::unique_ptr
<MCCodeEmitter
>(CE
), *STI
));
566 Str
->initSections(true, *STI
);
567 Str
->emitVersionForTarget(TheTriple
, VersionTuple(), nullptr,
572 bool disassemble
= false;
575 Res
= AsLexInput(SrcMgr
, *MAI
, Out
->os());
578 Res
= AssembleInput(ProgName
, TheTarget
, SrcMgr
, Ctx
, *Str
, *MAI
, *STI
,
581 case AC_MDisassemble
:
582 IP
->setUseMarkup(true);
585 case AC_CDisassemble
:
586 IP
->setUseColor(true);
594 Res
= Disassembler::disassemble(*TheTarget
, TripleName
, *STI
, *Str
, *Buffer
,
595 SrcMgr
, Ctx
, MCOptions
);
597 // Keep output if no errors.