1 //===-- llvm-mc.cpp - Machine Code Hacking Driver ---------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This utility is a simple driver that allows command line hacking on machine
11 // code.
12 //
13 //===----------------------------------------------------------------------===//
14
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"
42
43 using namespace llvm;
44
45 static cl::opt<std::string>
46 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
47
48 static cl::opt<std::string>
49 OutputFilename("o", cl::desc("Output filename"),
50 cl::value_desc("filename"));
51
52 static cl::opt<bool>
53 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
54
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"));
58
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:"),
63 cl::values(
64 clEnumValN(DebugCompressionType::DCT_None, "none",
65 "No compression"),
66 clEnumValN(DebugCompressionType::DCT_Zlib, "zlib",
67 "Use zlib compression"),
68 clEnumValN(DebugCompressionType::DCT_ZlibGnu, "zlib-gnu",
69 "Use zlib-gnu compression (depricated)"),
70 clEnumValEnd));
71
72 static cl::opt<bool>
73 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
74
75 static cl::opt<bool>
76 ShowInstOperands("show-inst-operands",
77 cl::desc("Show instructions operands as parsed"));
78
79 static cl::opt<unsigned>
80 OutputAsmVariant("output-asm-variant",
81 cl::desc("Syntax variant to use for output printing"));
82
83 static cl::opt<bool>
84 PrintImmHex("print-imm-hex", cl::init(false),
85 cl::desc("Prefer hex format for immediate values"));
86
87 static cl::list<std::string>
88 DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
89
90 static cl::opt<bool>
91 PreserveComments("preserve-comments",
92 cl::desc("Preserve Comments in outputted assembly"));
93
94 enum OutputFileType {
95 OFT_Null,
96 OFT_AssemblyFile,
97 OFT_ObjectFile
98 };
99 static cl::opt<OutputFileType>
100 FileType("filetype", cl::init(OFT_AssemblyFile),
101 cl::desc("Choose an output file type:"),
102 cl::values(
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"),
109 clEnumValEnd));
110
111 static cl::list<std::string>
112 IncludeDirs("I", cl::desc("Directory of include files"),
113 cl::value_desc("directory"), cl::Prefix);
114
115 static cl::opt<std::string>
116 ArchName("arch", cl::desc("Target arch to assemble for, "
117 "see -version for available targets"));
118
119 static cl::opt<std::string>
120 TripleName("triple", cl::desc("Target triple to assemble for, "
121 "see -version for available targets"));
122
123 static cl::opt<std::string>
124 MCPU("mcpu",
125 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
126 cl::value_desc("cpu-name"),
127 cl::init(""));
128
129 static cl::list<std::string>
130 MAttrs("mattr",
131 cl::CommaSeparated,
132 cl::desc("Target specific attributes (-mattr=help for details)"),
133 cl::value_desc("a1,+a2,-a3,..."));
134
135 static cl::opt<bool> PIC("position-independent",
136 cl::desc("Position independent"), cl::init(false));
137
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",
145 "Small code model"),
146 clEnumValN(CodeModel::Kernel, "kernel",
147 "Kernel code model"),
148 clEnumValN(CodeModel::Medium, "medium",
149 "Medium code model"),
150 clEnumValN(CodeModel::Large, "large",
151 "Large code model"),
152 clEnumValEnd));
153
154 static cl::opt<bool>
155 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
156 "in the text section"));
157
158 static cl::opt<bool>
159 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
160 "source files"));
161
162 static cl::opt<std::string>
163 DebugCompilationDir("fdebug-compilation-dir",
164 cl::desc("Specifies the debug info's compilation dir"));
165
166 static cl::opt<std::string>
167 MainFileName("main-file-name",
168 cl::desc("Specifies the name we should consider the input file"));
169
170 static cl::opt<bool> SaveTempLabels("save-temp-labels",
171 cl::desc("Don't discard temporary labels"));
172
173 static cl::opt<bool> NoExecStack("no-exec-stack",
174 cl::desc("File doesn't need an exec stack"));
175
176 enum ActionType {
177 AC_AsLex,
178 AC_Assemble,
179 AC_Disassemble,
180 AC_MDisassemble,
181 };
182
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"),
194 clEnumValEnd));
195
GetTarget(const char * ProgName)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));
201
202 // Get the target specific parser.
203 std::string Error;
204 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
205 Error);
206 if (!TheTarget) {
207 errs() << ProgName << ": " << Error;
208 return nullptr;
209 }
210
211 // Update the triple name and return the found target.
212 TripleName = TheTriple.getTriple();
213 return TheTarget;
214 }
215
GetOutputStream()216 static std::unique_ptr<tool_output_file> GetOutputStream() {
217 if (OutputFilename == "")
218 OutputFilename = "-";
219
220 std::error_code EC;
221 auto Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
222 sys::fs::F_None);
223 if (EC) {
224 errs() << EC.message() << '\n';
225 return nullptr;
226 }
227
228 return Out;
229 }
230
231 static std::string DwarfDebugFlags;
setDwarfDebugFlags(int argc,char ** argv)232 static void setDwarfDebugFlags(int argc, char **argv) {
233 if (!getenv("RC_DEBUG_OPTIONS"))
234 return;
235 for (int i = 0; i < argc; i++) {
236 DwarfDebugFlags += argv[i];
237 if (i + 1 < argc)
238 DwarfDebugFlags += " ";
239 }
240 }
241
242 static std::string DwarfDebugProducer;
setDwarfDebugProducer()243 static void setDwarfDebugProducer() {
244 if(!getenv("DEBUG_PRODUCER"))
245 return;
246 DwarfDebugProducer += getenv("DEBUG_PRODUCER");
247 }
248
AsLexInput(SourceMgr & SrcMgr,MCAsmInfo & MAI,raw_ostream & OS)249 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
250 raw_ostream &OS) {
251
252 AsmLexer Lexer(MAI);
253 Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
254
255 bool Error = false;
256 while (Lexer.Lex().isNot(AsmToken::Eof)) {
257 const AsmToken &Tok = Lexer.getTok();
258
259 switch (Tok.getKind()) {
260 default:
261 SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
262 "unknown token");
263 Error = true;
264 break;
265 case AsmToken::Error:
266 Error = true; // error already printed.
267 break;
268 case AsmToken::Identifier:
269 OS << "identifier: " << Lexer.getTok().getString();
270 break;
271 case AsmToken::Integer:
272 OS << "int: " << Lexer.getTok().getString();
273 break;
274 case AsmToken::Real:
275 OS << "real: " << Lexer.getTok().getString();
276 break;
277 case AsmToken::String:
278 OS << "string: " << Lexer.getTok().getString();
279 break;
280
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;
317 }
318
319 // Print the token string.
320 OS << " (\"";
321 OS.write_escaped(Tok.getString());
322 OS << "\")\n";
323 }
324
325 return Error;
326 }
327
fillCommandLineSymbols(MCAsmParser & Parser)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;
333 return 1;
334 }
335 int64_t Value;
336 if(Pair.second.getAsInteger(0, Value)){
337 errs() << "error: Value is not an integer: " << Pair.second;
338 return 1;
339 }
340 auto &Context = Parser.getContext();
341 auto Symbol = Context.getOrCreateSymbol(Pair.first);
342 Parser.getStreamer().EmitAssignment(Symbol,
343 MCConstantExpr::create(Value, Context));
344 }
345 return 0;
346 }
347
AssembleInput(const char * ProgName,const Target * TheTarget,SourceMgr & SrcMgr,MCContext & Ctx,MCStreamer & Str,MCAsmInfo & MAI,MCSubtargetInfo & STI,MCInstrInfo & MCII,MCTargetOptions & MCOptions)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));
356
357 if (!TAP) {
358 errs() << ProgName
359 << ": error: this target does not support assembly parsing.\n";
360 return 1;
361 }
362
363 int SymbolResult = fillCommandLineSymbols(*Parser);
364 if(SymbolResult)
365 return SymbolResult;
366 Parser->setShowParsedOperands(ShowInstOperands);
367 Parser->setTargetParser(*TAP);
368
369 int Res = Parser->Run(NoInitialTextSection);
370
371 return Res;
372 }
373
main(int argc,char ** argv)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.
379
380 // Initialize targets and assembly printers/parsers.
381 llvm::InitializeAllTargetInfos();
382 llvm::InitializeAllTargetMCs();
383 llvm::InitializeAllAsmParsers();
384 llvm::InitializeAllDisassemblers();
385
386 // Register the target printer for --version.
387 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
388
389 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
390 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
391 TripleName = Triple::normalize(TripleName);
392 setDwarfDebugFlags(argc, argv);
393
394 setDwarfDebugProducer();
395
396 const char *ProgName = argv[0];
397 const Target *TheTarget = GetTarget(ProgName);
398 if (!TheTarget)
399 return 1;
400 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
401 // construct the Triple object.
402 Triple TheTriple(TripleName);
403
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';
408 return 1;
409 }
410 MemoryBuffer *Buffer = BufferPtr->get();
411
412 SourceMgr SrcMgr;
413
414 // Tell SrcMgr about this buffer, which is what the parser will pick up.
415 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
416
417 // Record the location of the include directories so that the lexer can find
418 // it later.
419 SrcMgr.setIncludeDirs(IncludeDirs);
420
421 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
422 assert(MRI && "Unable to create target register info!");
423
424 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
425 assert(MAI && "Unable to create target asm info!");
426
427 MAI->setRelaxELFRelocations(RelaxELFRel);
428
429 if (CompressDebugSections != DebugCompressionType::DCT_None) {
430 if (!zlib::isAvailable()) {
431 errs() << ProgName
432 << ": build tools with zlib to enable -compress-debug-sections";
433 return 1;
434 }
435 MAI->setCompressDebugSections(CompressDebugSections);
436 }
437 MAI->setPreserveAsmComments(PreserveComments);
438
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);
444
445 if (SaveTempLabels)
446 Ctx.setAllowTemporaryLabels(false);
447
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';
454 return 1;
455 }
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);
463 else {
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);
468 }
469 if (!MainFileName.empty())
470 Ctx.setMainFileName(MainFileName);
471
472 // Package up features to be passed to target/subtarget
473 std::string FeaturesStr;
474 if (MAttrs.size()) {
475 SubtargetFeatures Features;
476 for (unsigned i = 0; i != MAttrs.size(); ++i)
477 Features.AddFeature(MAttrs[i]);
478 FeaturesStr = Features.getString();
479 }
480
481 std::unique_ptr<tool_output_file> Out = GetOutputStream();
482 if (!Out)
483 return 1;
484
485 std::unique_ptr<buffer_ostream> BOS;
486 raw_pwrite_stream *OS = &Out->os();
487 std::unique_ptr<MCStreamer> Str;
488
489 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
490 std::unique_ptr<MCSubtargetInfo> STI(
491 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
492
493 MCInstPrinter *IP = nullptr;
494 if (FileType == OFT_AssemblyFile) {
495 IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
496 *MAI, *MCII, *MRI);
497
498 // Set the display preference for hex vs. decimal immediates.
499 IP->setPrintImmHex(PrintImmHex);
500
501 // Set up the AsmStreamer.
502 MCCodeEmitter *CE = nullptr;
503 MCAsmBackend *MAB = nullptr;
504 if (ShowEncoding) {
505 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
506 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
507 }
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));
512
513 } else if (FileType == OFT_Null) {
514 Str.reset(TheTarget->createNullStreamer(Ctx));
515 } else {
516 assert(FileType == OFT_ObjectFile && "Invalid file type!");
517
518 // Don't waste memory on names of temp labels.
519 Ctx.setUseNamesOnTempLabels(false);
520
521 if (!Out->os().supportsSeeking()) {
522 BOS = make_unique<buffer_ostream>(Out->os());
523 OS = BOS.get();
524 }
525
526 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
527 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
528 Str.reset(TheTarget->createMCObjectStreamer(
529 TheTriple, Ctx, *MAB, *OS, CE, *STI, MCOptions.MCRelaxAll,
530 MCOptions.MCIncrementalLinkerCompatible,
531 /*DWARFMustBeAtTheEnd*/ false));
532 if (NoExecStack)
533 Str->InitSections(true);
534 }
535
536 int Res = 1;
537 bool disassemble = false;
538 switch (Action) {
539 case AC_AsLex:
540 Res = AsLexInput(SrcMgr, *MAI, Out->os());
541 break;
542 case AC_Assemble:
543 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
544 *MCII, MCOptions);
545 break;
546 case AC_MDisassemble:
547 assert(IP && "Expected assembly output");
548 IP->setUseMarkup(1);
549 disassemble = true;
550 break;
551 case AC_Disassemble:
552 disassemble = true;
553 break;
554 }
555 if (disassemble)
556 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
557 *Buffer, SrcMgr, Out->os());
558
559 // Keep output if no errors.
560 if (Res == 0) Out->keep();
561 return Res;
562 }
563