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