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/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/TargetAsmParser.h"
31 #include "llvm/Target/TargetRegistry.h"
32 #include "llvm/Target/TargetMachine.h" // FIXME.
33 #include "llvm/Target/TargetSelect.h"
34 #include "AsmParser.h"
35 #include "HexDisassembler.h"
38 static cl::opt<std::string>
39 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
41 static cl::opt<std::string>
42 OutputFilename("o", cl::desc("Output filename"),
43 cl::value_desc("filename"));
46 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
48 static cl::opt<unsigned>
49 OutputAsmVariant("output-asm-variant",
50 cl::desc("Syntax variant to use for output printing"));
56 static cl::opt<OutputFileType>
57 FileType("filetype", cl::init(OFT_AssemblyFile),
58 cl::desc("Choose an output file type:"),
60 clEnumValN(OFT_AssemblyFile, "asm",
61 "Emit an assembly ('.s') file"),
62 clEnumValN(OFT_ObjectFile, "obj",
63 "Emit a native object ('.o') file"),
67 Force("f", cl::desc("Enable binary output on terminals"));
69 static cl::list<std::string>
70 IncludeDirs("I", cl::desc("Directory of include files"),
71 cl::value_desc("directory"), cl::Prefix);
73 static cl::opt<std::string>
74 TripleName("triple", cl::desc("Target triple to assemble for, "
75 "see -version for available targets"),
76 cl::init(LLVM_HOSTTRIPLE));
84 static cl::opt<ActionType>
85 Action(cl::desc("Action to perform:"),
86 cl::init(AC_Assemble),
87 cl::values(clEnumValN(AC_AsLex, "as-lex",
88 "Lex tokens from a .s file"),
89 clEnumValN(AC_Assemble, "assemble",
90 "Assemble a .s file (default)"),
91 clEnumValN(AC_Disassemble, "disassemble",
92 "Disassemble strings of hex bytes"),
95 static const Target *GetTarget(const char *ProgName) {
96 // Get the target specific parser.
98 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
102 errs() << ProgName << ": error: unable to get target for '" << TripleName
103 << "', see --version and --triple.\n";
107 static int AsLexInput(const char *ProgName) {
108 std::string ErrorMessage;
109 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
112 errs() << ProgName << ": ";
113 if (ErrorMessage.size())
114 errs() << ErrorMessage << "\n";
116 errs() << "input file didn't read correctly.\n";
122 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
123 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
125 // Record the location of the include directories so that the lexer can find
127 SrcMgr.setIncludeDirs(IncludeDirs);
129 const Target *TheTarget = GetTarget(ProgName);
133 const MCAsmInfo *MAI = TheTarget->createAsmInfo(TripleName);
134 assert(MAI && "Unable to create target asm info!");
136 AsmLexer Lexer(SrcMgr, *MAI);
140 while (Lexer.Lex().isNot(AsmToken::Eof)) {
141 switch (Lexer.getKind()) {
143 Lexer.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
146 case AsmToken::Error:
147 Error = true; // error already printed.
149 case AsmToken::Identifier:
150 outs() << "identifier: " << Lexer.getTok().getString() << '\n';
152 case AsmToken::String:
153 outs() << "string: " << Lexer.getTok().getString() << '\n';
155 case AsmToken::Integer:
156 outs() << "int: " << Lexer.getTok().getString() << '\n';
159 case AsmToken::Amp: outs() << "Amp\n"; break;
160 case AsmToken::AmpAmp: outs() << "AmpAmp\n"; break;
161 case AsmToken::Caret: outs() << "Caret\n"; break;
162 case AsmToken::Colon: outs() << "Colon\n"; break;
163 case AsmToken::Comma: outs() << "Comma\n"; break;
164 case AsmToken::Dollar: outs() << "Dollar\n"; break;
165 case AsmToken::EndOfStatement: outs() << "EndOfStatement\n"; break;
166 case AsmToken::Eof: outs() << "Eof\n"; break;
167 case AsmToken::Equal: outs() << "Equal\n"; break;
168 case AsmToken::EqualEqual: outs() << "EqualEqual\n"; break;
169 case AsmToken::Exclaim: outs() << "Exclaim\n"; break;
170 case AsmToken::ExclaimEqual: outs() << "ExclaimEqual\n"; break;
171 case AsmToken::Greater: outs() << "Greater\n"; break;
172 case AsmToken::GreaterEqual: outs() << "GreaterEqual\n"; break;
173 case AsmToken::GreaterGreater: outs() << "GreaterGreater\n"; break;
174 case AsmToken::LParen: outs() << "LParen\n"; break;
175 case AsmToken::Less: outs() << "Less\n"; break;
176 case AsmToken::LessEqual: outs() << "LessEqual\n"; break;
177 case AsmToken::LessGreater: outs() << "LessGreater\n"; break;
178 case AsmToken::LessLess: outs() << "LessLess\n"; break;
179 case AsmToken::Minus: outs() << "Minus\n"; break;
180 case AsmToken::Percent: outs() << "Percent\n"; break;
181 case AsmToken::Pipe: outs() << "Pipe\n"; break;
182 case AsmToken::PipePipe: outs() << "PipePipe\n"; break;
183 case AsmToken::Plus: outs() << "Plus\n"; break;
184 case AsmToken::RParen: outs() << "RParen\n"; break;
185 case AsmToken::Slash: outs() << "Slash\n"; break;
186 case AsmToken::Star: outs() << "Star\n"; break;
187 case AsmToken::Tilde: outs() << "Tilde\n"; break;
194 static formatted_raw_ostream *GetOutputStream() {
195 if (OutputFilename == "")
196 OutputFilename = "-";
198 // Make sure that the Out file gets unlinked from the disk if we get a
200 if (OutputFilename != "-")
201 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
204 raw_fd_ostream *Out = new raw_fd_ostream(OutputFilename.c_str(), Err,
205 raw_fd_ostream::F_Binary);
207 errs() << Err << '\n';
212 return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
215 static int AssembleInput(const char *ProgName) {
216 const Target *TheTarget = GetTarget(ProgName);
221 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, &Error);
223 errs() << ProgName << ": ";
225 errs() << Error << "\n";
227 errs() << "input file didn't read correctly.\n";
233 // Tell SrcMgr about this buffer, which is what the parser will pick up.
234 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
236 // Record the location of the include directories so that the lexer can find
238 SrcMgr.setIncludeDirs(IncludeDirs);
241 formatted_raw_ostream *Out = GetOutputStream();
246 // FIXME: We shouldn't need to do this (and link in codegen).
247 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName, ""));
250 errs() << ProgName << ": error: could not create target for triple '"
251 << TripleName << "'.\n";
255 OwningPtr<MCInstPrinter> IP;
256 OwningPtr<MCCodeEmitter> CE;
257 OwningPtr<MCStreamer> Str;
259 const MCAsmInfo *MAI = TheTarget->createAsmInfo(TripleName);
260 assert(MAI && "Unable to create target asm info!");
262 if (FileType == OFT_AssemblyFile) {
263 IP.reset(TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *Out));
265 CE.reset(TheTarget->createCodeEmitter(*TM));
266 Str.reset(createAsmStreamer(Ctx, *Out, *MAI, IP.get(), CE.get()));
268 assert(FileType == OFT_ObjectFile && "Invalid file type!");
269 CE.reset(TheTarget->createCodeEmitter(*TM));
270 Str.reset(createMachOStreamer(Ctx, *Out, CE.get()));
273 AsmParser Parser(SrcMgr, Ctx, *Str.get(), *MAI);
274 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(Parser));
277 << ": error: this target does not support assembly parsing.\n";
281 Parser.setTargetParser(*TAP.get());
283 int Res = Parser.Run();
290 static int DisassembleInput(const char *ProgName) {
292 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
293 if (TheTarget == 0) {
294 errs() << ProgName << ": error: unable to get target for '" << TripleName
295 << "', see --version and --triple.\n";
299 std::string ErrorMessage;
301 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
305 errs() << ProgName << ": ";
306 if (ErrorMessage.size())
307 errs() << ErrorMessage << "\n";
309 errs() << "input file didn't read correctly.\n";
313 return HexDisassembler::disassemble(*TheTarget, TripleName, *Buffer);
317 int main(int argc, char **argv) {
318 // Print a stack trace if we signal out.
319 sys::PrintStackTraceOnErrorSignal();
320 PrettyStackTraceProgram X(argc, argv);
321 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
323 // Initialize targets and assembly printers/parsers.
324 llvm::InitializeAllTargetInfos();
325 // FIXME: We shouldn't need to initialize the Target(Machine)s.
326 llvm::InitializeAllTargets();
327 llvm::InitializeAllAsmPrinters();
328 llvm::InitializeAllAsmParsers();
329 llvm::InitializeAllDisassemblers();
331 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
336 return AsLexInput(argv[0]);
338 return AssembleInput(argv[0]);
340 return DisassembleInput(argv[0]);