1 //===-- llvm-mc.cpp - Machine Code Hacking Driver -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This utility is a simple driver that allows command line hacking on machine
13 //===----------------------------------------------------------------------===//
15 #include "llvm/MC/MCParser/MCAsmLexer.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCInstPrinter.h"
19 #include "llvm/MC/MCSectionMachO.h"
20 #include "llvm/MC/MCStreamer.h"
21 #include "llvm/MC/MCParser/AsmParser.h"
22 #include "llvm/Target/TargetAsmBackend.h"
23 #include "llvm/Target/TargetAsmParser.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetRegistry.h"
26 #include "llvm/Target/TargetMachine.h" // FIXME.
27 #include "llvm/Target/TargetSelect.h"
28 #include "llvm/ADT/OwningPtr.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/FormattedStream.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/PrettyStackTrace.h"
34 #include "llvm/Support/SourceMgr.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/System/Host.h"
37 #include "llvm/System/Signals.h"
38 #include "Disassembler.h"
41 static cl::opt<std::string>
42 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
44 static cl::opt<std::string>
45 OutputFilename("o", cl::desc("Output filename"),
46 cl::value_desc("filename"));
49 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
52 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
54 static cl::opt<unsigned>
55 OutputAsmVariant("output-asm-variant",
56 cl::desc("Syntax variant to use for output printing"));
59 RelaxAll("mc-relax-all", cl::desc("Relax all fixups"));
62 EnableLogging("enable-api-logging", cl::desc("Enable MC API logging"));
69 static cl::opt<OutputFileType>
70 FileType("filetype", cl::init(OFT_AssemblyFile),
71 cl::desc("Choose an output file type:"),
73 clEnumValN(OFT_AssemblyFile, "asm",
74 "Emit an assembly ('.s') file"),
75 clEnumValN(OFT_Null, "null",
76 "Don't emit anything (for timing purposes)"),
77 clEnumValN(OFT_ObjectFile, "obj",
78 "Emit a native object ('.o') file"),
81 static cl::list<std::string>
82 IncludeDirs("I", cl::desc("Directory of include files"),
83 cl::value_desc("directory"), cl::Prefix);
85 static cl::opt<std::string>
86 ArchName("arch", cl::desc("Target arch to assemble for, "
87 "see -version for available targets"));
89 static cl::opt<std::string>
90 TripleName("triple", cl::desc("Target triple to assemble for, "
91 "see -version for available targets"));
94 NoInitialTextSection("n", cl::desc(
95 "Don't assume assembly file starts in the text section"));
104 static cl::opt<ActionType>
105 Action(cl::desc("Action to perform:"),
106 cl::init(AC_Assemble),
107 cl::values(clEnumValN(AC_AsLex, "as-lex",
108 "Lex tokens from a .s file"),
109 clEnumValN(AC_Assemble, "assemble",
110 "Assemble a .s file (default)"),
111 clEnumValN(AC_Disassemble, "disassemble",
112 "Disassemble strings of hex bytes"),
113 clEnumValN(AC_EDisassemble, "edis",
114 "Enhanced disassembly of strings of hex bytes"),
117 static const Target *GetTarget(const char *ProgName) {
118 // Figure out the target triple.
119 if (TripleName.empty())
120 TripleName = sys::getHostTriple();
121 if (!ArchName.empty()) {
122 llvm::Triple TT(TripleName);
123 TT.setArchName(ArchName);
124 TripleName = TT.str();
127 // Get the target specific parser.
129 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
133 errs() << ProgName << ": error: unable to get target for '" << TripleName
134 << "', see --version and --triple.\n";
138 static int AsLexInput(const char *ProgName) {
139 std::string ErrorMessage;
140 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
143 errs() << ProgName << ": ";
144 if (ErrorMessage.size())
145 errs() << ErrorMessage << "\n";
147 errs() << "input file didn't read correctly.\n";
153 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
154 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
156 // Record the location of the include directories so that the lexer can find
158 SrcMgr.setIncludeDirs(IncludeDirs);
160 const Target *TheTarget = GetTarget(ProgName);
164 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(TripleName));
165 assert(MAI && "Unable to create target asm info!");
167 AsmLexer Lexer(*MAI);
171 while (Lexer.Lex().isNot(AsmToken::Eof)) {
172 switch (Lexer.getKind()) {
174 SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
177 case AsmToken::Error:
178 Error = true; // error already printed.
180 case AsmToken::Identifier:
181 outs() << "identifier: " << Lexer.getTok().getString() << '\n';
183 case AsmToken::String:
184 outs() << "string: " << Lexer.getTok().getString() << '\n';
186 case AsmToken::Integer:
187 outs() << "int: " << Lexer.getTok().getString() << '\n';
190 case AsmToken::Amp: outs() << "Amp\n"; break;
191 case AsmToken::AmpAmp: outs() << "AmpAmp\n"; break;
192 case AsmToken::Caret: outs() << "Caret\n"; break;
193 case AsmToken::Colon: outs() << "Colon\n"; break;
194 case AsmToken::Comma: outs() << "Comma\n"; break;
195 case AsmToken::Dollar: outs() << "Dollar\n"; break;
196 case AsmToken::EndOfStatement: outs() << "EndOfStatement\n"; break;
197 case AsmToken::Eof: outs() << "Eof\n"; break;
198 case AsmToken::Equal: outs() << "Equal\n"; break;
199 case AsmToken::EqualEqual: outs() << "EqualEqual\n"; break;
200 case AsmToken::Exclaim: outs() << "Exclaim\n"; break;
201 case AsmToken::ExclaimEqual: outs() << "ExclaimEqual\n"; break;
202 case AsmToken::Greater: outs() << "Greater\n"; break;
203 case AsmToken::GreaterEqual: outs() << "GreaterEqual\n"; break;
204 case AsmToken::GreaterGreater: outs() << "GreaterGreater\n"; break;
205 case AsmToken::LParen: outs() << "LParen\n"; break;
206 case AsmToken::Less: outs() << "Less\n"; break;
207 case AsmToken::LessEqual: outs() << "LessEqual\n"; break;
208 case AsmToken::LessGreater: outs() << "LessGreater\n"; break;
209 case AsmToken::LessLess: outs() << "LessLess\n"; break;
210 case AsmToken::Minus: outs() << "Minus\n"; break;
211 case AsmToken::Percent: outs() << "Percent\n"; break;
212 case AsmToken::Pipe: outs() << "Pipe\n"; break;
213 case AsmToken::PipePipe: outs() << "PipePipe\n"; break;
214 case AsmToken::Plus: outs() << "Plus\n"; break;
215 case AsmToken::RParen: outs() << "RParen\n"; break;
216 case AsmToken::Slash: outs() << "Slash\n"; break;
217 case AsmToken::Star: outs() << "Star\n"; break;
218 case AsmToken::Tilde: outs() << "Tilde\n"; break;
225 static formatted_raw_ostream *GetOutputStream() {
226 if (OutputFilename == "")
227 OutputFilename = "-";
229 // Make sure that the Out file gets unlinked from the disk if we get a
231 if (OutputFilename != "-")
232 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
235 raw_fd_ostream *Out = new raw_fd_ostream(OutputFilename.c_str(), Err,
236 raw_fd_ostream::F_Binary);
238 errs() << Err << '\n';
243 return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
246 static int AssembleInput(const char *ProgName) {
247 const Target *TheTarget = GetTarget(ProgName);
252 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, &Error);
254 errs() << ProgName << ": ";
256 errs() << Error << "\n";
258 errs() << "input file didn't read correctly.\n";
264 // Tell SrcMgr about this buffer, which is what the parser will pick up.
265 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
267 // Record the location of the include directories so that the lexer can find
269 SrcMgr.setIncludeDirs(IncludeDirs);
272 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(TripleName));
273 assert(MAI && "Unable to create target asm info!");
276 formatted_raw_ostream *Out = GetOutputStream();
281 // FIXME: We shouldn't need to do this (and link in codegen).
282 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName, ""));
285 errs() << ProgName << ": error: could not create target for triple '"
286 << TripleName << "'.\n";
290 OwningPtr<MCCodeEmitter> CE;
291 OwningPtr<MCStreamer> Str;
292 OwningPtr<TargetAsmBackend> TAB;
294 if (FileType == OFT_AssemblyFile) {
296 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI);
298 CE.reset(TheTarget->createCodeEmitter(*TM, Ctx));
299 Str.reset(createAsmStreamer(Ctx, *Out,TM->getTargetData()->isLittleEndian(),
300 /*asmverbose*/true, IP, CE.get(), ShowInst));
301 } else if (FileType == OFT_Null) {
302 Str.reset(createNullStreamer(Ctx));
304 assert(FileType == OFT_ObjectFile && "Invalid file type!");
305 CE.reset(TheTarget->createCodeEmitter(*TM, Ctx));
306 TAB.reset(TheTarget->createAsmBackend(TripleName));
307 Str.reset(TheTarget->createObjectStreamer(TripleName, Ctx, *TAB,
308 *Out, CE.get(), RelaxAll));
312 Str.reset(createLoggingStreamer(Str.take(), errs()));
315 AsmParser Parser(*TheTarget, SrcMgr, Ctx, *Str.get(), *MAI);
316 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(Parser));
319 << ": error: this target does not support assembly parsing.\n";
323 Parser.setTargetParser(*TAP.get());
325 int Res = Parser.Run(NoInitialTextSection);
328 // Delete output on errors.
329 if (Res && OutputFilename != "-")
330 sys::Path(OutputFilename).eraseFromDisk();
335 static int DisassembleInput(const char *ProgName, bool Enhanced) {
336 const Target *TheTarget = GetTarget(ProgName);
340 std::string ErrorMessage;
342 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
346 errs() << ProgName << ": ";
347 if (ErrorMessage.size())
348 errs() << ErrorMessage << "\n";
350 errs() << "input file didn't read correctly.\n";
355 return Disassembler::disassembleEnhanced(TripleName, *Buffer);
357 return Disassembler::disassemble(*TheTarget, TripleName, *Buffer);
361 int main(int argc, char **argv) {
362 // Print a stack trace if we signal out.
363 sys::PrintStackTraceOnErrorSignal();
364 PrettyStackTraceProgram X(argc, argv);
365 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
367 // Initialize targets and assembly printers/parsers.
368 llvm::InitializeAllTargetInfos();
369 // FIXME: We shouldn't need to initialize the Target(Machine)s.
370 llvm::InitializeAllTargets();
371 llvm::InitializeAllAsmPrinters();
372 llvm::InitializeAllAsmParsers();
373 llvm::InitializeAllDisassemblers();
375 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
380 return AsLexInput(argv[0]);
382 return AssembleInput(argv[0]);
384 return DisassembleInput(argv[0], false);
385 case AC_EDisassemble:
386 return DisassembleInput(argv[0], true);