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.def"
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/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/Signals.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/TargetSelect.h"
41 #include "llvm/Support/ToolOutputFile.h"
45 static cl::opt<std::string>
46 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
48 static cl::opt<std::string>
49 OutputFilename("o", cl::desc("Output filename"),
50 cl::value_desc("filename"));
53 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
55 static cl::opt<bool> RelaxELFRel(
56 "relax-relocations", cl::init(true),
57 cl::desc("Emit R_X86_64_GOTPCRELX instead of R_X86_64_GOTPCREL"));
59 static cl::opt<DebugCompressionType> CompressDebugSections(
60 "compress-debug-sections", cl::ValueOptional,
61 cl::init(DebugCompressionType::None),
62 cl::desc("Choose DWARF debug sections compression:"),
63 cl::values(clEnumValN(DebugCompressionType::None, "none", "No compression"),
64 clEnumValN(DebugCompressionType::Z, "zlib",
65 "Use zlib compression"),
66 clEnumValN(DebugCompressionType::GNU, "zlib-gnu",
67 "Use zlib-gnu compression (deprecated)")));
70 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
73 ShowInstOperands("show-inst-operands",
74 cl::desc("Show instructions operands as parsed"));
76 static cl::opt<unsigned>
77 OutputAsmVariant("output-asm-variant",
78 cl::desc("Syntax variant to use for output printing"));
81 PrintImmHex("print-imm-hex", cl::init(false),
82 cl::desc("Prefer hex format for immediate values"));
84 static cl::list<std::string>
85 DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
88 PreserveComments("preserve-comments",
89 cl::desc("Preserve Comments in outputted assembly"));
96 static cl::opt<OutputFileType>
97 FileType("filetype", cl::init(OFT_AssemblyFile),
98 cl::desc("Choose an output file type:"),
100 clEnumValN(OFT_AssemblyFile, "asm",
101 "Emit an assembly ('.s') file"),
102 clEnumValN(OFT_Null, "null",
103 "Don't emit anything (for timing purposes)"),
104 clEnumValN(OFT_ObjectFile, "obj",
105 "Emit a native object ('.o') file")));
107 static cl::list<std::string>
108 IncludeDirs("I", cl::desc("Directory of include files"),
109 cl::value_desc("directory"), cl::Prefix);
111 static cl::opt<std::string>
112 ArchName("arch", cl::desc("Target arch to assemble for, "
113 "see -version for available targets"));
115 static cl::opt<std::string>
116 TripleName("triple", cl::desc("Target triple to assemble for, "
117 "see -version for available targets"));
119 static cl::opt<std::string>
121 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
122 cl::value_desc("cpu-name"),
125 static cl::list<std::string>
128 cl::desc("Target specific attributes (-mattr=help for details)"),
129 cl::value_desc("a1,+a2,-a3,..."));
131 static cl::opt<bool> PIC("position-independent",
132 cl::desc("Position independent"), cl::init(false));
135 LargeCodeModel("large-code-model",
136 cl::desc("Create cfi directives that assume the code might "
137 "be more than 2gb away"));
140 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
141 "in the text section"));
144 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
147 static cl::opt<std::string>
148 DebugCompilationDir("fdebug-compilation-dir",
149 cl::desc("Specifies the debug info's compilation dir"));
151 static cl::opt<std::string>
152 MainFileName("main-file-name",
153 cl::desc("Specifies the name we should consider the input file"));
155 static cl::opt<bool> SaveTempLabels("save-temp-labels",
156 cl::desc("Don't discard temporary labels"));
158 static cl::opt<bool> NoExecStack("no-exec-stack",
159 cl::desc("File doesn't need an exec stack"));
168 static cl::opt<ActionType>
169 Action(cl::desc("Action to perform:"),
170 cl::init(AC_Assemble),
171 cl::values(clEnumValN(AC_AsLex, "as-lex",
172 "Lex tokens from a .s file"),
173 clEnumValN(AC_Assemble, "assemble",
174 "Assemble a .s file (default)"),
175 clEnumValN(AC_Disassemble, "disassemble",
176 "Disassemble strings of hex bytes"),
177 clEnumValN(AC_MDisassemble, "mdis",
178 "Marked up disassembly of strings of hex bytes")));
180 static const Target *GetTarget(const char *ProgName) {
181 // Figure out the target triple.
182 if (TripleName.empty())
183 TripleName = sys::getDefaultTargetTriple();
184 Triple TheTriple(Triple::normalize(TripleName));
186 // Get the target specific parser.
188 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
191 errs() << ProgName << ": " << Error;
195 // Update the triple name and return the found target.
196 TripleName = TheTriple.getTriple();
200 static std::unique_ptr<ToolOutputFile> GetOutputStream() {
201 if (OutputFilename == "")
202 OutputFilename = "-";
206 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
208 errs() << EC.message() << '\n';
215 static std::string DwarfDebugFlags;
216 static void setDwarfDebugFlags(int argc, char **argv) {
217 if (!getenv("RC_DEBUG_OPTIONS"))
219 for (int i = 0; i < argc; i++) {
220 DwarfDebugFlags += argv[i];
222 DwarfDebugFlags += " ";
226 static std::string DwarfDebugProducer;
227 static void setDwarfDebugProducer() {
228 if(!getenv("DEBUG_PRODUCER"))
230 DwarfDebugProducer += getenv("DEBUG_PRODUCER");
233 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
237 Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
240 while (Lexer.Lex().isNot(AsmToken::Eof)) {
241 Lexer.getTok().dump(OS);
243 if (Lexer.getTok().getKind() == AsmToken::Error)
250 static int fillCommandLineSymbols(MCAsmParser &Parser) {
251 for (auto &I: DefineSymbol) {
252 auto Pair = StringRef(I).split('=');
253 auto Sym = Pair.first;
254 auto Val = Pair.second;
256 if (Sym.empty() || Val.empty()) {
257 errs() << "error: defsym must be of the form: sym=value: " << I << "\n";
261 if (Val.getAsInteger(0, Value)) {
262 errs() << "error: Value is not an integer: " << Val << "\n";
265 Parser.getContext().setSymbolValue(Parser.getStreamer(), Sym, Value);
270 static int AssembleInput(const char *ProgName, const Target *TheTarget,
271 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
272 MCAsmInfo &MAI, MCSubtargetInfo &STI,
273 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
274 std::unique_ptr<MCAsmParser> Parser(
275 createMCAsmParser(SrcMgr, Ctx, Str, MAI));
276 std::unique_ptr<MCTargetAsmParser> TAP(
277 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
281 << ": error: this target does not support assembly parsing.\n";
285 int SymbolResult = fillCommandLineSymbols(*Parser);
288 Parser->setShowParsedOperands(ShowInstOperands);
289 Parser->setTargetParser(*TAP);
291 int Res = Parser->Run(NoInitialTextSection);
296 int main(int argc, char **argv) {
297 // Print a stack trace if we signal out.
298 sys::PrintStackTraceOnErrorSignal(argv[0]);
299 PrettyStackTraceProgram X(argc, argv);
300 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
302 // Initialize targets and assembly printers/parsers.
303 llvm::InitializeAllTargetInfos();
304 llvm::InitializeAllTargetMCs();
305 llvm::InitializeAllAsmParsers();
306 llvm::InitializeAllDisassemblers();
308 // Register the target printer for --version.
309 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
311 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
312 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
313 TripleName = Triple::normalize(TripleName);
314 setDwarfDebugFlags(argc, argv);
316 setDwarfDebugProducer();
318 const char *ProgName = argv[0];
319 const Target *TheTarget = GetTarget(ProgName);
322 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
323 // construct the Triple object.
324 Triple TheTriple(TripleName);
326 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
327 MemoryBuffer::getFileOrSTDIN(InputFilename);
328 if (std::error_code EC = BufferPtr.getError()) {
329 errs() << InputFilename << ": " << EC.message() << '\n';
332 MemoryBuffer *Buffer = BufferPtr->get();
336 // Tell SrcMgr about this buffer, which is what the parser will pick up.
337 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
339 // Record the location of the include directories so that the lexer can find
341 SrcMgr.setIncludeDirs(IncludeDirs);
343 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
344 assert(MRI && "Unable to create target register info!");
346 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
347 assert(MAI && "Unable to create target asm info!");
349 MAI->setRelaxELFRelocations(RelaxELFRel);
351 if (CompressDebugSections != DebugCompressionType::None) {
352 if (!zlib::isAvailable()) {
354 << ": build tools with zlib to enable -compress-debug-sections";
357 MAI->setCompressDebugSections(CompressDebugSections);
359 MAI->setPreserveAsmComments(PreserveComments);
361 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
362 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
363 MCObjectFileInfo MOFI;
364 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
365 MOFI.InitMCObjectFileInfo(TheTriple, PIC, Ctx, LargeCodeModel);
368 Ctx.setAllowTemporaryLabels(false);
370 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
371 // Default to 4 for dwarf version.
372 unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
373 if (DwarfVersion < 2 || DwarfVersion > 5) {
374 errs() << ProgName << ": Dwarf version " << DwarfVersion
375 << " is not supported." << '\n';
378 Ctx.setDwarfVersion(DwarfVersion);
379 if (!DwarfDebugFlags.empty())
380 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
381 if (!DwarfDebugProducer.empty())
382 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
383 if (!DebugCompilationDir.empty())
384 Ctx.setCompilationDir(DebugCompilationDir);
386 // If no compilation dir is set, try to use the current directory.
387 SmallString<128> CWD;
388 if (!sys::fs::current_path(CWD))
389 Ctx.setCompilationDir(CWD);
391 if (!MainFileName.empty())
392 Ctx.setMainFileName(MainFileName);
393 if (DwarfVersion >= 5) {
394 // DWARF v5 needs the root file as well as the compilation directory.
395 // If we find a '.file 0' directive that will supersede these values.
397 MD5::MD5Result *Cksum =
398 (MD5::MD5Result *)Ctx.allocate(sizeof(MD5::MD5Result), 1);
399 Hash.update(Buffer->getBuffer());
401 Ctx.setMCLineTableRootFile(
402 /*CUID=*/0, Ctx.getCompilationDir(),
403 !MainFileName.empty() ? MainFileName : InputFilename, Cksum, None);
406 // Package up features to be passed to target/subtarget
407 std::string FeaturesStr;
409 SubtargetFeatures Features;
410 for (unsigned i = 0; i != MAttrs.size(); ++i)
411 Features.AddFeature(MAttrs[i]);
412 FeaturesStr = Features.getString();
415 std::unique_ptr<ToolOutputFile> Out = GetOutputStream();
419 std::unique_ptr<buffer_ostream> BOS;
420 raw_pwrite_stream *OS = &Out->os();
421 std::unique_ptr<MCStreamer> Str;
423 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
424 std::unique_ptr<MCSubtargetInfo> STI(
425 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
427 MCInstPrinter *IP = nullptr;
428 if (FileType == OFT_AssemblyFile) {
429 IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
434 << "error: unable to create instruction printer for target triple '"
435 << TheTriple.normalize() << "' with assembly variant "
436 << OutputAsmVariant << ".\n";
440 // Set the display preference for hex vs. decimal immediates.
441 IP->setPrintImmHex(PrintImmHex);
443 // Set up the AsmStreamer.
444 MCCodeEmitter *CE = nullptr;
445 MCAsmBackend *MAB = nullptr;
447 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
448 MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions);
450 auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
451 Str.reset(TheTarget->createAsmStreamer(
452 Ctx, std::move(FOut), /*asmverbose*/ true,
453 /*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst));
455 } else if (FileType == OFT_Null) {
456 Str.reset(TheTarget->createNullStreamer(Ctx));
458 assert(FileType == OFT_ObjectFile && "Invalid file type!");
460 // Don't waste memory on names of temp labels.
461 Ctx.setUseNamesOnTempLabels(false);
463 if (!Out->os().supportsSeeking()) {
464 BOS = make_unique<buffer_ostream>(Out->os());
468 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
469 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions);
470 Str.reset(TheTarget->createMCObjectStreamer(
471 TheTriple, Ctx, std::unique_ptr<MCAsmBackend>(MAB), *OS,
472 std::unique_ptr<MCCodeEmitter>(CE), *STI, MCOptions.MCRelaxAll,
473 MCOptions.MCIncrementalLinkerCompatible,
474 /*DWARFMustBeAtTheEnd*/ false));
476 Str->InitSections(true);
480 bool disassemble = false;
483 Res = AsLexInput(SrcMgr, *MAI, Out->os());
486 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
489 case AC_MDisassemble:
490 assert(IP && "Expected assembly output");
499 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
500 *Buffer, SrcMgr, Out->os());
502 // Keep output if no errors.
503 if (Res == 0) Out->keep();