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/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 mc::RegisterMCTargetOptionsFlags MOF;
46 static cl::opt<std::string>
47 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
49 static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
50 cl::value_desc("filename"),
53 static cl::opt<std::string> SplitDwarfFile("split-dwarf-file",
54 cl::desc("DWO output filename"),
55 cl::value_desc("filename"));
58 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
60 static cl::opt<bool> RelaxELFRel(
61 "relax-relocations", cl::init(true),
62 cl::desc("Emit R_X86_64_GOTPCRELX instead of R_X86_64_GOTPCREL"));
64 static cl::opt<DebugCompressionType> CompressDebugSections(
65 "compress-debug-sections", cl::ValueOptional,
66 cl::init(DebugCompressionType::None),
67 cl::desc("Choose DWARF debug sections compression:"),
68 cl::values(clEnumValN(DebugCompressionType::None, "none", "No compression"),
69 clEnumValN(DebugCompressionType::Z, "zlib",
70 "Use zlib compression"),
71 clEnumValN(DebugCompressionType::GNU, "zlib-gnu",
72 "Use zlib-gnu compression (deprecated)")));
75 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
78 ShowInstOperands("show-inst-operands",
79 cl::desc("Show instructions operands as parsed"));
81 static cl::opt<unsigned>
82 OutputAsmVariant("output-asm-variant",
83 cl::desc("Syntax variant to use for output printing"));
86 PrintImmHex("print-imm-hex", cl::init(false),
87 cl::desc("Prefer hex format for immediate values"));
89 static cl::list<std::string>
90 DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
93 PreserveComments("preserve-comments",
94 cl::desc("Preserve Comments in outputted assembly"));
101 static cl::opt<OutputFileType>
102 FileType("filetype", cl::init(OFT_AssemblyFile),
103 cl::desc("Choose an output file type:"),
105 clEnumValN(OFT_AssemblyFile, "asm",
106 "Emit an assembly ('.s') file"),
107 clEnumValN(OFT_Null, "null",
108 "Don't emit anything (for timing purposes)"),
109 clEnumValN(OFT_ObjectFile, "obj",
110 "Emit a native object ('.o') file")));
112 static cl::list<std::string>
113 IncludeDirs("I", cl::desc("Directory of include files"),
114 cl::value_desc("directory"), cl::Prefix);
116 static cl::opt<std::string>
117 ArchName("arch", cl::desc("Target arch to assemble for, "
118 "see -version for available targets"));
120 static cl::opt<std::string>
121 TripleName("triple", cl::desc("Target triple to assemble for, "
122 "see -version for available targets"));
124 static cl::opt<std::string>
126 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
127 cl::value_desc("cpu-name"),
130 static cl::list<std::string>
133 cl::desc("Target specific attributes (-mattr=help for details)"),
134 cl::value_desc("a1,+a2,-a3,..."));
136 static cl::opt<bool> PIC("position-independent",
137 cl::desc("Position independent"), cl::init(false));
140 LargeCodeModel("large-code-model",
141 cl::desc("Create cfi directives that assume the code might "
142 "be more than 2gb away"));
145 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
146 "in the text section"));
149 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
152 static cl::opt<std::string>
153 DebugCompilationDir("fdebug-compilation-dir",
154 cl::desc("Specifies the debug info's compilation dir"));
156 static cl::list<std::string>
157 DebugPrefixMap("fdebug-prefix-map",
158 cl::desc("Map file source paths in debug info"),
159 cl::value_desc("= separated key-value pairs"));
161 static cl::opt<std::string>
162 MainFileName("main-file-name",
163 cl::desc("Specifies the name we should consider the input file"));
165 static cl::opt<bool> SaveTempLabels("save-temp-labels",
166 cl::desc("Don't discard temporary labels"));
168 static cl::opt<bool> LexMasmIntegers(
170 cl::desc("Enable binary and hex masm integers (0b110 and 0ABCh)"));
172 static cl::opt<bool> NoExecStack("no-exec-stack",
173 cl::desc("File doesn't need an exec stack"));
182 static cl::opt<ActionType>
183 Action(cl::desc("Action to perform:"),
184 cl::init(AC_Assemble),
185 cl::values(clEnumValN(AC_AsLex, "as-lex",
186 "Lex tokens from a .s file"),
187 clEnumValN(AC_Assemble, "assemble",
188 "Assemble a .s file (default)"),
189 clEnumValN(AC_Disassemble, "disassemble",
190 "Disassemble strings of hex bytes"),
191 clEnumValN(AC_MDisassemble, "mdis",
192 "Marked up disassembly of strings of hex bytes")));
194 static const Target *GetTarget(const char *ProgName) {
195 // Figure out the target triple.
196 if (TripleName.empty())
197 TripleName = sys::getDefaultTargetTriple();
198 Triple TheTriple(Triple::normalize(TripleName));
200 // Get the target specific parser.
202 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
205 WithColor::error(errs(), ProgName) << Error;
209 // Update the triple name and return the found target.
210 TripleName = TheTriple.getTriple();
214 static std::unique_ptr<ToolOutputFile> GetOutputStream(StringRef Path,
215 sys::fs::OpenFlags Flags) {
217 auto Out = std::make_unique<ToolOutputFile>(Path, EC, Flags);
219 WithColor::error() << EC.message() << '\n';
226 static std::string DwarfDebugFlags;
227 static void setDwarfDebugFlags(int argc, char **argv) {
228 if (!getenv("RC_DEBUG_OPTIONS"))
230 for (int i = 0; i < argc; i++) {
231 DwarfDebugFlags += argv[i];
233 DwarfDebugFlags += " ";
237 static std::string DwarfDebugProducer;
238 static void setDwarfDebugProducer() {
239 if(!getenv("DEBUG_PRODUCER"))
241 DwarfDebugProducer += getenv("DEBUG_PRODUCER");
244 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
248 Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
251 while (Lexer.Lex().isNot(AsmToken::Eof)) {
252 Lexer.getTok().dump(OS);
254 if (Lexer.getTok().getKind() == AsmToken::Error)
261 static int fillCommandLineSymbols(MCAsmParser &Parser) {
262 for (auto &I: DefineSymbol) {
263 auto Pair = StringRef(I).split('=');
264 auto Sym = Pair.first;
265 auto Val = Pair.second;
267 if (Sym.empty() || Val.empty()) {
268 WithColor::error() << "defsym must be of the form: sym=value: " << I
273 if (Val.getAsInteger(0, Value)) {
274 WithColor::error() << "value is not an integer: " << Val << "\n";
277 Parser.getContext().setSymbolValue(Parser.getStreamer(), Sym, Value);
282 static int AssembleInput(const char *ProgName, const Target *TheTarget,
283 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
284 MCAsmInfo &MAI, MCSubtargetInfo &STI,
285 MCInstrInfo &MCII, MCTargetOptions const &MCOptions) {
286 std::unique_ptr<MCAsmParser> Parser(
287 createMCAsmParser(SrcMgr, Ctx, Str, MAI));
288 std::unique_ptr<MCTargetAsmParser> TAP(
289 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
292 WithColor::error(errs(), ProgName)
293 << "this target does not support assembly parsing.\n";
297 int SymbolResult = fillCommandLineSymbols(*Parser);
300 Parser->setShowParsedOperands(ShowInstOperands);
301 Parser->setTargetParser(*TAP);
302 Parser->getLexer().setLexMasmIntegers(LexMasmIntegers);
304 int Res = Parser->Run(NoInitialTextSection);
309 int main(int argc, char **argv) {
310 InitLLVM X(argc, argv);
312 // Initialize targets and assembly printers/parsers.
313 llvm::InitializeAllTargetInfos();
314 llvm::InitializeAllTargetMCs();
315 llvm::InitializeAllAsmParsers();
316 llvm::InitializeAllDisassemblers();
318 // Register the target printer for --version.
319 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
321 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
322 const MCTargetOptions MCOptions = mc::InitMCTargetOptionsFromFlags();
323 setDwarfDebugFlags(argc, argv);
325 setDwarfDebugProducer();
327 const char *ProgName = argv[0];
328 const Target *TheTarget = GetTarget(ProgName);
331 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
332 // construct the Triple object.
333 Triple TheTriple(TripleName);
335 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
336 MemoryBuffer::getFileOrSTDIN(InputFilename);
337 if (std::error_code EC = BufferPtr.getError()) {
338 WithColor::error(errs(), ProgName)
339 << InputFilename << ": " << EC.message() << '\n';
342 MemoryBuffer *Buffer = BufferPtr->get();
346 // Tell SrcMgr about this buffer, which is what the parser will pick up.
347 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
349 // Record the location of the include directories so that the lexer can find
351 SrcMgr.setIncludeDirs(IncludeDirs);
353 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
354 assert(MRI && "Unable to create target register info!");
356 std::unique_ptr<MCAsmInfo> MAI(
357 TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
358 assert(MAI && "Unable to create target asm info!");
360 MAI->setRelaxELFRelocations(RelaxELFRel);
362 if (CompressDebugSections != DebugCompressionType::None) {
363 if (!zlib::isAvailable()) {
364 WithColor::error(errs(), ProgName)
365 << "build tools with zlib to enable -compress-debug-sections";
368 MAI->setCompressDebugSections(CompressDebugSections);
370 MAI->setPreserveAsmComments(PreserveComments);
372 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
373 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
374 MCObjectFileInfo MOFI;
375 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr, &MCOptions);
376 MOFI.InitMCObjectFileInfo(TheTriple, PIC, Ctx, LargeCodeModel);
379 Ctx.setAllowTemporaryLabels(false);
381 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
382 // Default to 4 for dwarf version.
383 unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
384 if (DwarfVersion < 2 || DwarfVersion > 5) {
385 errs() << ProgName << ": Dwarf version " << DwarfVersion
386 << " is not supported." << '\n';
389 Ctx.setDwarfVersion(DwarfVersion);
390 if (MCOptions.Dwarf64) {
391 // The 64-bit DWARF format was introduced in DWARFv3.
392 if (DwarfVersion < 3) {
394 << ": the 64-bit DWARF format is not supported for DWARF versions "
398 // 32-bit targets don't support DWARF64, which requires 64-bit relocations.
399 if (MAI->getCodePointerSize() < 8) {
401 << ": the 64-bit DWARF format is only supported for 64-bit "
405 // If needsDwarfSectionOffsetDirective is true, we would eventually call
406 // MCStreamer::emitSymbolValue() with IsSectionRelative = true, but that
407 // is supported only for 4-byte long references.
408 if (MAI->needsDwarfSectionOffsetDirective()) {
409 errs() << ProgName << ": the 64-bit DWARF format is not supported for "
410 << TheTriple.normalize() << "\n";
413 Ctx.setDwarfFormat(dwarf::DWARF64);
415 if (!DwarfDebugFlags.empty())
416 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
417 if (!DwarfDebugProducer.empty())
418 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
419 if (!DebugCompilationDir.empty())
420 Ctx.setCompilationDir(DebugCompilationDir);
422 // If no compilation dir is set, try to use the current directory.
423 SmallString<128> CWD;
424 if (!sys::fs::current_path(CWD))
425 Ctx.setCompilationDir(CWD);
427 for (const auto &Arg : DebugPrefixMap) {
428 const auto &KV = StringRef(Arg).split('=');
429 Ctx.addDebugPrefixMapEntry(std::string(KV.first), std::string(KV.second));
431 if (!MainFileName.empty())
432 Ctx.setMainFileName(MainFileName);
433 if (GenDwarfForAssembly)
434 Ctx.setGenDwarfRootFile(InputFilename, Buffer->getBuffer());
436 // Package up features to be passed to target/subtarget
437 std::string FeaturesStr;
439 SubtargetFeatures Features;
440 for (unsigned i = 0; i != MAttrs.size(); ++i)
441 Features.AddFeature(MAttrs[i]);
442 FeaturesStr = Features.getString();
445 sys::fs::OpenFlags Flags = (FileType == OFT_AssemblyFile) ? sys::fs::OF_Text
447 std::unique_ptr<ToolOutputFile> Out = GetOutputStream(OutputFilename, Flags);
451 std::unique_ptr<ToolOutputFile> DwoOut;
452 if (!SplitDwarfFile.empty()) {
453 if (FileType != OFT_ObjectFile) {
454 WithColor::error() << "dwo output only supported with object files\n";
457 DwoOut = GetOutputStream(SplitDwarfFile, sys::fs::OF_None);
462 std::unique_ptr<buffer_ostream> BOS;
463 raw_pwrite_stream *OS = &Out->os();
464 std::unique_ptr<MCStreamer> Str;
466 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
467 std::unique_ptr<MCSubtargetInfo> STI(
468 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
470 MCInstPrinter *IP = nullptr;
471 if (FileType == OFT_AssemblyFile) {
472 IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
477 << "unable to create instruction printer for target triple '"
478 << TheTriple.normalize() << "' with assembly variant "
479 << OutputAsmVariant << ".\n";
483 // Set the display preference for hex vs. decimal immediates.
484 IP->setPrintImmHex(PrintImmHex);
486 // Set up the AsmStreamer.
487 std::unique_ptr<MCCodeEmitter> CE;
489 CE.reset(TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
491 std::unique_ptr<MCAsmBackend> MAB(
492 TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
493 auto FOut = std::make_unique<formatted_raw_ostream>(*OS);
495 TheTarget->createAsmStreamer(Ctx, std::move(FOut), /*asmverbose*/ true,
496 /*useDwarfDirectory*/ true, IP,
497 std::move(CE), std::move(MAB), ShowInst));
499 } else if (FileType == OFT_Null) {
500 Str.reset(TheTarget->createNullStreamer(Ctx));
502 assert(FileType == OFT_ObjectFile && "Invalid file type!");
504 if (!Out->os().supportsSeeking()) {
505 BOS = std::make_unique<buffer_ostream>(Out->os());
509 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
510 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions);
511 Str.reset(TheTarget->createMCObjectStreamer(
512 TheTriple, Ctx, std::unique_ptr<MCAsmBackend>(MAB),
513 DwoOut ? MAB->createDwoObjectWriter(*OS, DwoOut->os())
514 : MAB->createObjectWriter(*OS),
515 std::unique_ptr<MCCodeEmitter>(CE), *STI, MCOptions.MCRelaxAll,
516 MCOptions.MCIncrementalLinkerCompatible,
517 /*DWARFMustBeAtTheEnd*/ false));
519 Str->InitSections(true);
522 // Use Assembler information for parsing.
523 Str->setUseAssemblerInfoForParsing(true);
526 bool disassemble = false;
529 Res = AsLexInput(SrcMgr, *MAI, Out->os());
532 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
535 case AC_MDisassemble:
536 assert(IP && "Expected assembly output");
537 IP->setUseMarkup(true);
545 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str, *Buffer,
546 SrcMgr, Ctx, Out->os(), MCOptions);
548 // Keep output if no errors.