llvm-mc.cpp revision 613b7576896fbd03fe495f4ee27b404f81386774
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/MCAsmBackend.h"
18#include "llvm/MC/MCContext.h"
19#include "llvm/MC/MCCodeEmitter.h"
20#include "llvm/MC/MCInstPrinter.h"
21#include "llvm/MC/MCInstrInfo.h"
22#include "llvm/MC/MCObjectFileInfo.h"
23#include "llvm/MC/MCRegisterInfo.h"
24#include "llvm/MC/MCSectionMachO.h"
25#include "llvm/MC/MCStreamer.h"
26#include "llvm/MC/MCSubtargetInfo.h"
27#include "llvm/MC/MCTargetAsmParser.h"
28#include "llvm/MC/SubtargetFeature.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/Support/Host.h"
39#include "llvm/Support/Signals.h"
40#include "llvm/Support/TargetRegistry.h"
41#include "llvm/Support/TargetSelect.h"
42#include "llvm/Support/system_error.h"
43#include "Disassembler.h"
44using namespace llvm;
45
46static cl::opt<std::string>
47InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
48
49static cl::opt<std::string>
50OutputFilename("o", cl::desc("Output filename"),
51               cl::value_desc("filename"));
52
53static cl::opt<bool>
54ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
55
56static cl::opt<bool>
57ShowInst("show-inst", cl::desc("Show internal instruction representation"));
58
59static cl::opt<bool>
60ShowInstOperands("show-inst-operands",
61                 cl::desc("Show instructions operands as parsed"));
62
63static cl::opt<unsigned>
64OutputAsmVariant("output-asm-variant",
65                 cl::desc("Syntax variant to use for output printing"));
66
67static cl::opt<bool>
68RelaxAll("mc-relax-all", cl::desc("Relax all fixups"));
69
70static cl::opt<bool>
71NoExecStack("mc-no-exec-stack", cl::desc("File doesn't need an exec stack"));
72
73static cl::opt<bool>
74EnableLogging("enable-api-logging", cl::desc("Enable MC API logging"));
75
76enum OutputFileType {
77  OFT_Null,
78  OFT_AssemblyFile,
79  OFT_ObjectFile
80};
81static cl::opt<OutputFileType>
82FileType("filetype", cl::init(OFT_AssemblyFile),
83  cl::desc("Choose an output file type:"),
84  cl::values(
85       clEnumValN(OFT_AssemblyFile, "asm",
86                  "Emit an assembly ('.s') file"),
87       clEnumValN(OFT_Null, "null",
88                  "Don't emit anything (for timing purposes)"),
89       clEnumValN(OFT_ObjectFile, "obj",
90                  "Emit a native object ('.o') file"),
91       clEnumValEnd));
92
93static cl::list<std::string>
94IncludeDirs("I", cl::desc("Directory of include files"),
95            cl::value_desc("directory"), cl::Prefix);
96
97static cl::opt<std::string>
98ArchName("arch", cl::desc("Target arch to assemble for, "
99                          "see -version for available targets"));
100
101static cl::opt<std::string>
102TripleName("triple", cl::desc("Target triple to assemble for, "
103                              "see -version for available targets"));
104
105static cl::opt<std::string>
106MCPU("mcpu",
107     cl::desc("Target a specific cpu type (-mcpu=help for details)"),
108     cl::value_desc("cpu-name"),
109     cl::init(""));
110
111static cl::list<std::string>
112MAttrs("mattr",
113  cl::CommaSeparated,
114  cl::desc("Target specific attributes (-mattr=help for details)"),
115  cl::value_desc("a1,+a2,-a3,..."));
116
117static cl::opt<Reloc::Model>
118RelocModel("relocation-model",
119             cl::desc("Choose relocation model"),
120             cl::init(Reloc::Default),
121             cl::values(
122            clEnumValN(Reloc::Default, "default",
123                       "Target default relocation model"),
124            clEnumValN(Reloc::Static, "static",
125                       "Non-relocatable code"),
126            clEnumValN(Reloc::PIC_, "pic",
127                       "Fully relocatable, position independent code"),
128            clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
129                       "Relocatable external references, non-relocatable code"),
130            clEnumValEnd));
131
132static cl::opt<llvm::CodeModel::Model>
133CMModel("code-model",
134        cl::desc("Choose code model"),
135        cl::init(CodeModel::Default),
136        cl::values(clEnumValN(CodeModel::Default, "default",
137                              "Target default code model"),
138                   clEnumValN(CodeModel::Small, "small",
139                              "Small code model"),
140                   clEnumValN(CodeModel::Kernel, "kernel",
141                              "Kernel code model"),
142                   clEnumValN(CodeModel::Medium, "medium",
143                              "Medium code model"),
144                   clEnumValN(CodeModel::Large, "large",
145                              "Large code model"),
146                   clEnumValEnd));
147
148static cl::opt<bool>
149NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
150                                   "in the text section"));
151
152static cl::opt<bool>
153SaveTempLabels("L", cl::desc("Don't discard temporary labels"));
154
155static cl::opt<bool>
156GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
157                                  "source files"));
158
159enum ActionType {
160  AC_AsLex,
161  AC_Assemble,
162  AC_Disassemble,
163  AC_EDisassemble
164};
165
166static cl::opt<ActionType>
167Action(cl::desc("Action to perform:"),
168       cl::init(AC_Assemble),
169       cl::values(clEnumValN(AC_AsLex, "as-lex",
170                             "Lex tokens from a .s file"),
171                  clEnumValN(AC_Assemble, "assemble",
172                             "Assemble a .s file (default)"),
173                  clEnumValN(AC_Disassemble, "disassemble",
174                             "Disassemble strings of hex bytes"),
175                  clEnumValN(AC_EDisassemble, "edis",
176                             "Enhanced disassembly of strings of hex bytes"),
177                  clEnumValEnd));
178
179static const Target *GetTarget(const char *ProgName) {
180  // Figure out the target triple.
181  if (TripleName.empty())
182    TripleName = sys::getDefaultTargetTriple();
183  Triple TheTriple(Triple::normalize(TripleName));
184
185  const Target *TheTarget = 0;
186  if (!ArchName.empty()) {
187    for (TargetRegistry::iterator it = TargetRegistry::begin(),
188           ie = TargetRegistry::end(); it != ie; ++it) {
189      if (ArchName == it->getName()) {
190        TheTarget = &*it;
191        break;
192      }
193    }
194
195    if (!TheTarget) {
196      errs() << ProgName << ": error: invalid target '" << ArchName << "'.\n";
197      return 0;
198    }
199
200    // Adjust the triple to match (if known), otherwise stick with the
201    // module/host triple.
202    Triple::ArchType Type = Triple::getArchTypeForLLVMName(ArchName);
203    if (Type != Triple::UnknownArch)
204      TheTriple.setArch(Type);
205  } else {
206    // Get the target specific parser.
207    std::string Error;
208    TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Error);
209    if (TheTarget == 0) {
210      errs() << ProgName << ": error: unable to get target for '"
211             << TheTriple.getTriple()
212             << "', see --version and --triple.\n";
213      return 0;
214    }
215  }
216
217  TripleName = TheTriple.getTriple();
218  return TheTarget;
219}
220
221static tool_output_file *GetOutputStream() {
222  if (OutputFilename == "")
223    OutputFilename = "-";
224
225  std::string Err;
226  tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
227                                               raw_fd_ostream::F_Binary);
228  if (!Err.empty()) {
229    errs() << Err << '\n';
230    delete Out;
231    return 0;
232  }
233
234  return Out;
235}
236
237static int AsLexInput(const char *ProgName) {
238  OwningPtr<MemoryBuffer> BufferPtr;
239  if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
240    errs() << ProgName << ": " << ec.message() << '\n';
241    return 1;
242  }
243  MemoryBuffer *Buffer = BufferPtr.take();
244
245  SourceMgr SrcMgr;
246
247  // Tell SrcMgr about this buffer, which is what TGParser will pick up.
248  SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
249
250  // Record the location of the include directories so that the lexer can find
251  // it later.
252  SrcMgr.setIncludeDirs(IncludeDirs);
253
254  const Target *TheTarget = GetTarget(ProgName);
255  if (!TheTarget)
256    return 1;
257
258  llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
259  assert(MAI && "Unable to create target asm info!");
260
261  AsmLexer Lexer(*MAI);
262  Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
263
264  OwningPtr<tool_output_file> Out(GetOutputStream());
265  if (!Out)
266    return 1;
267
268  bool Error = false;
269  while (Lexer.Lex().isNot(AsmToken::Eof)) {
270    AsmToken Tok = Lexer.getTok();
271
272    switch (Tok.getKind()) {
273    default:
274      SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
275                          "unknown token");
276      Error = true;
277      break;
278    case AsmToken::Error:
279      Error = true; // error already printed.
280      break;
281    case AsmToken::Identifier:
282      Out->os() << "identifier: " << Lexer.getTok().getString();
283      break;
284    case AsmToken::Integer:
285      Out->os() << "int: " << Lexer.getTok().getString();
286      break;
287    case AsmToken::Real:
288      Out->os() << "real: " << Lexer.getTok().getString();
289      break;
290    case AsmToken::Register:
291      Out->os() << "register: " << Lexer.getTok().getRegVal();
292      break;
293    case AsmToken::String:
294      Out->os() << "string: " << Lexer.getTok().getString();
295      break;
296
297    case AsmToken::Amp:            Out->os() << "Amp"; break;
298    case AsmToken::AmpAmp:         Out->os() << "AmpAmp"; break;
299    case AsmToken::At:             Out->os() << "At"; break;
300    case AsmToken::Caret:          Out->os() << "Caret"; break;
301    case AsmToken::Colon:          Out->os() << "Colon"; break;
302    case AsmToken::Comma:          Out->os() << "Comma"; break;
303    case AsmToken::Dollar:         Out->os() << "Dollar"; break;
304    case AsmToken::Dot:            Out->os() << "Dot"; break;
305    case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
306    case AsmToken::Eof:            Out->os() << "Eof"; break;
307    case AsmToken::Equal:          Out->os() << "Equal"; break;
308    case AsmToken::EqualEqual:     Out->os() << "EqualEqual"; break;
309    case AsmToken::Exclaim:        Out->os() << "Exclaim"; break;
310    case AsmToken::ExclaimEqual:   Out->os() << "ExclaimEqual"; break;
311    case AsmToken::Greater:        Out->os() << "Greater"; break;
312    case AsmToken::GreaterEqual:   Out->os() << "GreaterEqual"; break;
313    case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
314    case AsmToken::Hash:           Out->os() << "Hash"; break;
315    case AsmToken::LBrac:          Out->os() << "LBrac"; break;
316    case AsmToken::LCurly:         Out->os() << "LCurly"; break;
317    case AsmToken::LParen:         Out->os() << "LParen"; break;
318    case AsmToken::Less:           Out->os() << "Less"; break;
319    case AsmToken::LessEqual:      Out->os() << "LessEqual"; break;
320    case AsmToken::LessGreater:    Out->os() << "LessGreater"; break;
321    case AsmToken::LessLess:       Out->os() << "LessLess"; break;
322    case AsmToken::Minus:          Out->os() << "Minus"; break;
323    case AsmToken::Percent:        Out->os() << "Percent"; break;
324    case AsmToken::Pipe:           Out->os() << "Pipe"; break;
325    case AsmToken::PipePipe:       Out->os() << "PipePipe"; break;
326    case AsmToken::Plus:           Out->os() << "Plus"; break;
327    case AsmToken::RBrac:          Out->os() << "RBrac"; break;
328    case AsmToken::RCurly:         Out->os() << "RCurly"; break;
329    case AsmToken::RParen:         Out->os() << "RParen"; break;
330    case AsmToken::Slash:          Out->os() << "Slash"; break;
331    case AsmToken::Star:           Out->os() << "Star"; break;
332    case AsmToken::Tilde:          Out->os() << "Tilde"; break;
333    }
334
335    // Print the token string.
336    Out->os() << " (\"";
337    Out->os().write_escaped(Tok.getString());
338    Out->os() << "\")\n";
339  }
340
341  // Keep output if no errors.
342  if (Error == 0) Out->keep();
343
344  return Error;
345}
346
347static int AssembleInput(const char *ProgName) {
348  const Target *TheTarget = GetTarget(ProgName);
349  if (!TheTarget)
350    return 1;
351
352  OwningPtr<MemoryBuffer> BufferPtr;
353  if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
354    errs() << ProgName << ": " << ec.message() << '\n';
355    return 1;
356  }
357  MemoryBuffer *Buffer = BufferPtr.take();
358
359  SourceMgr SrcMgr;
360
361  // Tell SrcMgr about this buffer, which is what the parser will pick up.
362  SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
363
364  // Record the location of the include directories so that the lexer can find
365  // it later.
366  SrcMgr.setIncludeDirs(IncludeDirs);
367
368
369  llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
370  assert(MAI && "Unable to create target asm info!");
371
372  llvm::OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
373  assert(MRI && "Unable to create target register info!");
374
375  // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
376  // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
377  OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
378  MCContext Ctx(*MAI, *MRI, MOFI.get());
379  MOFI->InitMCObjectFileInfo(TripleName, RelocModel, CMModel, Ctx);
380
381  if (SaveTempLabels)
382    Ctx.setAllowTemporaryLabels(false);
383
384  Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
385
386  // Package up features to be passed to target/subtarget
387  std::string FeaturesStr;
388  if (MAttrs.size()) {
389    SubtargetFeatures Features;
390    for (unsigned i = 0; i != MAttrs.size(); ++i)
391      Features.AddFeature(MAttrs[i]);
392    FeaturesStr = Features.getString();
393  }
394
395  OwningPtr<tool_output_file> Out(GetOutputStream());
396  if (!Out)
397    return 1;
398
399  formatted_raw_ostream FOS(Out->os());
400  OwningPtr<MCStreamer> Str;
401
402  OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
403  OwningPtr<MCSubtargetInfo>
404    STI(TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
405
406  // FIXME: There is a bit of code duplication with addPassesToEmitFile.
407  if (FileType == OFT_AssemblyFile) {
408    MCInstPrinter *IP =
409      TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *STI);
410    MCCodeEmitter *CE = 0;
411    MCAsmBackend *MAB = 0;
412    if (ShowEncoding) {
413      CE = TheTarget->createMCCodeEmitter(*MCII, *STI, Ctx);
414      MAB = TheTarget->createMCAsmBackend(TripleName);
415    }
416    Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/true,
417                                           /*useLoc*/ true,
418                                           /*useCFI*/ true,
419                                           /*useDwarfDirectory*/ true,
420                                           IP, CE, MAB, ShowInst));
421
422  } else if (FileType == OFT_Null) {
423    Str.reset(createNullStreamer(Ctx));
424  } else {
425    assert(FileType == OFT_ObjectFile && "Invalid file type!");
426    MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *STI, Ctx);
427    MCAsmBackend *MAB = TheTarget->createMCAsmBackend(TripleName);
428    Str.reset(TheTarget->createMCObjectStreamer(TripleName, Ctx, *MAB,
429                                                FOS, CE, RelaxAll,
430                                                NoExecStack));
431  }
432
433  if (EnableLogging) {
434    Str.reset(createLoggingStreamer(Str.take(), errs()));
435  }
436
437  OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx,
438                                                  *Str.get(), *MAI));
439  OwningPtr<MCTargetAsmParser> TAP(TheTarget->createMCAsmParser(*STI, *Parser));
440  if (!TAP) {
441    errs() << ProgName
442           << ": error: this target does not support assembly parsing.\n";
443    return 1;
444  }
445
446  Parser->setShowParsedOperands(ShowInstOperands);
447  Parser->setTargetParser(*TAP.get());
448
449  int Res = Parser->Run(NoInitialTextSection);
450
451  // Keep output if no errors.
452  if (Res == 0) Out->keep();
453
454  return Res;
455}
456
457static int DisassembleInput(const char *ProgName, bool Enhanced) {
458  const Target *TheTarget = GetTarget(ProgName);
459  if (!TheTarget)
460    return 0;
461
462  OwningPtr<MemoryBuffer> Buffer;
463  if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, Buffer)) {
464    errs() << ProgName << ": " << ec.message() << '\n';
465    return 1;
466  }
467
468  OwningPtr<tool_output_file> Out(GetOutputStream());
469  if (!Out)
470    return 1;
471
472  int Res;
473  if (Enhanced) {
474    Res =
475      Disassembler::disassembleEnhanced(TripleName, *Buffer.take(), Out->os());
476  } else {
477    // Package up features to be passed to target/subtarget
478    std::string FeaturesStr;
479    if (MAttrs.size()) {
480      SubtargetFeatures Features;
481      for (unsigned i = 0; i != MAttrs.size(); ++i)
482        Features.AddFeature(MAttrs[i]);
483      FeaturesStr = Features.getString();
484    }
485
486    Res = Disassembler::disassemble(*TheTarget, TripleName, MCPU, FeaturesStr,
487                                    *Buffer.take(), Out->os());
488  }
489
490  // Keep output if no errors.
491  if (Res == 0) Out->keep();
492
493  return Res;
494}
495
496
497int main(int argc, char **argv) {
498  // Print a stack trace if we signal out.
499  sys::PrintStackTraceOnErrorSignal();
500  PrettyStackTraceProgram X(argc, argv);
501  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
502
503  // Initialize targets and assembly printers/parsers.
504  llvm::InitializeAllTargetInfos();
505  llvm::InitializeAllTargetMCs();
506  llvm::InitializeAllAsmParsers();
507  llvm::InitializeAllDisassemblers();
508
509  cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
510  TripleName = Triple::normalize(TripleName);
511
512  switch (Action) {
513  default:
514  case AC_AsLex:
515    return AsLexInput(argv[0]);
516  case AC_Assemble:
517    return AssembleInput(argv[0]);
518  case AC_Disassemble:
519    return DisassembleInput(argv[0], false);
520  case AC_EDisassemble:
521    return DisassembleInput(argv[0], true);
522  }
523
524  return 0;
525}
526