1 //===-- llvm-mc.cpp - Machine Code Hacking Driver ---------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This utility is a simple driver that allows command line hacking on machine
13 //===----------------------------------------------------------------------===//
15 #include "Disassembler.h"
16 #include "llvm/MC/MCAsmBackend.h"
17 #include "llvm/MC/MCAsmInfo.h"
18 #include "llvm/MC/MCCodeEmitter.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCInstPrinter.h"
21 #include "llvm/MC/MCInstrInfo.h"
22 #include "llvm/MC/MCObjectFileInfo.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"
43 static cl::opt<std::string>
44 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
46 static cl::opt<std::string>
47 OutputFilename("o", cl::desc("Output filename"),
48 cl::value_desc("filename"));
51 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
53 static cl::opt<bool> RelaxELFRel(
54 "relax-relocations", cl::init(true),
55 cl::desc("Emit R_X86_64_GOTPCRELX instead of R_X86_64_GOTPCREL"));
57 static cl::opt<DebugCompressionType> CompressDebugSections(
58 "compress-debug-sections", cl::ValueOptional,
59 cl::init(DebugCompressionType::None),
60 cl::desc("Choose DWARF debug sections compression:"),
61 cl::values(clEnumValN(DebugCompressionType::None, "none", "No compression"),
62 clEnumValN(DebugCompressionType::Z, "zlib",
63 "Use zlib compression"),
64 clEnumValN(DebugCompressionType::GNU, "zlib-gnu",
65 "Use zlib-gnu compression (deprecated)")));
68 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
71 ShowInstOperands("show-inst-operands",
72 cl::desc("Show instructions operands as parsed"));
74 static cl::opt<unsigned>
75 OutputAsmVariant("output-asm-variant",
76 cl::desc("Syntax variant to use for output printing"));
79 PrintImmHex("print-imm-hex", cl::init(false),
80 cl::desc("Prefer hex format for immediate values"));
82 static cl::list<std::string>
83 DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
86 PreserveComments("preserve-comments",
87 cl::desc("Preserve Comments in outputted assembly"));
94 static cl::opt<OutputFileType>
95 FileType("filetype", cl::init(OFT_AssemblyFile),
96 cl::desc("Choose an output file type:"),
98 clEnumValN(OFT_AssemblyFile, "asm",
99 "Emit an assembly ('.s') file"),
100 clEnumValN(OFT_Null, "null",
101 "Don't emit anything (for timing purposes)"),
102 clEnumValN(OFT_ObjectFile, "obj",
103 "Emit a native object ('.o') file")));
105 static cl::list<std::string>
106 IncludeDirs("I", cl::desc("Directory of include files"),
107 cl::value_desc("directory"), cl::Prefix);
109 static cl::opt<std::string>
110 ArchName("arch", cl::desc("Target arch to assemble for, "
111 "see -version for available targets"));
113 static cl::opt<std::string>
114 TripleName("triple", cl::desc("Target triple to assemble for, "
115 "see -version for available targets"));
117 static cl::opt<std::string>
119 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
120 cl::value_desc("cpu-name"),
123 static cl::list<std::string>
126 cl::desc("Target specific attributes (-mattr=help for details)"),
127 cl::value_desc("a1,+a2,-a3,..."));
129 static cl::opt<bool> PIC("position-independent",
130 cl::desc("Position independent"), cl::init(false));
133 LargeCodeModel("large-code-model",
134 cl::desc("Create cfi directives that assume the code might "
135 "be more than 2gb away"));
138 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
139 "in the text section"));
142 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
145 static cl::opt<std::string>
146 DebugCompilationDir("fdebug-compilation-dir",
147 cl::desc("Specifies the debug info's compilation dir"));
149 static cl::opt<std::string>
150 MainFileName("main-file-name",
151 cl::desc("Specifies the name we should consider the input file"));
153 static cl::opt<bool> SaveTempLabels("save-temp-labels",
154 cl::desc("Don't discard temporary labels"));
156 static cl::opt<bool> NoExecStack("no-exec-stack",
157 cl::desc("File doesn't need an exec stack"));
166 static cl::opt<ActionType>
167 Action(cl::desc("Action to perform:"),
168 cl::init(AC_Assemble),
169 cl::values(clEnumValN(AC_AsLex, "as-lex",
170 "Lex tokens from a .s file"),
171 clEnumValN(AC_Assemble, "assemble",
172 "Assemble a .s file (default)"),
173 clEnumValN(AC_Disassemble, "disassemble",
174 "Disassemble strings of hex bytes"),
175 clEnumValN(AC_MDisassemble, "mdis",
176 "Marked up disassembly of strings of hex bytes")));
178 static const Target *GetTarget(const char *ProgName) {
179 // Figure out the target triple.
180 if (TripleName.empty())
181 TripleName = sys::getDefaultTargetTriple();
182 Triple TheTriple(Triple::normalize(TripleName));
184 // Get the target specific parser.
186 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
189 errs() << ProgName << ": " << Error;
193 // Update the triple name and return the found target.
194 TripleName = TheTriple.getTriple();
198 static std::unique_ptr<ToolOutputFile> GetOutputStream() {
199 if (OutputFilename == "")
200 OutputFilename = "-";
204 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
206 errs() << EC.message() << '\n';
213 static std::string DwarfDebugFlags;
214 static void setDwarfDebugFlags(int argc, char **argv) {
215 if (!getenv("RC_DEBUG_OPTIONS"))
217 for (int i = 0; i < argc; i++) {
218 DwarfDebugFlags += argv[i];
220 DwarfDebugFlags += " ";
224 static std::string DwarfDebugProducer;
225 static void setDwarfDebugProducer() {
226 if(!getenv("DEBUG_PRODUCER"))
228 DwarfDebugProducer += getenv("DEBUG_PRODUCER");
231 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
235 Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
238 while (Lexer.Lex().isNot(AsmToken::Eof)) {
239 Lexer.getTok().dump(OS);
241 if (Lexer.getTok().getKind() == AsmToken::Error)
248 static int fillCommandLineSymbols(MCAsmParser &Parser) {
249 for (auto &I: DefineSymbol) {
250 auto Pair = StringRef(I).split('=');
251 auto Sym = Pair.first;
252 auto Val = Pair.second;
254 if (Sym.empty() || Val.empty()) {
255 errs() << "error: defsym must be of the form: sym=value: " << I << "\n";
259 if (Val.getAsInteger(0, Value)) {
260 errs() << "error: Value is not an integer: " << Val << "\n";
263 Parser.getContext().setSymbolValue(Parser.getStreamer(), Sym, Value);
268 static int AssembleInput(const char *ProgName, const Target *TheTarget,
269 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
270 MCAsmInfo &MAI, MCSubtargetInfo &STI,
271 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
272 std::unique_ptr<MCAsmParser> Parser(
273 createMCAsmParser(SrcMgr, Ctx, Str, MAI));
274 std::unique_ptr<MCTargetAsmParser> TAP(
275 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
279 << ": error: this target does not support assembly parsing.\n";
283 int SymbolResult = fillCommandLineSymbols(*Parser);
286 Parser->setShowParsedOperands(ShowInstOperands);
287 Parser->setTargetParser(*TAP);
289 int Res = Parser->Run(NoInitialTextSection);
294 int main(int argc, char **argv) {
295 InitLLVM X(argc, argv);
297 // Initialize targets and assembly printers/parsers.
298 llvm::InitializeAllTargetInfos();
299 llvm::InitializeAllTargetMCs();
300 llvm::InitializeAllAsmParsers();
301 llvm::InitializeAllDisassemblers();
303 // Register the target printer for --version.
304 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
306 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
307 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
308 TripleName = Triple::normalize(TripleName);
309 setDwarfDebugFlags(argc, argv);
311 setDwarfDebugProducer();
313 const char *ProgName = argv[0];
314 const Target *TheTarget = GetTarget(ProgName);
317 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
318 // construct the Triple object.
319 Triple TheTriple(TripleName);
321 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
322 MemoryBuffer::getFileOrSTDIN(InputFilename);
323 if (std::error_code EC = BufferPtr.getError()) {
324 errs() << InputFilename << ": " << EC.message() << '\n';
327 MemoryBuffer *Buffer = BufferPtr->get();
331 // Tell SrcMgr about this buffer, which is what the parser will pick up.
332 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
334 // Record the location of the include directories so that the lexer can find
336 SrcMgr.setIncludeDirs(IncludeDirs);
338 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
339 assert(MRI && "Unable to create target register info!");
341 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
342 assert(MAI && "Unable to create target asm info!");
344 MAI->setRelaxELFRelocations(RelaxELFRel);
346 if (CompressDebugSections != DebugCompressionType::None) {
347 if (!zlib::isAvailable()) {
349 << ": build tools with zlib to enable -compress-debug-sections";
352 MAI->setCompressDebugSections(CompressDebugSections);
354 MAI->setPreserveAsmComments(PreserveComments);
356 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
357 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
358 MCObjectFileInfo MOFI;
359 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
360 MOFI.InitMCObjectFileInfo(TheTriple, PIC, Ctx, LargeCodeModel);
363 Ctx.setAllowTemporaryLabels(false);
365 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
366 // Default to 4 for dwarf version.
367 unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
368 if (DwarfVersion < 2 || DwarfVersion > 5) {
369 errs() << ProgName << ": Dwarf version " << DwarfVersion
370 << " is not supported." << '\n';
373 Ctx.setDwarfVersion(DwarfVersion);
374 if (!DwarfDebugFlags.empty())
375 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
376 if (!DwarfDebugProducer.empty())
377 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
378 if (!DebugCompilationDir.empty())
379 Ctx.setCompilationDir(DebugCompilationDir);
381 // If no compilation dir is set, try to use the current directory.
382 SmallString<128> CWD;
383 if (!sys::fs::current_path(CWD))
384 Ctx.setCompilationDir(CWD);
386 if (!MainFileName.empty())
387 Ctx.setMainFileName(MainFileName);
388 if (DwarfVersion >= 5) {
389 // DWARF v5 needs the root file as well as the compilation directory.
390 // If we find a '.file 0' directive that will supersede these values.
392 MD5::MD5Result *Cksum =
393 (MD5::MD5Result *)Ctx.allocate(sizeof(MD5::MD5Result), 1);
394 Hash.update(Buffer->getBuffer());
396 Ctx.setMCLineTableRootFile(
397 /*CUID=*/0, Ctx.getCompilationDir(),
398 !MainFileName.empty() ? MainFileName : InputFilename, Cksum, None);
401 // Package up features to be passed to target/subtarget
402 std::string FeaturesStr;
404 SubtargetFeatures Features;
405 for (unsigned i = 0; i != MAttrs.size(); ++i)
406 Features.AddFeature(MAttrs[i]);
407 FeaturesStr = Features.getString();
410 std::unique_ptr<ToolOutputFile> Out = GetOutputStream();
414 std::unique_ptr<buffer_ostream> BOS;
415 raw_pwrite_stream *OS = &Out->os();
416 std::unique_ptr<MCStreamer> Str;
418 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
419 std::unique_ptr<MCSubtargetInfo> STI(
420 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
422 MCInstPrinter *IP = nullptr;
423 if (FileType == OFT_AssemblyFile) {
424 IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
429 << "error: unable to create instruction printer for target triple '"
430 << TheTriple.normalize() << "' with assembly variant "
431 << OutputAsmVariant << ".\n";
435 // Set the display preference for hex vs. decimal immediates.
436 IP->setPrintImmHex(PrintImmHex);
438 // Set up the AsmStreamer.
439 MCCodeEmitter *CE = nullptr;
440 MCAsmBackend *MAB = nullptr;
442 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
443 MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions);
445 auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
446 Str.reset(TheTarget->createAsmStreamer(
447 Ctx, std::move(FOut), /*asmverbose*/ true,
448 /*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst));
450 } else if (FileType == OFT_Null) {
451 Str.reset(TheTarget->createNullStreamer(Ctx));
453 assert(FileType == OFT_ObjectFile && "Invalid file type!");
455 // Don't waste memory on names of temp labels.
456 Ctx.setUseNamesOnTempLabels(false);
458 if (!Out->os().supportsSeeking()) {
459 BOS = make_unique<buffer_ostream>(Out->os());
463 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
464 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions);
465 Str.reset(TheTarget->createMCObjectStreamer(
466 TheTriple, Ctx, std::unique_ptr<MCAsmBackend>(MAB), *OS,
467 std::unique_ptr<MCCodeEmitter>(CE), *STI, MCOptions.MCRelaxAll,
468 MCOptions.MCIncrementalLinkerCompatible,
469 /*DWARFMustBeAtTheEnd*/ false));
471 Str->InitSections(true);
475 bool disassemble = false;
478 Res = AsLexInput(SrcMgr, *MAI, Out->os());
481 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
484 case AC_MDisassemble:
485 assert(IP && "Expected assembly output");
494 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
495 *Buffer, SrcMgr, Out->os());
497 // Keep output if no errors.
498 if (Res == 0) Out->keep();