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