llvm-mc.cpp 17 KB

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