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