xref: /llvm-project/llvm/tools/llvm-mc/llvm-mc.cpp (revision 345b98eddda9153a30c6c90b1532b71a60a06b89)
1 //===-- llvm-mc.cpp - Machine Code Hacking Driver -------------------------===//
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 "llvm/MC/MCParser/AsmLexer.h"
16 #include "llvm/MC/MCParser/MCAsmLexer.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCCodeEmitter.h"
19 #include "llvm/MC/MCInstPrinter.h"
20 #include "llvm/MC/MCSectionMachO.h"
21 #include "llvm/MC/MCStreamer.h"
22 #include "llvm/Target/TargetAsmBackend.h"
23 #include "llvm/Target/TargetAsmParser.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetRegistry.h"
26 #include "llvm/Target/SubtargetFeature.h" // FIXME.
27 #include "llvm/Target/TargetMachine.h"  // FIXME.
28 #include "llvm/Target/TargetSelect.h"
29 #include "llvm/ADT/OwningPtr.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/FileUtilities.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/PrettyStackTrace.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/ToolOutputFile.h"
38 #include "llvm/System/Host.h"
39 #include "llvm/System/Signals.h"
40 #include "Disassembler.h"
41 using namespace llvm;
42 
43 static cl::opt<std::string>
44 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
45 
46 static cl::opt<std::string>
47 OutputFilename("o", cl::desc("Output filename"),
48                cl::value_desc("filename"));
49 
50 static cl::opt<bool>
51 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
52 
53 static cl::opt<bool>
54 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
55 
56 static cl::opt<bool>
57 ShowInstOperands("show-inst-operands",
58                  cl::desc("Show instructions operands as parsed"));
59 
60 static cl::opt<unsigned>
61 OutputAsmVariant("output-asm-variant",
62                  cl::desc("Syntax variant to use for output printing"));
63 
64 static cl::opt<bool>
65 RelaxAll("mc-relax-all", cl::desc("Relax all fixups"));
66 
67 static cl::opt<bool>
68 EnableLogging("enable-api-logging", cl::desc("Enable MC API logging"));
69 
70 enum OutputFileType {
71   OFT_Null,
72   OFT_AssemblyFile,
73   OFT_ObjectFile
74 };
75 static cl::opt<OutputFileType>
76 FileType("filetype", cl::init(OFT_AssemblyFile),
77   cl::desc("Choose an output file type:"),
78   cl::values(
79        clEnumValN(OFT_AssemblyFile, "asm",
80                   "Emit an assembly ('.s') file"),
81        clEnumValN(OFT_Null, "null",
82                   "Don't emit anything (for timing purposes)"),
83        clEnumValN(OFT_ObjectFile, "obj",
84                   "Emit a native object ('.o') file"),
85        clEnumValEnd));
86 
87 static cl::list<std::string>
88 IncludeDirs("I", cl::desc("Directory of include files"),
89             cl::value_desc("directory"), cl::Prefix);
90 
91 static cl::opt<std::string>
92 ArchName("arch", cl::desc("Target arch to assemble for, "
93                             "see -version for available targets"));
94 
95 static cl::opt<std::string>
96 TripleName("triple", cl::desc("Target triple to assemble for, "
97                               "see -version for available targets"));
98 
99 static cl::opt<std::string>
100 MCPU("mcpu",
101      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
102      cl::value_desc("cpu-name"),
103      cl::init(""));
104 
105 static cl::opt<bool>
106 NoInitialTextSection("n", cl::desc(
107                    "Don't assume assembly file starts in the text section"));
108 
109 enum ActionType {
110   AC_AsLex,
111   AC_Assemble,
112   AC_Disassemble,
113   AC_EDisassemble
114 };
115 
116 static cl::opt<ActionType>
117 Action(cl::desc("Action to perform:"),
118        cl::init(AC_Assemble),
119        cl::values(clEnumValN(AC_AsLex, "as-lex",
120                              "Lex tokens from a .s file"),
121                   clEnumValN(AC_Assemble, "assemble",
122                              "Assemble a .s file (default)"),
123                   clEnumValN(AC_Disassemble, "disassemble",
124                              "Disassemble strings of hex bytes"),
125                   clEnumValN(AC_EDisassemble, "edis",
126                              "Enhanced disassembly of strings of hex bytes"),
127                   clEnumValEnd));
128 
129 static const Target *GetTarget(const char *ProgName) {
130   // Figure out the target triple.
131   if (TripleName.empty())
132     TripleName = sys::getHostTriple();
133   if (!ArchName.empty()) {
134     llvm::Triple TT(TripleName);
135     TT.setArchName(ArchName);
136     TripleName = TT.str();
137   }
138 
139   // Get the target specific parser.
140   std::string Error;
141   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
142   if (TheTarget)
143     return TheTarget;
144 
145   errs() << ProgName << ": error: unable to get target for '" << TripleName
146          << "', see --version and --triple.\n";
147   return 0;
148 }
149 
150 static tool_output_file *GetOutputStream() {
151   if (OutputFilename == "")
152     OutputFilename = "-";
153 
154   std::string Err;
155   tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
156                                                raw_fd_ostream::F_Binary);
157   if (!Err.empty()) {
158     errs() << Err << '\n';
159     delete Out;
160     return 0;
161   }
162 
163   return Out;
164 }
165 
166 static int AsLexInput(const char *ProgName) {
167   std::string ErrorMessage;
168   MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
169                                                       &ErrorMessage);
170   if (Buffer == 0) {
171     errs() << ProgName << ": ";
172     if (ErrorMessage.size())
173       errs() << ErrorMessage << "\n";
174     else
175       errs() << "input file didn't read correctly.\n";
176     return 1;
177   }
178 
179   SourceMgr SrcMgr;
180 
181   // Tell SrcMgr about this buffer, which is what TGParser will pick up.
182   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
183 
184   // Record the location of the include directories so that the lexer can find
185   // it later.
186   SrcMgr.setIncludeDirs(IncludeDirs);
187 
188   const Target *TheTarget = GetTarget(ProgName);
189   if (!TheTarget)
190     return 1;
191 
192   llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(TripleName));
193   assert(MAI && "Unable to create target asm info!");
194 
195   AsmLexer Lexer(*MAI);
196   Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
197 
198   OwningPtr<tool_output_file> Out(GetOutputStream());
199   if (!Out)
200     return 1;
201 
202   bool Error = false;
203   while (Lexer.Lex().isNot(AsmToken::Eof)) {
204     AsmToken Tok = Lexer.getTok();
205 
206     switch (Tok.getKind()) {
207     default:
208       SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
209       Error = true;
210       break;
211     case AsmToken::Error:
212       Error = true; // error already printed.
213       break;
214     case AsmToken::Identifier:
215       Out->os() << "identifier: " << Lexer.getTok().getString();
216       break;
217     case AsmToken::Integer:
218       Out->os() << "int: " << Lexer.getTok().getString();
219       break;
220     case AsmToken::Real:
221       Out->os() << "real: " << Lexer.getTok().getString();
222       break;
223     case AsmToken::Register:
224       Out->os() << "register: " << Lexer.getTok().getRegVal();
225       break;
226     case AsmToken::String:
227       Out->os() << "string: " << Lexer.getTok().getString();
228       break;
229 
230     case AsmToken::Amp:            Out->os() << "Amp"; break;
231     case AsmToken::AmpAmp:         Out->os() << "AmpAmp"; break;
232     case AsmToken::At:             Out->os() << "At"; break;
233     case AsmToken::Caret:          Out->os() << "Caret"; break;
234     case AsmToken::Colon:          Out->os() << "Colon"; break;
235     case AsmToken::Comma:          Out->os() << "Comma"; break;
236     case AsmToken::Dollar:         Out->os() << "Dollar"; break;
237     case AsmToken::Dot:            Out->os() << "Dot"; break;
238     case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
239     case AsmToken::Eof:            Out->os() << "Eof"; break;
240     case AsmToken::Equal:          Out->os() << "Equal"; break;
241     case AsmToken::EqualEqual:     Out->os() << "EqualEqual"; break;
242     case AsmToken::Exclaim:        Out->os() << "Exclaim"; break;
243     case AsmToken::ExclaimEqual:   Out->os() << "ExclaimEqual"; break;
244     case AsmToken::Greater:        Out->os() << "Greater"; break;
245     case AsmToken::GreaterEqual:   Out->os() << "GreaterEqual"; break;
246     case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
247     case AsmToken::Hash:           Out->os() << "Hash"; break;
248     case AsmToken::LBrac:          Out->os() << "LBrac"; break;
249     case AsmToken::LCurly:         Out->os() << "LCurly"; break;
250     case AsmToken::LParen:         Out->os() << "LParen"; break;
251     case AsmToken::Less:           Out->os() << "Less"; break;
252     case AsmToken::LessEqual:      Out->os() << "LessEqual"; break;
253     case AsmToken::LessGreater:    Out->os() << "LessGreater"; break;
254     case AsmToken::LessLess:       Out->os() << "LessLess"; break;
255     case AsmToken::Minus:          Out->os() << "Minus"; break;
256     case AsmToken::Percent:        Out->os() << "Percent"; break;
257     case AsmToken::Pipe:           Out->os() << "Pipe"; break;
258     case AsmToken::PipePipe:       Out->os() << "PipePipe"; break;
259     case AsmToken::Plus:           Out->os() << "Plus"; break;
260     case AsmToken::RBrac:          Out->os() << "RBrac"; break;
261     case AsmToken::RCurly:         Out->os() << "RCurly"; break;
262     case AsmToken::RParen:         Out->os() << "RParen"; break;
263     case AsmToken::Slash:          Out->os() << "Slash"; break;
264     case AsmToken::Star:           Out->os() << "Star"; break;
265     case AsmToken::Tilde:          Out->os() << "Tilde"; break;
266     }
267 
268     // Print the token string.
269     Out->os() << " (\"";
270     Out->os().write_escaped(Tok.getString());
271     Out->os() << "\")\n";
272   }
273 
274   // Keep output if no errors.
275   if (Error == 0) Out->keep();
276 
277   return Error;
278 }
279 
280 static int AssembleInput(const char *ProgName) {
281   const Target *TheTarget = GetTarget(ProgName);
282   if (!TheTarget)
283     return 1;
284 
285   std::string Error;
286   MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, &Error);
287   if (Buffer == 0) {
288     errs() << ProgName << ": ";
289     if (Error.size())
290       errs() << Error << "\n";
291     else
292       errs() << "input file didn't read correctly.\n";
293     return 1;
294   }
295 
296   SourceMgr SrcMgr;
297 
298   // Tell SrcMgr about this buffer, which is what the parser will pick up.
299   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
300 
301   // Record the location of the include directories so that the lexer can find
302   // it later.
303   SrcMgr.setIncludeDirs(IncludeDirs);
304 
305 
306   llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(TripleName));
307   assert(MAI && "Unable to create target asm info!");
308 
309   MCContext Ctx(*MAI);
310 
311   // Package up features to be passed to target/subtarget
312   std::string FeaturesStr;
313   if (MCPU.size()) {
314     SubtargetFeatures Features;
315     Features.setCPU(MCPU);
316     FeaturesStr = Features.getString();
317   }
318 
319   // FIXME: We shouldn't need to do this (and link in codegen).
320   //        When we split this out, we should do it in a way that makes
321   //        it straightforward to switch subtargets on the fly (.e.g,
322   //        the .cpu and .code16 directives).
323   OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName,
324                                                              FeaturesStr));
325 
326   if (!TM) {
327     errs() << ProgName << ": error: could not create target for triple '"
328            << TripleName << "'.\n";
329     return 1;
330   }
331 
332   OwningPtr<tool_output_file> Out(GetOutputStream());
333   if (!Out)
334     return 1;
335 
336   formatted_raw_ostream FOS(Out->os());
337   OwningPtr<MCStreamer> Str;
338 
339   if (FileType == OFT_AssemblyFile) {
340     MCInstPrinter *IP =
341       TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI);
342     MCCodeEmitter *CE = 0;
343     if (ShowEncoding)
344       CE = TheTarget->createCodeEmitter(*TM, Ctx);
345     Str.reset(TheTarget->createAsmStreamer(Ctx, FOS,
346                                            TM->getTargetData()->isLittleEndian(),
347                                            /*asmverbose*/true, IP, CE, ShowInst));
348   } else if (FileType == OFT_Null) {
349     Str.reset(createNullStreamer(Ctx));
350   } else {
351     assert(FileType == OFT_ObjectFile && "Invalid file type!");
352     MCCodeEmitter *CE = TheTarget->createCodeEmitter(*TM, Ctx);
353     TargetAsmBackend *TAB = TheTarget->createAsmBackend(TripleName);
354     Str.reset(TheTarget->createObjectStreamer(TripleName, Ctx, *TAB,
355                                               FOS, CE, RelaxAll));
356   }
357 
358   if (EnableLogging) {
359     Str.reset(createLoggingStreamer(Str.take(), errs()));
360   }
361 
362   OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
363                                                    *Str.get(), *MAI));
364   OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*Parser, *TM));
365   if (!TAP) {
366     errs() << ProgName
367            << ": error: this target does not support assembly parsing.\n";
368     return 1;
369   }
370 
371   Parser->setShowParsedOperands(ShowInstOperands);
372   Parser->setTargetParser(*TAP.get());
373 
374   int Res = Parser->Run(NoInitialTextSection);
375 
376   // Keep output if no errors.
377   if (Res == 0) Out->keep();
378 
379   return Res;
380 }
381 
382 static int DisassembleInput(const char *ProgName, bool Enhanced) {
383   const Target *TheTarget = GetTarget(ProgName);
384   if (!TheTarget)
385     return 0;
386 
387   std::string ErrorMessage;
388 
389   MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
390                                                       &ErrorMessage);
391 
392   if (Buffer == 0) {
393     errs() << ProgName << ": ";
394     if (ErrorMessage.size())
395       errs() << ErrorMessage << "\n";
396     else
397       errs() << "input file didn't read correctly.\n";
398     return 1;
399   }
400 
401   OwningPtr<tool_output_file> Out(GetOutputStream());
402   if (!Out)
403     return 1;
404 
405   int Res;
406   if (Enhanced)
407     Res = Disassembler::disassembleEnhanced(TripleName, *Buffer, Out->os());
408   else
409     Res = Disassembler::disassemble(*TheTarget, TripleName, *Buffer, Out->os());
410 
411   // Keep output if no errors.
412   if (Res == 0) Out->keep();
413 
414   return Res;
415 }
416 
417 
418 int main(int argc, char **argv) {
419   // Print a stack trace if we signal out.
420   sys::PrintStackTraceOnErrorSignal();
421   PrettyStackTraceProgram X(argc, argv);
422   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
423 
424   // Initialize targets and assembly printers/parsers.
425   llvm::InitializeAllTargetInfos();
426   // FIXME: We shouldn't need to initialize the Target(Machine)s.
427   llvm::InitializeAllTargets();
428   llvm::InitializeAllAsmPrinters();
429   llvm::InitializeAllAsmParsers();
430   llvm::InitializeAllDisassemblers();
431 
432   cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
433   TripleName = Triple::normalize(TripleName);
434 
435   switch (Action) {
436   default:
437   case AC_AsLex:
438     return AsLexInput(argv[0]);
439   case AC_Assemble:
440     return AssembleInput(argv[0]);
441   case AC_Disassemble:
442     return DisassembleInput(argv[0], false);
443   case AC_EDisassemble:
444     return DisassembleInput(argv[0], true);
445   }
446 
447   return 0;
448 }
449 
450