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/MCContext.h"
19 #include "llvm/MC/MCInstPrinter.h"
20 #include "llvm/MC/MCInstrInfo.h"
21 #include "llvm/MC/MCObjectFileInfo.h"
22 #include "llvm/MC/MCParser/AsmLexer.h"
23 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
24 #include "llvm/MC/MCRegisterInfo.h"
25 #include "llvm/MC/MCSectionMachO.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/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>
60 CompressDebugSections("compress-debug-sections", cl::ValueOptional,
61 cl::init(DebugCompressionType::DCT_None),
62 cl::desc("Choose DWARF debug sections compression:"),
64 clEnumValN(DebugCompressionType::DCT_None, "none",
66 clEnumValN(DebugCompressionType::DCT_Zlib, "zlib",
67 "Use zlib compression"),
68 clEnumValN(DebugCompressionType::DCT_ZlibGnu, "zlib-gnu",
69 "Use zlib-gnu compression (depricated)"),
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"),
111 static cl::list<std::string>
112 IncludeDirs("I", cl::desc("Directory of include files"),
113 cl::value_desc("directory"), cl::Prefix);
115 static cl::opt<std::string>
116 ArchName("arch", cl::desc("Target arch to assemble for, "
117 "see -version for available targets"));
119 static cl::opt<std::string>
120 TripleName("triple", cl::desc("Target triple to assemble for, "
121 "see -version for available targets"));
123 static cl::opt<std::string>
125 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
126 cl::value_desc("cpu-name"),
129 static cl::list<std::string>
132 cl::desc("Target specific attributes (-mattr=help for details)"),
133 cl::value_desc("a1,+a2,-a3,..."));
135 static cl::opt<bool> PIC("position-independent",
136 cl::desc("Position independent"), cl::init(false));
138 static cl::opt<llvm::CodeModel::Model>
139 CMModel("code-model",
140 cl::desc("Choose code model"),
141 cl::init(CodeModel::Default),
142 cl::values(clEnumValN(CodeModel::Default, "default",
143 "Target default code model"),
144 clEnumValN(CodeModel::Small, "small",
146 clEnumValN(CodeModel::Kernel, "kernel",
147 "Kernel code model"),
148 clEnumValN(CodeModel::Medium, "medium",
149 "Medium code model"),
150 clEnumValN(CodeModel::Large, "large",
155 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
156 "in the text section"));
159 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
162 static cl::opt<std::string>
163 DebugCompilationDir("fdebug-compilation-dir",
164 cl::desc("Specifies the debug info's compilation dir"));
166 static cl::opt<std::string>
167 MainFileName("main-file-name",
168 cl::desc("Specifies the name we should consider the input file"));
170 static cl::opt<bool> SaveTempLabels("save-temp-labels",
171 cl::desc("Don't discard temporary labels"));
173 static cl::opt<bool> NoExecStack("no-exec-stack",
174 cl::desc("File doesn't need an exec stack"));
183 static cl::opt<ActionType>
184 Action(cl::desc("Action to perform:"),
185 cl::init(AC_Assemble),
186 cl::values(clEnumValN(AC_AsLex, "as-lex",
187 "Lex tokens from a .s file"),
188 clEnumValN(AC_Assemble, "assemble",
189 "Assemble a .s file (default)"),
190 clEnumValN(AC_Disassemble, "disassemble",
191 "Disassemble strings of hex bytes"),
192 clEnumValN(AC_MDisassemble, "mdis",
193 "Marked up disassembly of strings of hex bytes"),
196 static const Target *GetTarget(const char *ProgName) {
197 // Figure out the target triple.
198 if (TripleName.empty())
199 TripleName = sys::getDefaultTargetTriple();
200 Triple TheTriple(Triple::normalize(TripleName));
202 // Get the target specific parser.
204 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
207 errs() << ProgName << ": " << Error;
211 // Update the triple name and return the found target.
212 TripleName = TheTriple.getTriple();
216 static std::unique_ptr<tool_output_file> GetOutputStream() {
217 if (OutputFilename == "")
218 OutputFilename = "-";
221 auto Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
224 errs() << EC.message() << '\n';
231 static std::string DwarfDebugFlags;
232 static void setDwarfDebugFlags(int argc, char **argv) {
233 if (!getenv("RC_DEBUG_OPTIONS"))
235 for (int i = 0; i < argc; i++) {
236 DwarfDebugFlags += argv[i];
238 DwarfDebugFlags += " ";
242 static std::string DwarfDebugProducer;
243 static void setDwarfDebugProducer() {
244 if(!getenv("DEBUG_PRODUCER"))
246 DwarfDebugProducer += getenv("DEBUG_PRODUCER");
249 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
253 Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
256 while (Lexer.Lex().isNot(AsmToken::Eof)) {
257 const AsmToken &Tok = Lexer.getTok();
259 switch (Tok.getKind()) {
261 SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
265 case AsmToken::Error:
266 Error = true; // error already printed.
268 case AsmToken::Identifier:
269 OS << "identifier: " << Lexer.getTok().getString();
271 case AsmToken::Integer:
272 OS << "int: " << Lexer.getTok().getString();
275 OS << "real: " << Lexer.getTok().getString();
277 case AsmToken::String:
278 OS << "string: " << Lexer.getTok().getString();
281 case AsmToken::Amp: OS << "Amp"; break;
282 case AsmToken::AmpAmp: OS << "AmpAmp"; break;
283 case AsmToken::At: OS << "At"; break;
284 case AsmToken::Caret: OS << "Caret"; break;
285 case AsmToken::Colon: OS << "Colon"; break;
286 case AsmToken::Comma: OS << "Comma"; break;
287 case AsmToken::Dollar: OS << "Dollar"; break;
288 case AsmToken::Dot: OS << "Dot"; break;
289 case AsmToken::EndOfStatement: OS << "EndOfStatement"; break;
290 case AsmToken::Eof: OS << "Eof"; break;
291 case AsmToken::Equal: OS << "Equal"; break;
292 case AsmToken::EqualEqual: OS << "EqualEqual"; break;
293 case AsmToken::Exclaim: OS << "Exclaim"; break;
294 case AsmToken::ExclaimEqual: OS << "ExclaimEqual"; break;
295 case AsmToken::Greater: OS << "Greater"; break;
296 case AsmToken::GreaterEqual: OS << "GreaterEqual"; break;
297 case AsmToken::GreaterGreater: OS << "GreaterGreater"; break;
298 case AsmToken::Hash: OS << "Hash"; break;
299 case AsmToken::LBrac: OS << "LBrac"; break;
300 case AsmToken::LCurly: OS << "LCurly"; break;
301 case AsmToken::LParen: OS << "LParen"; break;
302 case AsmToken::Less: OS << "Less"; break;
303 case AsmToken::LessEqual: OS << "LessEqual"; break;
304 case AsmToken::LessGreater: OS << "LessGreater"; break;
305 case AsmToken::LessLess: OS << "LessLess"; break;
306 case AsmToken::Minus: OS << "Minus"; break;
307 case AsmToken::Percent: OS << "Percent"; break;
308 case AsmToken::Pipe: OS << "Pipe"; break;
309 case AsmToken::PipePipe: OS << "PipePipe"; break;
310 case AsmToken::Plus: OS << "Plus"; break;
311 case AsmToken::RBrac: OS << "RBrac"; break;
312 case AsmToken::RCurly: OS << "RCurly"; break;
313 case AsmToken::RParen: OS << "RParen"; break;
314 case AsmToken::Slash: OS << "Slash"; break;
315 case AsmToken::Star: OS << "Star"; break;
316 case AsmToken::Tilde: OS << "Tilde"; break;
319 // Print the token string.
321 OS.write_escaped(Tok.getString());
328 static int fillCommandLineSymbols(MCAsmParser &Parser){
329 for(auto &I: DefineSymbol){
330 auto Pair = StringRef(I).split('=');
331 if(Pair.second.empty()){
332 errs() << "error: defsym must be of the form: sym=value: " << I;
336 if(Pair.second.getAsInteger(0, Value)){
337 errs() << "error: Value is not an integer: " << Pair.second;
340 auto &Context = Parser.getContext();
341 auto Symbol = Context.getOrCreateSymbol(Pair.first);
342 Parser.getStreamer().EmitAssignment(Symbol,
343 MCConstantExpr::create(Value, Context));
348 static int AssembleInput(const char *ProgName, const Target *TheTarget,
349 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
350 MCAsmInfo &MAI, MCSubtargetInfo &STI,
351 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
352 std::unique_ptr<MCAsmParser> Parser(
353 createMCAsmParser(SrcMgr, Ctx, Str, MAI));
354 std::unique_ptr<MCTargetAsmParser> TAP(
355 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
359 << ": error: this target does not support assembly parsing.\n";
363 int SymbolResult = fillCommandLineSymbols(*Parser);
366 Parser->setShowParsedOperands(ShowInstOperands);
367 Parser->setTargetParser(*TAP);
369 int Res = Parser->Run(NoInitialTextSection);
374 int main(int argc, char **argv) {
375 // Print a stack trace if we signal out.
376 sys::PrintStackTraceOnErrorSignal(argv[0]);
377 PrettyStackTraceProgram X(argc, argv);
378 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
380 // Initialize targets and assembly printers/parsers.
381 llvm::InitializeAllTargetInfos();
382 llvm::InitializeAllTargetMCs();
383 llvm::InitializeAllAsmParsers();
384 llvm::InitializeAllDisassemblers();
386 // Register the target printer for --version.
387 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
389 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
390 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
391 TripleName = Triple::normalize(TripleName);
392 setDwarfDebugFlags(argc, argv);
394 setDwarfDebugProducer();
396 const char *ProgName = argv[0];
397 const Target *TheTarget = GetTarget(ProgName);
400 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
401 // construct the Triple object.
402 Triple TheTriple(TripleName);
404 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
405 MemoryBuffer::getFileOrSTDIN(InputFilename);
406 if (std::error_code EC = BufferPtr.getError()) {
407 errs() << InputFilename << ": " << EC.message() << '\n';
410 MemoryBuffer *Buffer = BufferPtr->get();
414 // Tell SrcMgr about this buffer, which is what the parser will pick up.
415 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
417 // Record the location of the include directories so that the lexer can find
419 SrcMgr.setIncludeDirs(IncludeDirs);
421 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
422 assert(MRI && "Unable to create target register info!");
424 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
425 assert(MAI && "Unable to create target asm info!");
427 MAI->setRelaxELFRelocations(RelaxELFRel);
429 if (CompressDebugSections != DebugCompressionType::DCT_None) {
430 if (!zlib::isAvailable()) {
432 << ": build tools with zlib to enable -compress-debug-sections";
435 MAI->setCompressDebugSections(CompressDebugSections);
437 MAI->setPreserveAsmComments(PreserveComments);
439 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
440 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
441 MCObjectFileInfo MOFI;
442 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
443 MOFI.InitMCObjectFileInfo(TheTriple, PIC, CMModel, Ctx);
446 Ctx.setAllowTemporaryLabels(false);
448 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
449 // Default to 4 for dwarf version.
450 unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
451 if (DwarfVersion < 2 || DwarfVersion > 4) {
452 errs() << ProgName << ": Dwarf version " << DwarfVersion
453 << " is not supported." << '\n';
456 Ctx.setDwarfVersion(DwarfVersion);
457 if (!DwarfDebugFlags.empty())
458 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
459 if (!DwarfDebugProducer.empty())
460 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
461 if (!DebugCompilationDir.empty())
462 Ctx.setCompilationDir(DebugCompilationDir);
464 // If no compilation dir is set, try to use the current directory.
465 SmallString<128> CWD;
466 if (!sys::fs::current_path(CWD))
467 Ctx.setCompilationDir(CWD);
469 if (!MainFileName.empty())
470 Ctx.setMainFileName(MainFileName);
472 // Package up features to be passed to target/subtarget
473 std::string FeaturesStr;
475 SubtargetFeatures Features;
476 for (unsigned i = 0; i != MAttrs.size(); ++i)
477 Features.AddFeature(MAttrs[i]);
478 FeaturesStr = Features.getString();
481 std::unique_ptr<tool_output_file> Out = GetOutputStream();
485 std::unique_ptr<buffer_ostream> BOS;
486 raw_pwrite_stream *OS = &Out->os();
487 std::unique_ptr<MCStreamer> Str;
489 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
490 std::unique_ptr<MCSubtargetInfo> STI(
491 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
493 MCInstPrinter *IP = nullptr;
494 if (FileType == OFT_AssemblyFile) {
495 IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
498 // Set the display preference for hex vs. decimal immediates.
499 IP->setPrintImmHex(PrintImmHex);
501 // Set up the AsmStreamer.
502 MCCodeEmitter *CE = nullptr;
503 MCAsmBackend *MAB = nullptr;
505 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
506 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU, MCOptions);
508 auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
509 Str.reset(TheTarget->createAsmStreamer(
510 Ctx, std::move(FOut), /*asmverbose*/ true,
511 /*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst));
513 } else if (FileType == OFT_Null) {
514 Str.reset(TheTarget->createNullStreamer(Ctx));
516 assert(FileType == OFT_ObjectFile && "Invalid file type!");
518 // Don't waste memory on names of temp labels.
519 Ctx.setUseNamesOnTempLabels(false);
521 if (!Out->os().supportsSeeking()) {
522 BOS = make_unique<buffer_ostream>(Out->os());
526 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
527 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU,
529 Str.reset(TheTarget->createMCObjectStreamer(
530 TheTriple, Ctx, *MAB, *OS, CE, *STI, MCOptions.MCRelaxAll,
531 MCOptions.MCIncrementalLinkerCompatible,
532 /*DWARFMustBeAtTheEnd*/ false));
534 Str->InitSections(true);
538 bool disassemble = false;
541 Res = AsLexInput(SrcMgr, *MAI, Out->os());
544 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
547 case AC_MDisassemble:
548 assert(IP && "Expected assembly output");
557 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
558 *Buffer, SrcMgr, Out->os());
560 // Keep output if no errors.
561 if (Res == 0) Out->keep();