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