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/Host.h"
30 #include "llvm/System/Signals.h"
31 #include "llvm/Target/TargetAsmBackend.h"
32 #include "llvm/Target/TargetAsmParser.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetRegistry.h"
35 #include "llvm/Target/TargetMachine.h" // FIXME.
36 #include "llvm/Target/TargetSelect.h"
37 #include "llvm/MC/MCParser/AsmParser.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"));
62 static cl::opt<OutputFileType>
63 FileType("filetype", cl::init(OFT_AssemblyFile),
64 cl::desc("Choose an output file type:"),
66 clEnumValN(OFT_AssemblyFile, "asm",
67 "Emit an assembly ('.s') file"),
68 clEnumValN(OFT_ObjectFile, "obj",
69 "Emit a native object ('.o') file"),
73 Force("f", cl::desc("Enable binary output on terminals"));
75 static cl::list<std::string>
76 IncludeDirs("I", cl::desc("Directory of include files"),
77 cl::value_desc("directory"), cl::Prefix);
79 static cl::opt<std::string>
80 ArchName("arch", cl::desc("Target arch to assemble for, "
81 "see -version for available targets"));
83 static cl::opt<std::string>
84 TripleName("triple", cl::desc("Target triple to assemble for, "
85 "see -version for available targets"));
88 NoInitialTextSection("n", cl::desc(
89 "Don't assume assembly file starts in the text section"));
97 static cl::opt<ActionType>
98 Action(cl::desc("Action to perform:"),
99 cl::init(AC_Assemble),
100 cl::values(clEnumValN(AC_AsLex, "as-lex",
101 "Lex tokens from a .s file"),
102 clEnumValN(AC_Assemble, "assemble",
103 "Assemble a .s file (default)"),
104 clEnumValN(AC_Disassemble, "disassemble",
105 "Disassemble strings of hex bytes"),
108 static const Target *GetTarget(const char *ProgName) {
109 // Figure out the target triple.
110 if (TripleName.empty())
111 TripleName = sys::getHostTriple();
112 if (!ArchName.empty()) {
113 llvm::Triple TT(TripleName);
114 TT.setArchName(ArchName);
115 TripleName = TT.str();
118 // Get the target specific parser.
120 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
124 errs() << ProgName << ": error: unable to get target for '" << TripleName
125 << "', see --version and --triple.\n";
129 static int AsLexInput(const char *ProgName) {
130 std::string ErrorMessage;
131 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
134 errs() << ProgName << ": ";
135 if (ErrorMessage.size())
136 errs() << ErrorMessage << "\n";
138 errs() << "input file didn't read correctly.\n";
144 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
145 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
147 // Record the location of the include directories so that the lexer can find
149 SrcMgr.setIncludeDirs(IncludeDirs);
151 const Target *TheTarget = GetTarget(ProgName);
155 const MCAsmInfo *MAI = TheTarget->createAsmInfo(TripleName);
156 assert(MAI && "Unable to create target asm info!");
158 AsmLexer Lexer(*MAI);
162 while (Lexer.Lex().isNot(AsmToken::Eof)) {
163 switch (Lexer.getKind()) {
165 SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
168 case AsmToken::Error:
169 Error = true; // error already printed.
171 case AsmToken::Identifier:
172 outs() << "identifier: " << Lexer.getTok().getString() << '\n';
174 case AsmToken::String:
175 outs() << "string: " << Lexer.getTok().getString() << '\n';
177 case AsmToken::Integer:
178 outs() << "int: " << Lexer.getTok().getString() << '\n';
181 case AsmToken::Amp: outs() << "Amp\n"; break;
182 case AsmToken::AmpAmp: outs() << "AmpAmp\n"; break;
183 case AsmToken::Caret: outs() << "Caret\n"; break;
184 case AsmToken::Colon: outs() << "Colon\n"; break;
185 case AsmToken::Comma: outs() << "Comma\n"; break;
186 case AsmToken::Dollar: outs() << "Dollar\n"; break;
187 case AsmToken::EndOfStatement: outs() << "EndOfStatement\n"; break;
188 case AsmToken::Eof: outs() << "Eof\n"; break;
189 case AsmToken::Equal: outs() << "Equal\n"; break;
190 case AsmToken::EqualEqual: outs() << "EqualEqual\n"; break;
191 case AsmToken::Exclaim: outs() << "Exclaim\n"; break;
192 case AsmToken::ExclaimEqual: outs() << "ExclaimEqual\n"; break;
193 case AsmToken::Greater: outs() << "Greater\n"; break;
194 case AsmToken::GreaterEqual: outs() << "GreaterEqual\n"; break;
195 case AsmToken::GreaterGreater: outs() << "GreaterGreater\n"; break;
196 case AsmToken::LParen: outs() << "LParen\n"; break;
197 case AsmToken::Less: outs() << "Less\n"; break;
198 case AsmToken::LessEqual: outs() << "LessEqual\n"; break;
199 case AsmToken::LessGreater: outs() << "LessGreater\n"; break;
200 case AsmToken::LessLess: outs() << "LessLess\n"; break;
201 case AsmToken::Minus: outs() << "Minus\n"; break;
202 case AsmToken::Percent: outs() << "Percent\n"; break;
203 case AsmToken::Pipe: outs() << "Pipe\n"; break;
204 case AsmToken::PipePipe: outs() << "PipePipe\n"; break;
205 case AsmToken::Plus: outs() << "Plus\n"; break;
206 case AsmToken::RParen: outs() << "RParen\n"; break;
207 case AsmToken::Slash: outs() << "Slash\n"; break;
208 case AsmToken::Star: outs() << "Star\n"; break;
209 case AsmToken::Tilde: outs() << "Tilde\n"; break;
216 static formatted_raw_ostream *GetOutputStream() {
217 if (OutputFilename == "")
218 OutputFilename = "-";
220 // Make sure that the Out file gets unlinked from the disk if we get a
222 if (OutputFilename != "-")
223 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
226 raw_fd_ostream *Out = new raw_fd_ostream(OutputFilename.c_str(), Err,
227 raw_fd_ostream::F_Binary);
229 errs() << Err << '\n';
234 return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
237 static int AssembleInput(const char *ProgName) {
238 const Target *TheTarget = GetTarget(ProgName);
243 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, &Error);
245 errs() << ProgName << ": ";
247 errs() << Error << "\n";
249 errs() << "input file didn't read correctly.\n";
255 // Tell SrcMgr about this buffer, which is what the parser will pick up.
256 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
258 // Record the location of the include directories so that the lexer can find
260 SrcMgr.setIncludeDirs(IncludeDirs);
263 const MCAsmInfo *MAI = TheTarget->createAsmInfo(TripleName);
264 assert(MAI && "Unable to create target asm info!");
267 formatted_raw_ostream *Out = GetOutputStream();
272 // FIXME: We shouldn't need to do this (and link in codegen).
273 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName, ""));
276 errs() << ProgName << ": error: could not create target for triple '"
277 << TripleName << "'.\n";
281 OwningPtr<MCCodeEmitter> CE;
282 OwningPtr<MCStreamer> Str;
283 OwningPtr<TargetAsmBackend> TAB;
285 if (FileType == OFT_AssemblyFile) {
287 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *Out);
289 CE.reset(TheTarget->createCodeEmitter(*TM, Ctx));
290 Str.reset(createAsmStreamer(Ctx, *Out,TM->getTargetData()->isLittleEndian(),
291 /*asmverbose*/true, IP, CE.get(), ShowInst));
293 assert(FileType == OFT_ObjectFile && "Invalid file type!");
294 CE.reset(TheTarget->createCodeEmitter(*TM, Ctx));
295 TAB.reset(TheTarget->createAsmBackend(TripleName));
296 Str.reset(createMachOStreamer(Ctx, *TAB, *Out, CE.get()));
299 AsmParser Parser(SrcMgr, Ctx, *Str.get(), *MAI);
300 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(Parser));
303 << ": error: this target does not support assembly parsing.\n";
307 Parser.setTargetParser(*TAP.get());
309 int Res = Parser.Run(NoInitialTextSection);
313 // Delete output on errors.
314 if (Res && OutputFilename != "-")
315 sys::Path(OutputFilename).eraseFromDisk();
320 static int DisassembleInput(const char *ProgName) {
321 const Target *TheTarget = GetTarget(ProgName);
325 std::string ErrorMessage;
327 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
331 errs() << ProgName << ": ";
332 if (ErrorMessage.size())
333 errs() << ErrorMessage << "\n";
335 errs() << "input file didn't read correctly.\n";
339 return Disassembler::disassemble(*TheTarget, TripleName, *Buffer);
343 int main(int argc, char **argv) {
344 // Print a stack trace if we signal out.
345 sys::PrintStackTraceOnErrorSignal();
346 PrettyStackTraceProgram X(argc, argv);
347 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
349 // Initialize targets and assembly printers/parsers.
350 llvm::InitializeAllTargetInfos();
351 // FIXME: We shouldn't need to initialize the Target(Machine)s.
352 llvm::InitializeAllTargets();
353 llvm::InitializeAllAsmPrinters();
354 llvm::InitializeAllAsmParsers();
355 llvm::InitializeAllDisassemblers();
357 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
362 return AsLexInput(argv[0]);
364 return AssembleInput(argv[0]);
366 return DisassembleInput(argv[0]);