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/ADT/OwningPtr.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/FormattedStream.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/PrettyStackTrace.h"
27 #include "llvm/Support/SourceMgr.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/System/Signals.h"
30 #include "llvm/Target/TargetAsmBackend.h"
31 #include "llvm/Target/TargetAsmParser.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Target/TargetRegistry.h"
34 #include "llvm/Target/TargetMachine.h" // FIXME.
35 #include "llvm/Target/TargetSelect.h"
36 #include "llvm/MC/MCParser/AsmParser.h"
37 #include "Disassembler.h"
40 static cl::opt<std::string>
41 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
43 static cl::opt<std::string>
44 OutputFilename("o", cl::desc("Output filename"),
45 cl::value_desc("filename"));
48 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
51 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
53 static cl::opt<unsigned>
54 OutputAsmVariant("output-asm-variant",
55 cl::desc("Syntax variant to use for output printing"));
61 static cl::opt<OutputFileType>
62 FileType("filetype", cl::init(OFT_AssemblyFile),
63 cl::desc("Choose an output file type:"),
65 clEnumValN(OFT_AssemblyFile, "asm",
66 "Emit an assembly ('.s') file"),
67 clEnumValN(OFT_ObjectFile, "obj",
68 "Emit a native object ('.o') file"),
72 Force("f", cl::desc("Enable binary output on terminals"));
74 static cl::list<std::string>
75 IncludeDirs("I", cl::desc("Directory of include files"),
76 cl::value_desc("directory"), cl::Prefix);
78 static cl::opt<std::string>
79 TripleName("triple", cl::desc("Target triple to assemble for, "
80 "see -version for available targets"),
81 cl::init(LLVM_HOSTTRIPLE));
89 static cl::opt<ActionType>
90 Action(cl::desc("Action to perform:"),
91 cl::init(AC_Assemble),
92 cl::values(clEnumValN(AC_AsLex, "as-lex",
93 "Lex tokens from a .s file"),
94 clEnumValN(AC_Assemble, "assemble",
95 "Assemble a .s file (default)"),
96 clEnumValN(AC_Disassemble, "disassemble",
97 "Disassemble strings of hex bytes"),
100 static const Target *GetTarget(const char *ProgName) {
101 // Get the target specific parser.
103 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
107 errs() << ProgName << ": error: unable to get target for '" << TripleName
108 << "', see --version and --triple.\n";
112 static int AsLexInput(const char *ProgName) {
113 std::string ErrorMessage;
114 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
117 errs() << ProgName << ": ";
118 if (ErrorMessage.size())
119 errs() << ErrorMessage << "\n";
121 errs() << "input file didn't read correctly.\n";
127 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
128 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
130 // Record the location of the include directories so that the lexer can find
132 SrcMgr.setIncludeDirs(IncludeDirs);
134 const Target *TheTarget = GetTarget(ProgName);
138 const MCAsmInfo *MAI = TheTarget->createAsmInfo(TripleName);
139 assert(MAI && "Unable to create target asm info!");
141 AsmLexer Lexer(*MAI);
145 while (Lexer.Lex().isNot(AsmToken::Eof)) {
146 switch (Lexer.getKind()) {
148 SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
151 case AsmToken::Error:
152 Error = true; // error already printed.
154 case AsmToken::Identifier:
155 outs() << "identifier: " << Lexer.getTok().getString() << '\n';
157 case AsmToken::String:
158 outs() << "string: " << Lexer.getTok().getString() << '\n';
160 case AsmToken::Integer:
161 outs() << "int: " << Lexer.getTok().getString() << '\n';
164 case AsmToken::Amp: outs() << "Amp\n"; break;
165 case AsmToken::AmpAmp: outs() << "AmpAmp\n"; break;
166 case AsmToken::Caret: outs() << "Caret\n"; break;
167 case AsmToken::Colon: outs() << "Colon\n"; break;
168 case AsmToken::Comma: outs() << "Comma\n"; break;
169 case AsmToken::Dollar: outs() << "Dollar\n"; break;
170 case AsmToken::EndOfStatement: outs() << "EndOfStatement\n"; break;
171 case AsmToken::Eof: outs() << "Eof\n"; break;
172 case AsmToken::Equal: outs() << "Equal\n"; break;
173 case AsmToken::EqualEqual: outs() << "EqualEqual\n"; break;
174 case AsmToken::Exclaim: outs() << "Exclaim\n"; break;
175 case AsmToken::ExclaimEqual: outs() << "ExclaimEqual\n"; break;
176 case AsmToken::Greater: outs() << "Greater\n"; break;
177 case AsmToken::GreaterEqual: outs() << "GreaterEqual\n"; break;
178 case AsmToken::GreaterGreater: outs() << "GreaterGreater\n"; break;
179 case AsmToken::LParen: outs() << "LParen\n"; break;
180 case AsmToken::Less: outs() << "Less\n"; break;
181 case AsmToken::LessEqual: outs() << "LessEqual\n"; break;
182 case AsmToken::LessGreater: outs() << "LessGreater\n"; break;
183 case AsmToken::LessLess: outs() << "LessLess\n"; break;
184 case AsmToken::Minus: outs() << "Minus\n"; break;
185 case AsmToken::Percent: outs() << "Percent\n"; break;
186 case AsmToken::Pipe: outs() << "Pipe\n"; break;
187 case AsmToken::PipePipe: outs() << "PipePipe\n"; break;
188 case AsmToken::Plus: outs() << "Plus\n"; break;
189 case AsmToken::RParen: outs() << "RParen\n"; break;
190 case AsmToken::Slash: outs() << "Slash\n"; break;
191 case AsmToken::Star: outs() << "Star\n"; break;
192 case AsmToken::Tilde: outs() << "Tilde\n"; break;
199 static formatted_raw_ostream *GetOutputStream() {
200 if (OutputFilename == "")
201 OutputFilename = "-";
203 // Make sure that the Out file gets unlinked from the disk if we get a
205 if (OutputFilename != "-")
206 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
209 raw_fd_ostream *Out = new raw_fd_ostream(OutputFilename.c_str(), Err,
210 raw_fd_ostream::F_Binary);
212 errs() << Err << '\n';
217 return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
220 static int AssembleInput(const char *ProgName) {
221 const Target *TheTarget = GetTarget(ProgName);
226 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, &Error);
228 errs() << ProgName << ": ";
230 errs() << Error << "\n";
232 errs() << "input file didn't read correctly.\n";
238 // Tell SrcMgr about this buffer, which is what the parser will pick up.
239 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
241 // Record the location of the include directories so that the lexer can find
243 SrcMgr.setIncludeDirs(IncludeDirs);
246 formatted_raw_ostream *Out = GetOutputStream();
251 // FIXME: We shouldn't need to do this (and link in codegen).
252 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName, ""));
255 errs() << ProgName << ": error: could not create target for triple '"
256 << TripleName << "'.\n";
260 OwningPtr<MCInstPrinter> IP;
261 OwningPtr<MCCodeEmitter> CE;
262 OwningPtr<MCStreamer> Str;
263 OwningPtr<TargetAsmBackend> TAB;
265 const MCAsmInfo *MAI = TheTarget->createAsmInfo(TripleName);
266 assert(MAI && "Unable to create target asm info!");
268 if (FileType == OFT_AssemblyFile) {
269 IP.reset(TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *Out));
271 CE.reset(TheTarget->createCodeEmitter(*TM, Ctx));
272 Str.reset(createAsmStreamer(Ctx, *Out, *MAI,
273 TM->getTargetData()->isLittleEndian(),
274 /*asmverbose*/true, IP.get(), CE.get(),
277 assert(FileType == OFT_ObjectFile && "Invalid file type!");
278 CE.reset(TheTarget->createCodeEmitter(*TM, Ctx));
279 TAB.reset(TheTarget->createAsmBackend(TripleName));
280 Str.reset(createMachOStreamer(Ctx, *TAB, *Out, CE.get()));
283 AsmParser Parser(SrcMgr, Ctx, *Str.get(), *MAI);
284 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(Parser));
287 << ": error: this target does not support assembly parsing.\n";
291 Parser.setTargetParser(*TAP.get());
293 int Res = Parser.Run();
300 static int DisassembleInput(const char *ProgName) {
302 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
303 if (TheTarget == 0) {
304 errs() << ProgName << ": error: unable to get target for '" << TripleName
305 << "', see --version and --triple.\n";
309 std::string ErrorMessage;
311 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
315 errs() << ProgName << ": ";
316 if (ErrorMessage.size())
317 errs() << ErrorMessage << "\n";
319 errs() << "input file didn't read correctly.\n";
323 return Disassembler::disassemble(*TheTarget, TripleName, *Buffer);
327 int main(int argc, char **argv) {
328 // Print a stack trace if we signal out.
329 sys::PrintStackTraceOnErrorSignal();
330 PrettyStackTraceProgram X(argc, argv);
331 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
333 // Initialize targets and assembly printers/parsers.
334 llvm::InitializeAllTargetInfos();
335 // FIXME: We shouldn't need to initialize the Target(Machine)s.
336 llvm::InitializeAllTargets();
337 llvm::InitializeAllAsmPrinters();
338 llvm::InitializeAllAsmParsers();
339 llvm::InitializeAllDisassemblers();
341 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
346 return AsLexInput(argv[0]);
348 return AssembleInput(argv[0]);
350 return DisassembleInput(argv[0]);