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