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"));
66 static cl::opt<OutputFileType>
67 FileType("filetype", cl::init(OFT_AssemblyFile),
68 cl::desc("Choose an output file type:"),
70 clEnumValN(OFT_AssemblyFile, "asm",
71 "Emit an assembly ('.s') file"),
72 clEnumValN(OFT_Null, "null",
73 "Don't emit anything (for timing purposes)"),
74 clEnumValN(OFT_ObjectFile, "obj",
75 "Emit a native object ('.o') file"),
78 static cl::list<std::string>
79 IncludeDirs("I", cl::desc("Directory of include files"),
80 cl::value_desc("directory"), cl::Prefix);
82 static cl::opt<std::string>
83 ArchName("arch", cl::desc("Target arch to assemble for, "
84 "see -version for available targets"));
86 static cl::opt<std::string>
87 TripleName("triple", cl::desc("Target triple to assemble for, "
88 "see -version for available targets"));
91 NoInitialTextSection("n", cl::desc(
92 "Don't assume assembly file starts in the text section"));
101 static cl::opt<ActionType>
102 Action(cl::desc("Action to perform:"),
103 cl::init(AC_Assemble),
104 cl::values(clEnumValN(AC_AsLex, "as-lex",
105 "Lex tokens from a .s file"),
106 clEnumValN(AC_Assemble, "assemble",
107 "Assemble a .s file (default)"),
108 clEnumValN(AC_Disassemble, "disassemble",
109 "Disassemble strings of hex bytes"),
110 clEnumValN(AC_EDisassemble, "edis",
111 "Enhanced disassembly of strings of hex bytes"),
114 static const Target *GetTarget(const char *ProgName) {
115 // Figure out the target triple.
116 if (TripleName.empty())
117 TripleName = sys::getHostTriple();
118 if (!ArchName.empty()) {
119 llvm::Triple TT(TripleName);
120 TT.setArchName(ArchName);
121 TripleName = TT.str();
124 // Get the target specific parser.
126 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
130 errs() << ProgName << ": error: unable to get target for '" << TripleName
131 << "', see --version and --triple.\n";
135 static int AsLexInput(const char *ProgName) {
136 std::string ErrorMessage;
137 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
140 errs() << ProgName << ": ";
141 if (ErrorMessage.size())
142 errs() << ErrorMessage << "\n";
144 errs() << "input file didn't read correctly.\n";
150 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
151 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
153 // Record the location of the include directories so that the lexer can find
155 SrcMgr.setIncludeDirs(IncludeDirs);
157 const Target *TheTarget = GetTarget(ProgName);
161 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(TripleName));
162 assert(MAI && "Unable to create target asm info!");
164 AsmLexer Lexer(*MAI);
168 while (Lexer.Lex().isNot(AsmToken::Eof)) {
169 switch (Lexer.getKind()) {
171 SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
174 case AsmToken::Error:
175 Error = true; // error already printed.
177 case AsmToken::Identifier:
178 outs() << "identifier: " << Lexer.getTok().getString() << '\n';
180 case AsmToken::String:
181 outs() << "string: " << Lexer.getTok().getString() << '\n';
183 case AsmToken::Integer:
184 outs() << "int: " << Lexer.getTok().getString() << '\n';
187 case AsmToken::Amp: outs() << "Amp\n"; break;
188 case AsmToken::AmpAmp: outs() << "AmpAmp\n"; break;
189 case AsmToken::Caret: outs() << "Caret\n"; break;
190 case AsmToken::Colon: outs() << "Colon\n"; break;
191 case AsmToken::Comma: outs() << "Comma\n"; break;
192 case AsmToken::Dollar: outs() << "Dollar\n"; break;
193 case AsmToken::EndOfStatement: outs() << "EndOfStatement\n"; break;
194 case AsmToken::Eof: outs() << "Eof\n"; break;
195 case AsmToken::Equal: outs() << "Equal\n"; break;
196 case AsmToken::EqualEqual: outs() << "EqualEqual\n"; break;
197 case AsmToken::Exclaim: outs() << "Exclaim\n"; break;
198 case AsmToken::ExclaimEqual: outs() << "ExclaimEqual\n"; break;
199 case AsmToken::Greater: outs() << "Greater\n"; break;
200 case AsmToken::GreaterEqual: outs() << "GreaterEqual\n"; break;
201 case AsmToken::GreaterGreater: outs() << "GreaterGreater\n"; break;
202 case AsmToken::LParen: outs() << "LParen\n"; break;
203 case AsmToken::Less: outs() << "Less\n"; break;
204 case AsmToken::LessEqual: outs() << "LessEqual\n"; break;
205 case AsmToken::LessGreater: outs() << "LessGreater\n"; break;
206 case AsmToken::LessLess: outs() << "LessLess\n"; break;
207 case AsmToken::Minus: outs() << "Minus\n"; break;
208 case AsmToken::Percent: outs() << "Percent\n"; break;
209 case AsmToken::Pipe: outs() << "Pipe\n"; break;
210 case AsmToken::PipePipe: outs() << "PipePipe\n"; break;
211 case AsmToken::Plus: outs() << "Plus\n"; break;
212 case AsmToken::RParen: outs() << "RParen\n"; break;
213 case AsmToken::Slash: outs() << "Slash\n"; break;
214 case AsmToken::Star: outs() << "Star\n"; break;
215 case AsmToken::Tilde: outs() << "Tilde\n"; break;
222 static formatted_raw_ostream *GetOutputStream() {
223 if (OutputFilename == "")
224 OutputFilename = "-";
226 // Make sure that the Out file gets unlinked from the disk if we get a
228 if (OutputFilename != "-")
229 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
232 raw_fd_ostream *Out = new raw_fd_ostream(OutputFilename.c_str(), Err,
233 raw_fd_ostream::F_Binary);
235 errs() << Err << '\n';
240 return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
243 static int AssembleInput(const char *ProgName) {
244 const Target *TheTarget = GetTarget(ProgName);
249 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, &Error);
251 errs() << ProgName << ": ";
253 errs() << Error << "\n";
255 errs() << "input file didn't read correctly.\n";
261 // Tell SrcMgr about this buffer, which is what the parser will pick up.
262 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
264 // Record the location of the include directories so that the lexer can find
266 SrcMgr.setIncludeDirs(IncludeDirs);
269 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(TripleName));
270 assert(MAI && "Unable to create target asm info!");
273 formatted_raw_ostream *Out = GetOutputStream();
278 // FIXME: We shouldn't need to do this (and link in codegen).
279 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName, ""));
282 errs() << ProgName << ": error: could not create target for triple '"
283 << TripleName << "'.\n";
287 OwningPtr<MCCodeEmitter> CE;
288 OwningPtr<MCStreamer> Str;
289 OwningPtr<TargetAsmBackend> TAB;
291 if (FileType == OFT_AssemblyFile) {
293 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI);
295 CE.reset(TheTarget->createCodeEmitter(*TM, Ctx));
296 Str.reset(createAsmStreamer(Ctx, *Out,TM->getTargetData()->isLittleEndian(),
297 /*asmverbose*/true, IP, CE.get(), ShowInst));
298 } else if (FileType == OFT_Null) {
299 Str.reset(createNullStreamer(Ctx));
301 assert(FileType == OFT_ObjectFile && "Invalid file type!");
302 CE.reset(TheTarget->createCodeEmitter(*TM, Ctx));
303 TAB.reset(TheTarget->createAsmBackend(TripleName));
304 Str.reset(createMachOStreamer(Ctx, *TAB, *Out, CE.get(), RelaxAll));
307 AsmParser Parser(SrcMgr, Ctx, *Str.get(), *MAI);
308 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(Parser));
311 << ": error: this target does not support assembly parsing.\n";
315 Parser.setTargetParser(*TAP.get());
317 int Res = Parser.Run(NoInitialTextSection);
321 // Delete output on errors.
322 if (Res && OutputFilename != "-")
323 sys::Path(OutputFilename).eraseFromDisk();
328 static int DisassembleInput(const char *ProgName, bool Enhanced) {
329 const Target *TheTarget = GetTarget(ProgName);
333 std::string ErrorMessage;
335 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
339 errs() << ProgName << ": ";
340 if (ErrorMessage.size())
341 errs() << ErrorMessage << "\n";
343 errs() << "input file didn't read correctly.\n";
348 return Disassembler::disassembleEnhanced(TripleName, *Buffer);
350 return Disassembler::disassemble(*TheTarget, TripleName, *Buffer);
354 int main(int argc, char **argv) {
355 // Print a stack trace if we signal out.
356 sys::PrintStackTraceOnErrorSignal();
357 PrettyStackTraceProgram X(argc, argv);
358 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
360 // Initialize targets and assembly printers/parsers.
361 llvm::InitializeAllTargetInfos();
362 // FIXME: We shouldn't need to initialize the Target(Machine)s.
363 llvm::InitializeAllTargets();
364 llvm::InitializeAllAsmPrinters();
365 llvm::InitializeAllAsmParsers();
366 llvm::InitializeAllDisassemblers();
368 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
373 return AsLexInput(argv[0]);
375 return AssembleInput(argv[0]);
377 return DisassembleInput(argv[0], false);
378 case AC_EDisassemble:
379 return DisassembleInput(argv[0], true);