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
<bool> RelaxELFRel(
70 "relax-relocations", cl::init(true),
71 cl::desc("Emit R_X86_64_GOTPCRELX instead of R_X86_64_GOTPCREL"),
74 static cl::opt
<DebugCompressionType
> CompressDebugSections(
75 "compress-debug-sections", cl::ValueOptional
,
76 cl::init(DebugCompressionType::None
),
77 cl::desc("Choose DWARF debug sections compression:"),
78 cl::values(clEnumValN(DebugCompressionType::None
, "none", "No compression"),
79 clEnumValN(DebugCompressionType::Zlib
, "zlib", "Use zlib"),
80 clEnumValN(DebugCompressionType::Zstd
, "zstd", "Use zstd")),
84 ShowInst("show-inst", cl::desc("Show internal instruction representation"),
88 ShowInstOperands("show-inst-operands",
89 cl::desc("Show instructions operands as parsed"),
92 static cl::opt
<unsigned>
93 OutputAsmVariant("output-asm-variant",
94 cl::desc("Syntax variant to use for output printing"),
98 PrintImmHex("print-imm-hex", cl::init(false),
99 cl::desc("Prefer hex format for immediate values"),
100 cl::cat(MCCategory
));
102 static cl::list
<std::string
>
103 DefineSymbol("defsym",
104 cl::desc("Defines a symbol to be an integer constant"),
105 cl::cat(MCCategory
));
108 PreserveComments("preserve-comments",
109 cl::desc("Preserve Comments in outputted assembly"),
110 cl::cat(MCCategory
));
112 enum OutputFileType
{
117 static cl::opt
<OutputFileType
>
118 FileType("filetype", cl::init(OFT_AssemblyFile
),
119 cl::desc("Choose an output file type:"),
120 cl::values(clEnumValN(OFT_AssemblyFile
, "asm",
121 "Emit an assembly ('.s') file"),
122 clEnumValN(OFT_Null
, "null",
123 "Don't emit anything (for timing purposes)"),
124 clEnumValN(OFT_ObjectFile
, "obj",
125 "Emit a native object ('.o') file")),
126 cl::cat(MCCategory
));
128 static cl::list
<std::string
> IncludeDirs("I",
129 cl::desc("Directory of include files"),
130 cl::value_desc("directory"),
131 cl::Prefix
, cl::cat(MCCategory
));
133 static cl::opt
<std::string
>
135 cl::desc("Target arch to assemble for, "
136 "see -version for available targets"),
137 cl::cat(MCCategory
));
139 static cl::opt
<std::string
>
141 cl::desc("Target triple to assemble for, "
142 "see -version for available targets"),
143 cl::cat(MCCategory
));
145 static cl::opt
<std::string
>
147 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
148 cl::value_desc("cpu-name"), cl::init(""), cl::cat(MCCategory
));
150 static cl::list
<std::string
>
151 MAttrs("mattr", cl::CommaSeparated
,
152 cl::desc("Target specific attributes (-mattr=help for details)"),
153 cl::value_desc("a1,+a2,-a3,..."), cl::cat(MCCategory
));
155 static cl::opt
<bool> PIC("position-independent",
156 cl::desc("Position independent"), cl::init(false),
157 cl::cat(MCCategory
));
160 LargeCodeModel("large-code-model",
161 cl::desc("Create cfi directives that assume the code might "
162 "be more than 2gb away"),
163 cl::cat(MCCategory
));
166 NoInitialTextSection("n",
167 cl::desc("Don't assume assembly file starts "
168 "in the text section"),
169 cl::cat(MCCategory
));
172 GenDwarfForAssembly("g",
173 cl::desc("Generate dwarf debugging info for assembly "
175 cl::cat(MCCategory
));
177 static cl::opt
<std::string
>
178 DebugCompilationDir("fdebug-compilation-dir",
179 cl::desc("Specifies the debug info's compilation dir"),
180 cl::cat(MCCategory
));
182 static cl::list
<std::string
> DebugPrefixMap(
183 "fdebug-prefix-map", cl::desc("Map file source paths in debug info"),
184 cl::value_desc("= separated key-value pairs"), cl::cat(MCCategory
));
186 static cl::opt
<std::string
> MainFileName(
188 cl::desc("Specifies the name we should consider the input file"),
189 cl::cat(MCCategory
));
191 static cl::opt
<bool> SaveTempLabels("save-temp-labels",
192 cl::desc("Don't discard temporary labels"),
193 cl::cat(MCCategory
));
195 static cl::opt
<bool> LexMasmIntegers(
197 cl::desc("Enable binary and hex masm integers (0b110 and 0ABCh)"),
198 cl::cat(MCCategory
));
200 static cl::opt
<bool> LexMasmHexFloats(
202 cl::desc("Enable MASM-style hex float initializers (3F800000r)"),
203 cl::cat(MCCategory
));
205 static cl::opt
<bool> LexMotorolaIntegers(
207 cl::desc("Enable binary and hex Motorola integers (%110 and $ABC)"),
208 cl::cat(MCCategory
));
210 static cl::opt
<bool> NoExecStack("no-exec-stack",
211 cl::desc("File doesn't need an exec stack"),
212 cl::cat(MCCategory
));
222 static cl::opt
<ActionType
> Action(
223 cl::desc("Action to perform:"), cl::init(AC_Assemble
),
224 cl::values(clEnumValN(AC_AsLex
, "as-lex", "Lex tokens from a .s file"),
225 clEnumValN(AC_Assemble
, "assemble",
226 "Assemble a .s file (default)"),
227 clEnumValN(AC_Disassemble
, "disassemble",
228 "Disassemble strings of hex bytes"),
229 clEnumValN(AC_MDisassemble
, "mdis",
230 "Marked up disassembly of strings of hex bytes"),
231 clEnumValN(AC_CDisassemble
, "cdis",
232 "Colored disassembly of strings of hex bytes")),
233 cl::cat(MCCategory
));
235 static const Target
*GetTarget(const char *ProgName
) {
236 // Figure out the target triple.
237 if (TripleName
.empty())
238 TripleName
= sys::getDefaultTargetTriple();
239 Triple
TheTriple(Triple::normalize(TripleName
));
241 // Get the target specific parser.
243 const Target
*TheTarget
= TargetRegistry::lookupTarget(ArchName
, TheTriple
,
246 WithColor::error(errs(), ProgName
) << Error
;
250 // Update the triple name and return the found target.
251 TripleName
= TheTriple
.getTriple();
255 static std::unique_ptr
<ToolOutputFile
> GetOutputStream(StringRef Path
,
256 sys::fs::OpenFlags Flags
) {
258 auto Out
= std::make_unique
<ToolOutputFile
>(Path
, EC
, Flags
);
260 WithColor::error() << EC
.message() << '\n';
267 static std::string DwarfDebugFlags
;
268 static void setDwarfDebugFlags(int argc
, char **argv
) {
269 if (!getenv("RC_DEBUG_OPTIONS"))
271 for (int i
= 0; i
< argc
; i
++) {
272 DwarfDebugFlags
+= argv
[i
];
274 DwarfDebugFlags
+= " ";
278 static std::string DwarfDebugProducer
;
279 static void setDwarfDebugProducer() {
280 if(!getenv("DEBUG_PRODUCER"))
282 DwarfDebugProducer
+= getenv("DEBUG_PRODUCER");
285 static int AsLexInput(SourceMgr
&SrcMgr
, MCAsmInfo
&MAI
,
289 Lexer
.setBuffer(SrcMgr
.getMemoryBuffer(SrcMgr
.getMainFileID())->getBuffer());
292 while (Lexer
.Lex().isNot(AsmToken::Eof
)) {
293 Lexer
.getTok().dump(OS
);
295 if (Lexer
.getTok().getKind() == AsmToken::Error
)
302 static int fillCommandLineSymbols(MCAsmParser
&Parser
) {
303 for (auto &I
: DefineSymbol
) {
304 auto Pair
= StringRef(I
).split('=');
305 auto Sym
= Pair
.first
;
306 auto Val
= Pair
.second
;
308 if (Sym
.empty() || Val
.empty()) {
309 WithColor::error() << "defsym must be of the form: sym=value: " << I
314 if (Val
.getAsInteger(0, Value
)) {
315 WithColor::error() << "value is not an integer: " << Val
<< "\n";
318 Parser
.getContext().setSymbolValue(Parser
.getStreamer(), Sym
, Value
);
323 static int AssembleInput(const char *ProgName
, const Target
*TheTarget
,
324 SourceMgr
&SrcMgr
, MCContext
&Ctx
, MCStreamer
&Str
,
325 MCAsmInfo
&MAI
, MCSubtargetInfo
&STI
,
326 MCInstrInfo
&MCII
, MCTargetOptions
const &MCOptions
) {
327 std::unique_ptr
<MCAsmParser
> Parser(
328 createMCAsmParser(SrcMgr
, Ctx
, Str
, MAI
));
329 std::unique_ptr
<MCTargetAsmParser
> TAP(
330 TheTarget
->createMCAsmParser(STI
, *Parser
, MCII
, MCOptions
));
333 WithColor::error(errs(), ProgName
)
334 << "this target does not support assembly parsing.\n";
338 int SymbolResult
= fillCommandLineSymbols(*Parser
);
341 Parser
->setShowParsedOperands(ShowInstOperands
);
342 Parser
->setTargetParser(*TAP
);
343 Parser
->getLexer().setLexMasmIntegers(LexMasmIntegers
);
344 Parser
->getLexer().setLexMasmHexFloats(LexMasmHexFloats
);
345 Parser
->getLexer().setLexMotorolaIntegers(LexMotorolaIntegers
);
347 int Res
= Parser
->Run(NoInitialTextSection
);
352 int main(int argc
, char **argv
) {
353 InitLLVM
X(argc
, argv
);
355 // Initialize targets and assembly printers/parsers.
356 llvm::InitializeAllTargetInfos();
357 llvm::InitializeAllTargetMCs();
358 llvm::InitializeAllAsmParsers();
359 llvm::InitializeAllDisassemblers();
361 // Register the target printer for --version.
362 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion
);
364 cl::HideUnrelatedOptions({&MCCategory
, &getColorCategory()});
365 cl::ParseCommandLineOptions(argc
, argv
, "llvm machine code playground\n");
366 const MCTargetOptions MCOptions
= mc::InitMCTargetOptionsFromFlags();
367 setDwarfDebugFlags(argc
, argv
);
369 setDwarfDebugProducer();
371 const char *ProgName
= argv
[0];
372 const Target
*TheTarget
= GetTarget(ProgName
);
375 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
376 // construct the Triple object.
377 Triple
TheTriple(TripleName
);
379 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufferPtr
=
380 MemoryBuffer::getFileOrSTDIN(InputFilename
, /*IsText=*/true);
381 if (std::error_code EC
= BufferPtr
.getError()) {
382 WithColor::error(errs(), ProgName
)
383 << InputFilename
<< ": " << EC
.message() << '\n';
386 MemoryBuffer
*Buffer
= BufferPtr
->get();
390 // Tell SrcMgr about this buffer, which is what the parser will pick up.
391 SrcMgr
.AddNewSourceBuffer(std::move(*BufferPtr
), SMLoc());
393 // Record the location of the include directories so that the lexer can find
395 SrcMgr
.setIncludeDirs(IncludeDirs
);
397 std::unique_ptr
<MCRegisterInfo
> MRI(TheTarget
->createMCRegInfo(TripleName
));
398 assert(MRI
&& "Unable to create target register info!");
400 std::unique_ptr
<MCAsmInfo
> MAI(
401 TheTarget
->createMCAsmInfo(*MRI
, TripleName
, MCOptions
));
402 assert(MAI
&& "Unable to create target asm info!");
404 MAI
->setRelaxELFRelocations(RelaxELFRel
);
405 if (CompressDebugSections
!= DebugCompressionType::None
) {
406 if (const char *Reason
= compression::getReasonIfUnsupported(
407 compression::formatFor(CompressDebugSections
))) {
408 WithColor::error(errs(), ProgName
)
409 << "--compress-debug-sections: " << Reason
;
413 MAI
->setCompressDebugSections(CompressDebugSections
);
414 MAI
->setPreserveAsmComments(PreserveComments
);
416 // Package up features to be passed to target/subtarget
417 std::string FeaturesStr
;
419 SubtargetFeatures Features
;
420 for (unsigned i
= 0; i
!= MAttrs
.size(); ++i
)
421 Features
.AddFeature(MAttrs
[i
]);
422 FeaturesStr
= Features
.getString();
425 std::unique_ptr
<MCSubtargetInfo
> STI(
426 TheTarget
->createMCSubtargetInfo(TripleName
, MCPU
, FeaturesStr
));
427 assert(STI
&& "Unable to create subtarget info!");
429 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
430 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
431 MCContext
Ctx(TheTriple
, MAI
.get(), MRI
.get(), STI
.get(), &SrcMgr
,
433 std::unique_ptr
<MCObjectFileInfo
> MOFI(
434 TheTarget
->createMCObjectFileInfo(Ctx
, PIC
, LargeCodeModel
));
435 Ctx
.setObjectFileInfo(MOFI
.get());
438 Ctx
.setAllowTemporaryLabels(false);
440 Ctx
.setGenDwarfForAssembly(GenDwarfForAssembly
);
441 // Default to 4 for dwarf version.
442 unsigned DwarfVersion
= MCOptions
.DwarfVersion
? MCOptions
.DwarfVersion
: 4;
443 if (DwarfVersion
< 2 || DwarfVersion
> 5) {
444 errs() << ProgName
<< ": Dwarf version " << DwarfVersion
445 << " is not supported." << '\n';
448 Ctx
.setDwarfVersion(DwarfVersion
);
449 if (MCOptions
.Dwarf64
) {
450 // The 64-bit DWARF format was introduced in DWARFv3.
451 if (DwarfVersion
< 3) {
453 << ": the 64-bit DWARF format is not supported for DWARF versions "
457 // 32-bit targets don't support DWARF64, which requires 64-bit relocations.
458 if (MAI
->getCodePointerSize() < 8) {
460 << ": the 64-bit DWARF format is only supported for 64-bit "
464 // If needsDwarfSectionOffsetDirective is true, we would eventually call
465 // MCStreamer::emitSymbolValue() with IsSectionRelative = true, but that
466 // is supported only for 4-byte long references.
467 if (MAI
->needsDwarfSectionOffsetDirective()) {
468 errs() << ProgName
<< ": the 64-bit DWARF format is not supported for "
469 << TheTriple
.normalize() << "\n";
472 Ctx
.setDwarfFormat(dwarf::DWARF64
);
474 if (!DwarfDebugFlags
.empty())
475 Ctx
.setDwarfDebugFlags(StringRef(DwarfDebugFlags
));
476 if (!DwarfDebugProducer
.empty())
477 Ctx
.setDwarfDebugProducer(StringRef(DwarfDebugProducer
));
478 if (!DebugCompilationDir
.empty())
479 Ctx
.setCompilationDir(DebugCompilationDir
);
481 // If no compilation dir is set, try to use the current directory.
482 SmallString
<128> CWD
;
483 if (!sys::fs::current_path(CWD
))
484 Ctx
.setCompilationDir(CWD
);
486 for (const auto &Arg
: DebugPrefixMap
) {
487 const auto &KV
= StringRef(Arg
).split('=');
488 Ctx
.addDebugPrefixMapEntry(std::string(KV
.first
), std::string(KV
.second
));
490 if (!MainFileName
.empty())
491 Ctx
.setMainFileName(MainFileName
);
492 if (GenDwarfForAssembly
)
493 Ctx
.setGenDwarfRootFile(InputFilename
, Buffer
->getBuffer());
495 sys::fs::OpenFlags Flags
= (FileType
== OFT_AssemblyFile
)
496 ? sys::fs::OF_TextWithCRLF
498 std::unique_ptr
<ToolOutputFile
> Out
= GetOutputStream(OutputFilename
, Flags
);
502 std::unique_ptr
<ToolOutputFile
> DwoOut
;
503 if (!SplitDwarfFile
.empty()) {
504 if (FileType
!= OFT_ObjectFile
) {
505 WithColor::error() << "dwo output only supported with object files\n";
508 DwoOut
= GetOutputStream(SplitDwarfFile
, sys::fs::OF_None
);
513 std::unique_ptr
<buffer_ostream
> BOS
;
514 raw_pwrite_stream
*OS
= &Out
->os();
515 std::unique_ptr
<MCStreamer
> Str
;
517 std::unique_ptr
<MCInstrInfo
> MCII(TheTarget
->createMCInstrInfo());
518 assert(MCII
&& "Unable to create instruction info!");
520 MCInstPrinter
*IP
= nullptr;
521 if (FileType
== OFT_AssemblyFile
) {
522 IP
= TheTarget
->createMCInstPrinter(Triple(TripleName
), OutputAsmVariant
,
527 << "unable to create instruction printer for target triple '"
528 << TheTriple
.normalize() << "' with assembly variant "
529 << OutputAsmVariant
<< ".\n";
533 for (StringRef Opt
: DisassemblerOptions
)
534 if (!IP
->applyTargetSpecificCLOption(Opt
)) {
535 WithColor::error() << "invalid disassembler option '" << Opt
<< "'\n";
539 // Set the display preference for hex vs. decimal immediates.
540 IP
->setPrintImmHex(PrintImmHex
);
542 // Set up the AsmStreamer.
543 std::unique_ptr
<MCCodeEmitter
> CE
;
545 CE
.reset(TheTarget
->createMCCodeEmitter(*MCII
, Ctx
));
547 std::unique_ptr
<MCAsmBackend
> MAB(
548 TheTarget
->createMCAsmBackend(*STI
, *MRI
, MCOptions
));
549 auto FOut
= std::make_unique
<formatted_raw_ostream
>(*OS
);
550 // FIXME: Workaround for bug in formatted_raw_ostream. Color escape codes
551 // are (incorrectly) written directly to the unbuffered raw_ostream wrapped
552 // by the formatted_raw_ostream.
553 if (Action
== AC_CDisassemble
)
554 FOut
->SetUnbuffered();
556 TheTarget
->createAsmStreamer(Ctx
, std::move(FOut
), /*asmverbose*/ true,
557 /*useDwarfDirectory*/ true, IP
,
558 std::move(CE
), std::move(MAB
), ShowInst
));
560 } else if (FileType
== OFT_Null
) {
561 Str
.reset(TheTarget
->createNullStreamer(Ctx
));
563 assert(FileType
== OFT_ObjectFile
&& "Invalid file type!");
565 if (!Out
->os().supportsSeeking()) {
566 BOS
= std::make_unique
<buffer_ostream
>(Out
->os());
570 MCCodeEmitter
*CE
= TheTarget
->createMCCodeEmitter(*MCII
, Ctx
);
571 MCAsmBackend
*MAB
= TheTarget
->createMCAsmBackend(*STI
, *MRI
, MCOptions
);
572 Str
.reset(TheTarget
->createMCObjectStreamer(
573 TheTriple
, Ctx
, std::unique_ptr
<MCAsmBackend
>(MAB
),
574 DwoOut
? MAB
->createDwoObjectWriter(*OS
, DwoOut
->os())
575 : MAB
->createObjectWriter(*OS
),
576 std::unique_ptr
<MCCodeEmitter
>(CE
), *STI
, MCOptions
.MCRelaxAll
,
577 MCOptions
.MCIncrementalLinkerCompatible
,
578 /*DWARFMustBeAtTheEnd*/ false));
580 Str
->initSections(true, *STI
);
583 // Use Assembler information for parsing.
584 Str
->setUseAssemblerInfoForParsing(true);
587 bool disassemble
= false;
590 Res
= AsLexInput(SrcMgr
, *MAI
, Out
->os());
593 Res
= AssembleInput(ProgName
, TheTarget
, SrcMgr
, Ctx
, *Str
, *MAI
, *STI
,
596 case AC_MDisassemble
:
597 IP
->setUseMarkup(true);
600 case AC_CDisassemble
:
601 IP
->setUseColor(true);
609 Res
= Disassembler::disassemble(*TheTarget
, TripleName
, *STI
, *Str
, *Buffer
,
610 SrcMgr
, Ctx
, MCOptions
);
612 // Keep output if no errors.