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.inc"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Compression.h"
31 #include "llvm/Support/FileUtilities.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/Host.h"
34 #include "llvm/Support/InitLLVM.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Support/TargetSelect.h"
39 #include "llvm/Support/ToolOutputFile.h"
40 #include "llvm/Support/WithColor.h"
44 static cl::opt
<std::string
>
45 InputFilename(cl::Positional
, cl::desc("<input file>"), cl::init("-"));
47 static cl::opt
<std::string
> OutputFilename("o", cl::desc("Output filename"),
48 cl::value_desc("filename"),
51 static cl::opt
<std::string
> SplitDwarfFile("split-dwarf-file",
52 cl::desc("DWO output filename"),
53 cl::value_desc("filename"));
56 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
58 static cl::opt
<bool> RelaxELFRel(
59 "relax-relocations", cl::init(true),
60 cl::desc("Emit R_X86_64_GOTPCRELX instead of R_X86_64_GOTPCREL"));
62 static cl::opt
<DebugCompressionType
> CompressDebugSections(
63 "compress-debug-sections", cl::ValueOptional
,
64 cl::init(DebugCompressionType::None
),
65 cl::desc("Choose DWARF debug sections compression:"),
66 cl::values(clEnumValN(DebugCompressionType::None
, "none", "No compression"),
67 clEnumValN(DebugCompressionType::Z
, "zlib",
68 "Use zlib compression"),
69 clEnumValN(DebugCompressionType::GNU
, "zlib-gnu",
70 "Use zlib-gnu compression (deprecated)")));
73 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
76 ShowInstOperands("show-inst-operands",
77 cl::desc("Show instructions operands as parsed"));
79 static cl::opt
<unsigned>
80 OutputAsmVariant("output-asm-variant",
81 cl::desc("Syntax variant to use for output printing"));
84 PrintImmHex("print-imm-hex", cl::init(false),
85 cl::desc("Prefer hex format for immediate values"));
87 static cl::list
<std::string
>
88 DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
91 PreserveComments("preserve-comments",
92 cl::desc("Preserve Comments in outputted assembly"));
99 static cl::opt
<OutputFileType
>
100 FileType("filetype", cl::init(OFT_AssemblyFile
),
101 cl::desc("Choose an output file type:"),
103 clEnumValN(OFT_AssemblyFile
, "asm",
104 "Emit an assembly ('.s') file"),
105 clEnumValN(OFT_Null
, "null",
106 "Don't emit anything (for timing purposes)"),
107 clEnumValN(OFT_ObjectFile
, "obj",
108 "Emit a native object ('.o') file")));
110 static cl::list
<std::string
>
111 IncludeDirs("I", cl::desc("Directory of include files"),
112 cl::value_desc("directory"), cl::Prefix
);
114 static cl::opt
<std::string
>
115 ArchName("arch", cl::desc("Target arch to assemble for, "
116 "see -version for available targets"));
118 static cl::opt
<std::string
>
119 TripleName("triple", cl::desc("Target triple to assemble for, "
120 "see -version for available targets"));
122 static cl::opt
<std::string
>
124 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
125 cl::value_desc("cpu-name"),
128 static cl::list
<std::string
>
131 cl::desc("Target specific attributes (-mattr=help for details)"),
132 cl::value_desc("a1,+a2,-a3,..."));
134 static cl::opt
<bool> PIC("position-independent",
135 cl::desc("Position independent"), cl::init(false));
138 LargeCodeModel("large-code-model",
139 cl::desc("Create cfi directives that assume the code might "
140 "be more than 2gb away"));
143 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
144 "in the text section"));
147 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
150 static cl::opt
<std::string
>
151 DebugCompilationDir("fdebug-compilation-dir",
152 cl::desc("Specifies the debug info's compilation dir"));
154 static cl::list
<std::string
>
155 DebugPrefixMap("fdebug-prefix-map",
156 cl::desc("Map file source paths in debug info"),
157 cl::value_desc("= separated key-value pairs"));
159 static cl::opt
<std::string
>
160 MainFileName("main-file-name",
161 cl::desc("Specifies the name we should consider the input file"));
163 static cl::opt
<bool> SaveTempLabels("save-temp-labels",
164 cl::desc("Don't discard temporary labels"));
166 static cl::opt
<bool> LexMasmIntegers(
168 cl::desc("Enable binary and hex masm integers (0b110 and 0ABCh)"));
170 static cl::opt
<bool> NoExecStack("no-exec-stack",
171 cl::desc("File doesn't need an exec stack"));
180 static cl::opt
<ActionType
>
181 Action(cl::desc("Action to perform:"),
182 cl::init(AC_Assemble
),
183 cl::values(clEnumValN(AC_AsLex
, "as-lex",
184 "Lex tokens from a .s file"),
185 clEnumValN(AC_Assemble
, "assemble",
186 "Assemble a .s file (default)"),
187 clEnumValN(AC_Disassemble
, "disassemble",
188 "Disassemble strings of hex bytes"),
189 clEnumValN(AC_MDisassemble
, "mdis",
190 "Marked up disassembly of strings of hex bytes")));
192 static const Target
*GetTarget(const char *ProgName
) {
193 // Figure out the target triple.
194 if (TripleName
.empty())
195 TripleName
= sys::getDefaultTargetTriple();
196 Triple
TheTriple(Triple::normalize(TripleName
));
198 // Get the target specific parser.
200 const Target
*TheTarget
= TargetRegistry::lookupTarget(ArchName
, TheTriple
,
203 WithColor::error(errs(), ProgName
) << Error
;
207 // Update the triple name and return the found target.
208 TripleName
= TheTriple
.getTriple();
212 static std::unique_ptr
<ToolOutputFile
> GetOutputStream(StringRef Path
) {
214 auto Out
= llvm::make_unique
<ToolOutputFile
>(Path
, EC
, sys::fs::F_None
);
216 WithColor::error() << EC
.message() << '\n';
223 static std::string DwarfDebugFlags
;
224 static void setDwarfDebugFlags(int argc
, char **argv
) {
225 if (!getenv("RC_DEBUG_OPTIONS"))
227 for (int i
= 0; i
< argc
; i
++) {
228 DwarfDebugFlags
+= argv
[i
];
230 DwarfDebugFlags
+= " ";
234 static std::string DwarfDebugProducer
;
235 static void setDwarfDebugProducer() {
236 if(!getenv("DEBUG_PRODUCER"))
238 DwarfDebugProducer
+= getenv("DEBUG_PRODUCER");
241 static int AsLexInput(SourceMgr
&SrcMgr
, MCAsmInfo
&MAI
,
245 Lexer
.setBuffer(SrcMgr
.getMemoryBuffer(SrcMgr
.getMainFileID())->getBuffer());
248 while (Lexer
.Lex().isNot(AsmToken::Eof
)) {
249 Lexer
.getTok().dump(OS
);
251 if (Lexer
.getTok().getKind() == AsmToken::Error
)
258 static int fillCommandLineSymbols(MCAsmParser
&Parser
) {
259 for (auto &I
: DefineSymbol
) {
260 auto Pair
= StringRef(I
).split('=');
261 auto Sym
= Pair
.first
;
262 auto Val
= Pair
.second
;
264 if (Sym
.empty() || Val
.empty()) {
265 WithColor::error() << "defsym must be of the form: sym=value: " << I
270 if (Val
.getAsInteger(0, Value
)) {
271 WithColor::error() << "value is not an integer: " << Val
<< "\n";
274 Parser
.getContext().setSymbolValue(Parser
.getStreamer(), Sym
, Value
);
279 static int AssembleInput(const char *ProgName
, const Target
*TheTarget
,
280 SourceMgr
&SrcMgr
, MCContext
&Ctx
, MCStreamer
&Str
,
281 MCAsmInfo
&MAI
, MCSubtargetInfo
&STI
,
282 MCInstrInfo
&MCII
, MCTargetOptions
&MCOptions
) {
283 std::unique_ptr
<MCAsmParser
> Parser(
284 createMCAsmParser(SrcMgr
, Ctx
, Str
, MAI
));
285 std::unique_ptr
<MCTargetAsmParser
> TAP(
286 TheTarget
->createMCAsmParser(STI
, *Parser
, MCII
, MCOptions
));
289 WithColor::error(errs(), ProgName
)
290 << "this target does not support assembly parsing.\n";
294 int SymbolResult
= fillCommandLineSymbols(*Parser
);
297 Parser
->setShowParsedOperands(ShowInstOperands
);
298 Parser
->setTargetParser(*TAP
);
299 Parser
->getLexer().setLexMasmIntegers(LexMasmIntegers
);
301 int Res
= Parser
->Run(NoInitialTextSection
);
306 int main(int argc
, char **argv
) {
307 InitLLVM
X(argc
, argv
);
309 // Initialize targets and assembly printers/parsers.
310 llvm::InitializeAllTargetInfos();
311 llvm::InitializeAllTargetMCs();
312 llvm::InitializeAllAsmParsers();
313 llvm::InitializeAllDisassemblers();
315 // Register the target printer for --version.
316 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion
);
318 cl::ParseCommandLineOptions(argc
, argv
, "llvm machine code playground\n");
319 MCTargetOptions MCOptions
= InitMCTargetOptionsFromFlags();
320 setDwarfDebugFlags(argc
, argv
);
322 setDwarfDebugProducer();
324 const char *ProgName
= argv
[0];
325 const Target
*TheTarget
= GetTarget(ProgName
);
328 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
329 // construct the Triple object.
330 Triple
TheTriple(TripleName
);
332 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufferPtr
=
333 MemoryBuffer::getFileOrSTDIN(InputFilename
);
334 if (std::error_code EC
= BufferPtr
.getError()) {
335 WithColor::error(errs(), ProgName
)
336 << InputFilename
<< ": " << EC
.message() << '\n';
339 MemoryBuffer
*Buffer
= BufferPtr
->get();
343 // Tell SrcMgr about this buffer, which is what the parser will pick up.
344 SrcMgr
.AddNewSourceBuffer(std::move(*BufferPtr
), SMLoc());
346 // Record the location of the include directories so that the lexer can find
348 SrcMgr
.setIncludeDirs(IncludeDirs
);
350 std::unique_ptr
<MCRegisterInfo
> MRI(TheTarget
->createMCRegInfo(TripleName
));
351 assert(MRI
&& "Unable to create target register info!");
353 std::unique_ptr
<MCAsmInfo
> MAI(TheTarget
->createMCAsmInfo(*MRI
, TripleName
));
354 assert(MAI
&& "Unable to create target asm info!");
356 MAI
->setRelaxELFRelocations(RelaxELFRel
);
358 if (CompressDebugSections
!= DebugCompressionType::None
) {
359 if (!zlib::isAvailable()) {
360 WithColor::error(errs(), ProgName
)
361 << "build tools with zlib to enable -compress-debug-sections";
364 MAI
->setCompressDebugSections(CompressDebugSections
);
366 MAI
->setPreserveAsmComments(PreserveComments
);
368 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
369 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
370 MCObjectFileInfo MOFI
;
371 MCContext
Ctx(MAI
.get(), MRI
.get(), &MOFI
, &SrcMgr
);
372 MOFI
.InitMCObjectFileInfo(TheTriple
, PIC
, Ctx
, LargeCodeModel
);
375 Ctx
.setAllowTemporaryLabels(false);
377 Ctx
.setGenDwarfForAssembly(GenDwarfForAssembly
);
378 // Default to 4 for dwarf version.
379 unsigned DwarfVersion
= MCOptions
.DwarfVersion
? MCOptions
.DwarfVersion
: 4;
380 if (DwarfVersion
< 2 || DwarfVersion
> 5) {
381 errs() << ProgName
<< ": Dwarf version " << DwarfVersion
382 << " is not supported." << '\n';
385 Ctx
.setDwarfVersion(DwarfVersion
);
386 if (!DwarfDebugFlags
.empty())
387 Ctx
.setDwarfDebugFlags(StringRef(DwarfDebugFlags
));
388 if (!DwarfDebugProducer
.empty())
389 Ctx
.setDwarfDebugProducer(StringRef(DwarfDebugProducer
));
390 if (!DebugCompilationDir
.empty())
391 Ctx
.setCompilationDir(DebugCompilationDir
);
393 // If no compilation dir is set, try to use the current directory.
394 SmallString
<128> CWD
;
395 if (!sys::fs::current_path(CWD
))
396 Ctx
.setCompilationDir(CWD
);
398 for (const auto &Arg
: DebugPrefixMap
) {
399 const auto &KV
= StringRef(Arg
).split('=');
400 Ctx
.addDebugPrefixMapEntry(KV
.first
, KV
.second
);
402 if (!MainFileName
.empty())
403 Ctx
.setMainFileName(MainFileName
);
404 if (GenDwarfForAssembly
&& DwarfVersion
>= 5) {
405 // DWARF v5 needs the root file as well as the compilation directory.
406 // If we find a '.file 0' directive that will supersede these values.
408 MD5::MD5Result
*Cksum
=
409 (MD5::MD5Result
*)Ctx
.allocate(sizeof(MD5::MD5Result
), 1);
410 Hash
.update(Buffer
->getBuffer());
412 Ctx
.setMCLineTableRootFile(
413 /*CUID=*/0, Ctx
.getCompilationDir(),
414 !MainFileName
.empty() ? MainFileName
: InputFilename
, Cksum
, None
);
417 // Package up features to be passed to target/subtarget
418 std::string FeaturesStr
;
420 SubtargetFeatures Features
;
421 for (unsigned i
= 0; i
!= MAttrs
.size(); ++i
)
422 Features
.AddFeature(MAttrs
[i
]);
423 FeaturesStr
= Features
.getString();
426 std::unique_ptr
<ToolOutputFile
> Out
= GetOutputStream(OutputFilename
);
430 std::unique_ptr
<ToolOutputFile
> DwoOut
;
431 if (!SplitDwarfFile
.empty()) {
432 if (FileType
!= OFT_ObjectFile
) {
433 WithColor::error() << "dwo output only supported with object files\n";
436 DwoOut
= GetOutputStream(SplitDwarfFile
);
441 std::unique_ptr
<buffer_ostream
> BOS
;
442 raw_pwrite_stream
*OS
= &Out
->os();
443 std::unique_ptr
<MCStreamer
> Str
;
445 std::unique_ptr
<MCInstrInfo
> MCII(TheTarget
->createMCInstrInfo());
446 std::unique_ptr
<MCSubtargetInfo
> STI(
447 TheTarget
->createMCSubtargetInfo(TripleName
, MCPU
, FeaturesStr
));
449 MCInstPrinter
*IP
= nullptr;
450 if (FileType
== OFT_AssemblyFile
) {
451 IP
= TheTarget
->createMCInstPrinter(Triple(TripleName
), OutputAsmVariant
,
456 << "unable to create instruction printer for target triple '"
457 << TheTriple
.normalize() << "' with assembly variant "
458 << OutputAsmVariant
<< ".\n";
462 // Set the display preference for hex vs. decimal immediates.
463 IP
->setPrintImmHex(PrintImmHex
);
465 // Set up the AsmStreamer.
466 std::unique_ptr
<MCCodeEmitter
> CE
;
468 CE
.reset(TheTarget
->createMCCodeEmitter(*MCII
, *MRI
, Ctx
));
470 std::unique_ptr
<MCAsmBackend
> MAB(
471 TheTarget
->createMCAsmBackend(*STI
, *MRI
, MCOptions
));
472 auto FOut
= llvm::make_unique
<formatted_raw_ostream
>(*OS
);
474 TheTarget
->createAsmStreamer(Ctx
, std::move(FOut
), /*asmverbose*/ true,
475 /*useDwarfDirectory*/ true, IP
,
476 std::move(CE
), std::move(MAB
), ShowInst
));
478 } else if (FileType
== OFT_Null
) {
479 Str
.reset(TheTarget
->createNullStreamer(Ctx
));
481 assert(FileType
== OFT_ObjectFile
&& "Invalid file type!");
483 // Don't waste memory on names of temp labels.
484 Ctx
.setUseNamesOnTempLabels(false);
486 if (!Out
->os().supportsSeeking()) {
487 BOS
= make_unique
<buffer_ostream
>(Out
->os());
491 MCCodeEmitter
*CE
= TheTarget
->createMCCodeEmitter(*MCII
, *MRI
, Ctx
);
492 MCAsmBackend
*MAB
= TheTarget
->createMCAsmBackend(*STI
, *MRI
, MCOptions
);
493 Str
.reset(TheTarget
->createMCObjectStreamer(
494 TheTriple
, Ctx
, std::unique_ptr
<MCAsmBackend
>(MAB
),
495 DwoOut
? MAB
->createDwoObjectWriter(*OS
, DwoOut
->os())
496 : MAB
->createObjectWriter(*OS
),
497 std::unique_ptr
<MCCodeEmitter
>(CE
), *STI
, MCOptions
.MCRelaxAll
,
498 MCOptions
.MCIncrementalLinkerCompatible
,
499 /*DWARFMustBeAtTheEnd*/ false));
501 Str
->InitSections(true);
504 // Use Assembler information for parsing.
505 Str
->setUseAssemblerInfoForParsing(true);
508 bool disassemble
= false;
511 Res
= AsLexInput(SrcMgr
, *MAI
, Out
->os());
514 Res
= AssembleInput(ProgName
, TheTarget
, SrcMgr
, Ctx
, *Str
, *MAI
, *STI
,
517 case AC_MDisassemble
:
518 assert(IP
&& "Expected assembly output");
527 Res
= Disassembler::disassemble(*TheTarget
, TripleName
, *STI
, *Str
,
528 *Buffer
, SrcMgr
, Out
->os());
530 // Keep output if no errors.