1//===-- llvm-mc.cpp - Machine Code Hacking Driver ---------------*- C++ -*-===//
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 "Disassembler.h"
16#include "llvm/MC/MCAsmBackend.h"
17#include "llvm/MC/MCAsmInfo.h"
18#include "llvm/MC/MCContext.h"
19#include "llvm/MC/MCInstPrinter.h"
20#include "llvm/MC/MCInstrInfo.h"
21#include "llvm/MC/MCObjectFileInfo.h"
22#include "llvm/MC/MCParser/AsmLexer.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/MCTargetOptionsCommandFlags.h"
29#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Compression.h"
31#include "llvm/Support/FileUtilities.h"
32#include "llvm/Support/FormattedStream.h"
33#include "llvm/Support/Host.h"
34#include "llvm/Support/ManagedStatic.h"
35#include "llvm/Support/MemoryBuffer.h"
36#include "llvm/Support/PrettyStackTrace.h"
37#include "llvm/Support/Signals.h"
38#include "llvm/Support/SourceMgr.h"
39#include "llvm/Support/TargetRegistry.h"
40#include "llvm/Support/TargetSelect.h"
41#include "llvm/Support/ToolOutputFile.h"
42
43using namespace llvm;
44
45static cl::opt<std::string>
46InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
47
48static cl::opt<std::string>
49OutputFilename("o", cl::desc("Output filename"),
50               cl::value_desc("filename"));
51
52static cl::opt<bool>
53ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
54
55static cl::opt<bool>
56CompressDebugSections("compress-debug-sections",
57                      cl::desc("Compress DWARF debug sections"));
58
59static cl::opt<bool>
60ShowInst("show-inst", cl::desc("Show internal instruction representation"));
61
62static cl::opt<bool>
63ShowInstOperands("show-inst-operands",
64                 cl::desc("Show instructions operands as parsed"));
65
66static cl::opt<unsigned>
67OutputAsmVariant("output-asm-variant",
68                 cl::desc("Syntax variant to use for output printing"));
69
70static cl::opt<bool>
71PrintImmHex("print-imm-hex", cl::init(false),
72            cl::desc("Prefer hex format for immediate values"));
73
74static cl::list<std::string>
75DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
76
77enum OutputFileType {
78  OFT_Null,
79  OFT_AssemblyFile,
80  OFT_ObjectFile
81};
82static cl::opt<OutputFileType>
83FileType("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
94static cl::list<std::string>
95IncludeDirs("I", cl::desc("Directory of include files"),
96            cl::value_desc("directory"), cl::Prefix);
97
98static cl::opt<std::string>
99ArchName("arch", cl::desc("Target arch to assemble for, "
100                          "see -version for available targets"));
101
102static cl::opt<std::string>
103TripleName("triple", cl::desc("Target triple to assemble for, "
104                              "see -version for available targets"));
105
106static cl::opt<std::string>
107MCPU("mcpu",
108     cl::desc("Target a specific cpu type (-mcpu=help for details)"),
109     cl::value_desc("cpu-name"),
110     cl::init(""));
111
112static cl::list<std::string>
113MAttrs("mattr",
114  cl::CommaSeparated,
115  cl::desc("Target specific attributes (-mattr=help for details)"),
116  cl::value_desc("a1,+a2,-a3,..."));
117
118static cl::opt<Reloc::Model>
119RelocModel("relocation-model",
120             cl::desc("Choose relocation model"),
121             cl::init(Reloc::Default),
122             cl::values(
123            clEnumValN(Reloc::Default, "default",
124                       "Target default relocation model"),
125            clEnumValN(Reloc::Static, "static",
126                       "Non-relocatable code"),
127            clEnumValN(Reloc::PIC_, "pic",
128                       "Fully relocatable, position independent code"),
129            clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
130                       "Relocatable external references, non-relocatable code"),
131            clEnumValEnd));
132
133static cl::opt<llvm::CodeModel::Model>
134CMModel("code-model",
135        cl::desc("Choose code model"),
136        cl::init(CodeModel::Default),
137        cl::values(clEnumValN(CodeModel::Default, "default",
138                              "Target default code model"),
139                   clEnumValN(CodeModel::Small, "small",
140                              "Small code model"),
141                   clEnumValN(CodeModel::Kernel, "kernel",
142                              "Kernel code model"),
143                   clEnumValN(CodeModel::Medium, "medium",
144                              "Medium code model"),
145                   clEnumValN(CodeModel::Large, "large",
146                              "Large code model"),
147                   clEnumValEnd));
148
149static cl::opt<bool>
150NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
151                                   "in the text section"));
152
153static cl::opt<bool>
154GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
155                                  "source files"));
156
157static cl::opt<std::string>
158DebugCompilationDir("fdebug-compilation-dir",
159                    cl::desc("Specifies the debug info's compilation dir"));
160
161static cl::opt<std::string>
162MainFileName("main-file-name",
163             cl::desc("Specifies the name we should consider the input file"));
164
165static cl::opt<bool> SaveTempLabels("save-temp-labels",
166                                    cl::desc("Don't discard temporary labels"));
167
168static cl::opt<bool> NoExecStack("no-exec-stack",
169                                 cl::desc("File doesn't need an exec stack"));
170
171enum ActionType {
172  AC_AsLex,
173  AC_Assemble,
174  AC_Disassemble,
175  AC_MDisassemble,
176};
177
178static cl::opt<ActionType>
179Action(cl::desc("Action to perform:"),
180       cl::init(AC_Assemble),
181       cl::values(clEnumValN(AC_AsLex, "as-lex",
182                             "Lex tokens from a .s file"),
183                  clEnumValN(AC_Assemble, "assemble",
184                             "Assemble a .s file (default)"),
185                  clEnumValN(AC_Disassemble, "disassemble",
186                             "Disassemble strings of hex bytes"),
187                  clEnumValN(AC_MDisassemble, "mdis",
188                             "Marked up disassembly of strings of hex bytes"),
189                  clEnumValEnd));
190
191static const Target *GetTarget(const char *ProgName) {
192  // Figure out the target triple.
193  if (TripleName.empty())
194    TripleName = sys::getDefaultTargetTriple();
195  Triple TheTriple(Triple::normalize(TripleName));
196
197  // Get the target specific parser.
198  std::string Error;
199  const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
200                                                         Error);
201  if (!TheTarget) {
202    errs() << ProgName << ": " << Error;
203    return nullptr;
204  }
205
206  // Update the triple name and return the found target.
207  TripleName = TheTriple.getTriple();
208  return TheTarget;
209}
210
211static std::unique_ptr<tool_output_file> GetOutputStream() {
212  if (OutputFilename == "")
213    OutputFilename = "-";
214
215  std::error_code EC;
216  auto Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
217                                                 sys::fs::F_None);
218  if (EC) {
219    errs() << EC.message() << '\n';
220    return nullptr;
221  }
222
223  return Out;
224}
225
226static std::string DwarfDebugFlags;
227static void setDwarfDebugFlags(int argc, char **argv) {
228  if (!getenv("RC_DEBUG_OPTIONS"))
229    return;
230  for (int i = 0; i < argc; i++) {
231    DwarfDebugFlags += argv[i];
232    if (i + 1 < argc)
233      DwarfDebugFlags += " ";
234  }
235}
236
237static std::string DwarfDebugProducer;
238static void setDwarfDebugProducer() {
239  if(!getenv("DEBUG_PRODUCER"))
240    return;
241  DwarfDebugProducer += getenv("DEBUG_PRODUCER");
242}
243
244static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
245                      raw_ostream &OS) {
246
247  AsmLexer Lexer(MAI);
248  Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
249
250  bool Error = false;
251  while (Lexer.Lex().isNot(AsmToken::Eof)) {
252    AsmToken Tok = Lexer.getTok();
253
254    switch (Tok.getKind()) {
255    default:
256      SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
257                          "unknown token");
258      Error = true;
259      break;
260    case AsmToken::Error:
261      Error = true; // error already printed.
262      break;
263    case AsmToken::Identifier:
264      OS << "identifier: " << Lexer.getTok().getString();
265      break;
266    case AsmToken::Integer:
267      OS << "int: " << Lexer.getTok().getString();
268      break;
269    case AsmToken::Real:
270      OS << "real: " << Lexer.getTok().getString();
271      break;
272    case AsmToken::String:
273      OS << "string: " << Lexer.getTok().getString();
274      break;
275
276    case AsmToken::Amp:            OS << "Amp"; break;
277    case AsmToken::AmpAmp:         OS << "AmpAmp"; break;
278    case AsmToken::At:             OS << "At"; break;
279    case AsmToken::Caret:          OS << "Caret"; break;
280    case AsmToken::Colon:          OS << "Colon"; break;
281    case AsmToken::Comma:          OS << "Comma"; break;
282    case AsmToken::Dollar:         OS << "Dollar"; break;
283    case AsmToken::Dot:            OS << "Dot"; break;
284    case AsmToken::EndOfStatement: OS << "EndOfStatement"; break;
285    case AsmToken::Eof:            OS << "Eof"; break;
286    case AsmToken::Equal:          OS << "Equal"; break;
287    case AsmToken::EqualEqual:     OS << "EqualEqual"; break;
288    case AsmToken::Exclaim:        OS << "Exclaim"; break;
289    case AsmToken::ExclaimEqual:   OS << "ExclaimEqual"; break;
290    case AsmToken::Greater:        OS << "Greater"; break;
291    case AsmToken::GreaterEqual:   OS << "GreaterEqual"; break;
292    case AsmToken::GreaterGreater: OS << "GreaterGreater"; break;
293    case AsmToken::Hash:           OS << "Hash"; break;
294    case AsmToken::LBrac:          OS << "LBrac"; break;
295    case AsmToken::LCurly:         OS << "LCurly"; break;
296    case AsmToken::LParen:         OS << "LParen"; break;
297    case AsmToken::Less:           OS << "Less"; break;
298    case AsmToken::LessEqual:      OS << "LessEqual"; break;
299    case AsmToken::LessGreater:    OS << "LessGreater"; break;
300    case AsmToken::LessLess:       OS << "LessLess"; break;
301    case AsmToken::Minus:          OS << "Minus"; break;
302    case AsmToken::Percent:        OS << "Percent"; break;
303    case AsmToken::Pipe:           OS << "Pipe"; break;
304    case AsmToken::PipePipe:       OS << "PipePipe"; break;
305    case AsmToken::Plus:           OS << "Plus"; break;
306    case AsmToken::RBrac:          OS << "RBrac"; break;
307    case AsmToken::RCurly:         OS << "RCurly"; break;
308    case AsmToken::RParen:         OS << "RParen"; break;
309    case AsmToken::Slash:          OS << "Slash"; break;
310    case AsmToken::Star:           OS << "Star"; break;
311    case AsmToken::Tilde:          OS << "Tilde"; break;
312    }
313
314    // Print the token string.
315    OS << " (\"";
316    OS.write_escaped(Tok.getString());
317    OS << "\")\n";
318  }
319
320  return Error;
321}
322
323static int fillCommandLineSymbols(MCAsmParser &Parser){
324  for(auto &I: DefineSymbol){
325    auto Pair = StringRef(I).split('=');
326    if(Pair.second.empty()){
327      errs() << "error: defsym must be of the form: sym=value: " << I;
328      return 1;
329    }
330    int64_t Value;
331    if(Pair.second.getAsInteger(0, Value)){
332      errs() << "error: Value is not an integer: " << Pair.second;
333      return 1;
334    }
335    auto &Context = Parser.getContext();
336    auto Symbol = Context.getOrCreateSymbol(Pair.first);
337    Parser.getStreamer().EmitAssignment(Symbol,
338                                        MCConstantExpr::create(Value, Context));
339  }
340  return 0;
341}
342
343static int AssembleInput(const char *ProgName, const Target *TheTarget,
344                         SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
345                         MCAsmInfo &MAI, MCSubtargetInfo &STI,
346                         MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
347  std::unique_ptr<MCAsmParser> Parser(
348      createMCAsmParser(SrcMgr, Ctx, Str, MAI));
349  std::unique_ptr<MCTargetAsmParser> TAP(
350      TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
351
352  if (!TAP) {
353    errs() << ProgName
354           << ": error: this target does not support assembly parsing.\n";
355    return 1;
356  }
357
358  int SymbolResult = fillCommandLineSymbols(*Parser);
359  if(SymbolResult)
360    return SymbolResult;
361  Parser->setShowParsedOperands(ShowInstOperands);
362  Parser->setTargetParser(*TAP);
363
364  int Res = Parser->Run(NoInitialTextSection);
365
366  return Res;
367}
368
369int main(int argc, char **argv) {
370  // Print a stack trace if we signal out.
371  sys::PrintStackTraceOnErrorSignal();
372  PrettyStackTraceProgram X(argc, argv);
373  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
374
375  // Initialize targets and assembly printers/parsers.
376  llvm::InitializeAllTargetInfos();
377  llvm::InitializeAllTargetMCs();
378  llvm::InitializeAllAsmParsers();
379  llvm::InitializeAllDisassemblers();
380
381  // Register the target printer for --version.
382  cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
383
384  cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
385  MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
386  TripleName = Triple::normalize(TripleName);
387  setDwarfDebugFlags(argc, argv);
388
389  setDwarfDebugProducer();
390
391  const char *ProgName = argv[0];
392  const Target *TheTarget = GetTarget(ProgName);
393  if (!TheTarget)
394    return 1;
395  // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
396  // construct the Triple object.
397  Triple TheTriple(TripleName);
398
399  ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
400      MemoryBuffer::getFileOrSTDIN(InputFilename);
401  if (std::error_code EC = BufferPtr.getError()) {
402    errs() << InputFilename << ": " << EC.message() << '\n';
403    return 1;
404  }
405  MemoryBuffer *Buffer = BufferPtr->get();
406
407  SourceMgr SrcMgr;
408
409  // Tell SrcMgr about this buffer, which is what the parser will pick up.
410  SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
411
412  // Record the location of the include directories so that the lexer can find
413  // it later.
414  SrcMgr.setIncludeDirs(IncludeDirs);
415
416  std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
417  assert(MRI && "Unable to create target register info!");
418
419  std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
420  assert(MAI && "Unable to create target asm info!");
421
422  if (CompressDebugSections) {
423    if (!zlib::isAvailable()) {
424      errs() << ProgName
425             << ": build tools with zlib to enable -compress-debug-sections";
426      return 1;
427    }
428    MAI->setCompressDebugSections(true);
429  }
430
431  // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
432  // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
433  MCObjectFileInfo MOFI;
434  MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
435  MOFI.InitMCObjectFileInfo(TheTriple, RelocModel, CMModel, Ctx);
436
437  if (SaveTempLabels)
438    Ctx.setAllowTemporaryLabels(false);
439
440  Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
441  // Default to 4 for dwarf version.
442  unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
443  if (DwarfVersion < 2 || DwarfVersion > 4) {
444    errs() << ProgName << ": Dwarf version " << DwarfVersion
445           << " is not supported." << '\n';
446    return 1;
447  }
448  Ctx.setDwarfVersion(DwarfVersion);
449  if (!DwarfDebugFlags.empty())
450    Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
451  if (!DwarfDebugProducer.empty())
452    Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
453  if (!DebugCompilationDir.empty())
454    Ctx.setCompilationDir(DebugCompilationDir);
455  if (!MainFileName.empty())
456    Ctx.setMainFileName(MainFileName);
457
458  // Package up features to be passed to target/subtarget
459  std::string FeaturesStr;
460  if (MAttrs.size()) {
461    SubtargetFeatures Features;
462    for (unsigned i = 0; i != MAttrs.size(); ++i)
463      Features.AddFeature(MAttrs[i]);
464    FeaturesStr = Features.getString();
465  }
466
467  std::unique_ptr<tool_output_file> Out = GetOutputStream();
468  if (!Out)
469    return 1;
470
471  std::unique_ptr<buffer_ostream> BOS;
472  raw_pwrite_stream *OS = &Out->os();
473  std::unique_ptr<MCStreamer> Str;
474
475  std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
476  std::unique_ptr<MCSubtargetInfo> STI(
477      TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
478
479  MCInstPrinter *IP = nullptr;
480  if (FileType == OFT_AssemblyFile) {
481    IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
482                                        *MAI, *MCII, *MRI);
483
484    // Set the display preference for hex vs. decimal immediates.
485    IP->setPrintImmHex(PrintImmHex);
486
487    // Set up the AsmStreamer.
488    MCCodeEmitter *CE = nullptr;
489    MCAsmBackend *MAB = nullptr;
490    if (ShowEncoding) {
491      CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
492      MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
493    }
494    auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
495    Str.reset(TheTarget->createAsmStreamer(
496        Ctx, std::move(FOut), /*asmverbose*/ true,
497        /*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst));
498
499  } else if (FileType == OFT_Null) {
500    Str.reset(TheTarget->createNullStreamer(Ctx));
501  } else {
502    assert(FileType == OFT_ObjectFile && "Invalid file type!");
503
504    // Don't waste memory on names of temp labels.
505    Ctx.setUseNamesOnTempLabels(false);
506
507    if (!Out->os().supportsSeeking()) {
508      BOS = make_unique<buffer_ostream>(Out->os());
509      OS = BOS.get();
510    }
511
512    MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
513    MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
514    Str.reset(TheTarget->createMCObjectStreamer(
515        TheTriple, Ctx, *MAB, *OS, CE, *STI, MCOptions.MCRelaxAll,
516        MCOptions.MCIncrementalLinkerCompatible,
517        /*DWARFMustBeAtTheEnd*/ false));
518    if (NoExecStack)
519      Str->InitSections(true);
520  }
521
522  int Res = 1;
523  bool disassemble = false;
524  switch (Action) {
525  case AC_AsLex:
526    Res = AsLexInput(SrcMgr, *MAI, Out->os());
527    break;
528  case AC_Assemble:
529    Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
530                        *MCII, MCOptions);
531    break;
532  case AC_MDisassemble:
533    assert(IP && "Expected assembly output");
534    IP->setUseMarkup(1);
535    disassemble = true;
536    break;
537  case AC_Disassemble:
538    disassemble = true;
539    break;
540  }
541  if (disassemble)
542    Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
543                                    *Buffer, SrcMgr, Out->os());
544
545  // Keep output if no errors.
546  if (Res == 0) Out->keep();
547  return Res;
548}
549