1 //===-- llvm-mc.cpp - Machine Code Hacking Driver -------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This utility is a simple driver that allows command line hacking on machine
11 // code.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/MC/MCParser/AsmLexer.h"
16 #include "llvm/MC/MCParser/MCAsmLexer.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCCodeEmitter.h"
19 #include "llvm/MC/MCInstPrinter.h"
20 #include "llvm/MC/MCInstrInfo.h"
21 #include "llvm/MC/MCObjectFileInfo.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCSectionMachO.h"
24 #include "llvm/MC/MCStreamer.h"
25 #include "llvm/MC/MCSubtargetInfo.h"
26 #include "llvm/MC/SubtargetFeature.h"
27 #include "llvm/Target/TargetAsmBackend.h"
28 #include "llvm/Target/TargetAsmParser.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetRegistry.h"
31 #include "llvm/Target/TargetAsmInfo.h" // FIXME.
32 #include "llvm/Target/TargetLowering.h" // FIXME.
33 #include "llvm/Target/TargetLoweringObjectFile.h" // FIXME.
34 #include "llvm/Target/TargetMachine.h" // FIXME.
35 #include "llvm/Target/TargetSelect.h"
36 #include "llvm/ADT/OwningPtr.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/FileUtilities.h"
39 #include "llvm/Support/FormattedStream.h"
40 #include "llvm/Support/ManagedStatic.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/Support/PrettyStackTrace.h"
43 #include "llvm/Support/SourceMgr.h"
44 #include "llvm/Support/ToolOutputFile.h"
45 #include "llvm/Support/Host.h"
46 #include "llvm/Support/Signals.h"
47 #include "llvm/Support/system_error.h"
48 #include "Disassembler.h"
49 using namespace llvm;
50
51 static cl::opt<std::string>
52 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
53
54 static cl::opt<std::string>
55 OutputFilename("o", cl::desc("Output filename"),
56 cl::value_desc("filename"));
57
58 static cl::opt<bool>
59 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
60
61 static cl::opt<bool>
62 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
63
64 static cl::opt<bool>
65 ShowInstOperands("show-inst-operands",
66 cl::desc("Show instructions operands as parsed"));
67
68 static cl::opt<unsigned>
69 OutputAsmVariant("output-asm-variant",
70 cl::desc("Syntax variant to use for output printing"));
71
72 static cl::opt<bool>
73 RelaxAll("mc-relax-all", cl::desc("Relax all fixups"));
74
75 static cl::opt<bool>
76 NoExecStack("mc-no-exec-stack", cl::desc("File doesn't need an exec stack"));
77
78 static cl::opt<bool>
79 EnableLogging("enable-api-logging", cl::desc("Enable MC API logging"));
80
81 enum OutputFileType {
82 OFT_Null,
83 OFT_AssemblyFile,
84 OFT_ObjectFile
85 };
86 static cl::opt<OutputFileType>
87 FileType("filetype", cl::init(OFT_AssemblyFile),
88 cl::desc("Choose an output file type:"),
89 cl::values(
90 clEnumValN(OFT_AssemblyFile, "asm",
91 "Emit an assembly ('.s') file"),
92 clEnumValN(OFT_Null, "null",
93 "Don't emit anything (for timing purposes)"),
94 clEnumValN(OFT_ObjectFile, "obj",
95 "Emit a native object ('.o') file"),
96 clEnumValEnd));
97
98 static cl::list<std::string>
99 IncludeDirs("I", cl::desc("Directory of include files"),
100 cl::value_desc("directory"), cl::Prefix);
101
102 static cl::opt<std::string>
103 ArchName("arch", cl::desc("Target arch to assemble for, "
104 "see -version for available targets"));
105
106 static cl::opt<std::string>
107 TripleName("triple", cl::desc("Target triple to assemble for, "
108 "see -version for available targets"));
109
110 static cl::opt<std::string>
111 MCPU("mcpu",
112 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
113 cl::value_desc("cpu-name"),
114 cl::init(""));
115
116 static cl::opt<Reloc::Model>
117 RelocModel("relocation-model",
118 cl::desc("Choose relocation model"),
119 cl::init(Reloc::Default),
120 cl::values(
121 clEnumValN(Reloc::Default, "default",
122 "Target default relocation model"),
123 clEnumValN(Reloc::Static, "static",
124 "Non-relocatable code"),
125 clEnumValN(Reloc::PIC_, "pic",
126 "Fully relocatable, position independent code"),
127 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
128 "Relocatable external references, non-relocatable code"),
129 clEnumValEnd));
130
131 static cl::opt<bool>
132 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
133 "in the text section"));
134
135 static cl::opt<bool>
136 SaveTempLabels("L", cl::desc("Don't discard temporary labels"));
137
138 enum ActionType {
139 AC_AsLex,
140 AC_Assemble,
141 AC_Disassemble,
142 AC_EDisassemble
143 };
144
145 static cl::opt<ActionType>
146 Action(cl::desc("Action to perform:"),
147 cl::init(AC_Assemble),
148 cl::values(clEnumValN(AC_AsLex, "as-lex",
149 "Lex tokens from a .s file"),
150 clEnumValN(AC_Assemble, "assemble",
151 "Assemble a .s file (default)"),
152 clEnumValN(AC_Disassemble, "disassemble",
153 "Disassemble strings of hex bytes"),
154 clEnumValN(AC_EDisassemble, "edis",
155 "Enhanced disassembly of strings of hex bytes"),
156 clEnumValEnd));
157
GetTarget(const char * ProgName)158 static const Target *GetTarget(const char *ProgName) {
159 // Figure out the target triple.
160 if (TripleName.empty())
161 TripleName = sys::getHostTriple();
162 if (!ArchName.empty()) {
163 llvm::Triple TT(TripleName);
164 TT.setArchName(ArchName);
165 TripleName = TT.str();
166 }
167
168 // Get the target specific parser.
169 std::string Error;
170 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
171 if (TheTarget)
172 return TheTarget;
173
174 errs() << ProgName << ": error: unable to get target for '" << TripleName
175 << "', see --version and --triple.\n";
176 return 0;
177 }
178
GetOutputStream()179 static tool_output_file *GetOutputStream() {
180 if (OutputFilename == "")
181 OutputFilename = "-";
182
183 std::string Err;
184 tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
185 raw_fd_ostream::F_Binary);
186 if (!Err.empty()) {
187 errs() << Err << '\n';
188 delete Out;
189 return 0;
190 }
191
192 return Out;
193 }
194
AsLexInput(const char * ProgName)195 static int AsLexInput(const char *ProgName) {
196 OwningPtr<MemoryBuffer> BufferPtr;
197 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
198 errs() << ProgName << ": " << ec.message() << '\n';
199 return 1;
200 }
201 MemoryBuffer *Buffer = BufferPtr.take();
202
203 SourceMgr SrcMgr;
204
205 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
206 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
207
208 // Record the location of the include directories so that the lexer can find
209 // it later.
210 SrcMgr.setIncludeDirs(IncludeDirs);
211
212 const Target *TheTarget = GetTarget(ProgName);
213 if (!TheTarget)
214 return 1;
215
216 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
217 assert(MAI && "Unable to create target asm info!");
218
219 AsmLexer Lexer(*MAI);
220 Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
221
222 OwningPtr<tool_output_file> Out(GetOutputStream());
223 if (!Out)
224 return 1;
225
226 bool Error = false;
227 while (Lexer.Lex().isNot(AsmToken::Eof)) {
228 AsmToken Tok = Lexer.getTok();
229
230 switch (Tok.getKind()) {
231 default:
232 SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
233 Error = true;
234 break;
235 case AsmToken::Error:
236 Error = true; // error already printed.
237 break;
238 case AsmToken::Identifier:
239 Out->os() << "identifier: " << Lexer.getTok().getString();
240 break;
241 case AsmToken::Integer:
242 Out->os() << "int: " << Lexer.getTok().getString();
243 break;
244 case AsmToken::Real:
245 Out->os() << "real: " << Lexer.getTok().getString();
246 break;
247 case AsmToken::Register:
248 Out->os() << "register: " << Lexer.getTok().getRegVal();
249 break;
250 case AsmToken::String:
251 Out->os() << "string: " << Lexer.getTok().getString();
252 break;
253
254 case AsmToken::Amp: Out->os() << "Amp"; break;
255 case AsmToken::AmpAmp: Out->os() << "AmpAmp"; break;
256 case AsmToken::At: Out->os() << "At"; break;
257 case AsmToken::Caret: Out->os() << "Caret"; break;
258 case AsmToken::Colon: Out->os() << "Colon"; break;
259 case AsmToken::Comma: Out->os() << "Comma"; break;
260 case AsmToken::Dollar: Out->os() << "Dollar"; break;
261 case AsmToken::Dot: Out->os() << "Dot"; break;
262 case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
263 case AsmToken::Eof: Out->os() << "Eof"; break;
264 case AsmToken::Equal: Out->os() << "Equal"; break;
265 case AsmToken::EqualEqual: Out->os() << "EqualEqual"; break;
266 case AsmToken::Exclaim: Out->os() << "Exclaim"; break;
267 case AsmToken::ExclaimEqual: Out->os() << "ExclaimEqual"; break;
268 case AsmToken::Greater: Out->os() << "Greater"; break;
269 case AsmToken::GreaterEqual: Out->os() << "GreaterEqual"; break;
270 case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
271 case AsmToken::Hash: Out->os() << "Hash"; break;
272 case AsmToken::LBrac: Out->os() << "LBrac"; break;
273 case AsmToken::LCurly: Out->os() << "LCurly"; break;
274 case AsmToken::LParen: Out->os() << "LParen"; break;
275 case AsmToken::Less: Out->os() << "Less"; break;
276 case AsmToken::LessEqual: Out->os() << "LessEqual"; break;
277 case AsmToken::LessGreater: Out->os() << "LessGreater"; break;
278 case AsmToken::LessLess: Out->os() << "LessLess"; break;
279 case AsmToken::Minus: Out->os() << "Minus"; break;
280 case AsmToken::Percent: Out->os() << "Percent"; break;
281 case AsmToken::Pipe: Out->os() << "Pipe"; break;
282 case AsmToken::PipePipe: Out->os() << "PipePipe"; break;
283 case AsmToken::Plus: Out->os() << "Plus"; break;
284 case AsmToken::RBrac: Out->os() << "RBrac"; break;
285 case AsmToken::RCurly: Out->os() << "RCurly"; break;
286 case AsmToken::RParen: Out->os() << "RParen"; break;
287 case AsmToken::Slash: Out->os() << "Slash"; break;
288 case AsmToken::Star: Out->os() << "Star"; break;
289 case AsmToken::Tilde: Out->os() << "Tilde"; break;
290 }
291
292 // Print the token string.
293 Out->os() << " (\"";
294 Out->os().write_escaped(Tok.getString());
295 Out->os() << "\")\n";
296 }
297
298 // Keep output if no errors.
299 if (Error == 0) Out->keep();
300
301 return Error;
302 }
303
AssembleInput(const char * ProgName)304 static int AssembleInput(const char *ProgName) {
305 const Target *TheTarget = GetTarget(ProgName);
306 if (!TheTarget)
307 return 1;
308
309 OwningPtr<MemoryBuffer> BufferPtr;
310 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
311 errs() << ProgName << ": " << ec.message() << '\n';
312 return 1;
313 }
314 MemoryBuffer *Buffer = BufferPtr.take();
315
316 SourceMgr SrcMgr;
317
318 // Tell SrcMgr about this buffer, which is what the parser will pick up.
319 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
320
321 // Record the location of the include directories so that the lexer can find
322 // it later.
323 SrcMgr.setIncludeDirs(IncludeDirs);
324
325
326 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
327 assert(MAI && "Unable to create target asm info!");
328
329 llvm::OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
330 assert(MRI && "Unable to create target register info!");
331
332 // Package up features to be passed to target/subtarget
333 std::string FeaturesStr;
334
335 // FIXME: We shouldn't need to do this (and link in codegen).
336 // When we split this out, we should do it in a way that makes
337 // it straightforward to switch subtargets on the fly (.e.g,
338 // the .cpu and .code16 directives).
339 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName,
340 MCPU,
341 FeaturesStr,
342 RelocModel));
343
344 if (!TM) {
345 errs() << ProgName << ": error: could not create target for triple '"
346 << TripleName << "'.\n";
347 return 1;
348 }
349
350 const TargetAsmInfo *tai = new TargetAsmInfo(*TM);
351 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
352 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
353 OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
354 MCContext Ctx(*MAI, *MRI, MOFI.get(), tai);
355 MOFI->InitMCObjectFileInfo(TripleName, RelocModel, Ctx);
356
357 if (SaveTempLabels)
358 Ctx.setAllowTemporaryLabels(false);
359
360 OwningPtr<tool_output_file> Out(GetOutputStream());
361 if (!Out)
362 return 1;
363
364 formatted_raw_ostream FOS(Out->os());
365 OwningPtr<MCStreamer> Str;
366
367 const TargetLoweringObjectFile &TLOF =
368 TM->getTargetLowering()->getObjFileLowering();
369 const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(Ctx, *TM);
370
371 OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
372 OwningPtr<MCSubtargetInfo>
373 STI(TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
374
375 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
376 if (FileType == OFT_AssemblyFile) {
377 MCInstPrinter *IP =
378 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI);
379 MCCodeEmitter *CE = 0;
380 TargetAsmBackend *TAB = 0;
381 if (ShowEncoding) {
382 CE = TheTarget->createCodeEmitter(*MCII, *STI, Ctx);
383 TAB = TheTarget->createAsmBackend(TripleName);
384 }
385 Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/true,
386 /*useLoc*/ true,
387 /*useCFI*/ true, IP, CE, TAB,
388 ShowInst));
389 } else if (FileType == OFT_Null) {
390 Str.reset(createNullStreamer(Ctx));
391 } else {
392 assert(FileType == OFT_ObjectFile && "Invalid file type!");
393 MCCodeEmitter *CE = TheTarget->createCodeEmitter(*MCII, *STI, Ctx);
394 TargetAsmBackend *TAB = TheTarget->createAsmBackend(TripleName);
395 Str.reset(TheTarget->createObjectStreamer(TripleName, Ctx, *TAB,
396 FOS, CE, RelaxAll,
397 NoExecStack));
398 }
399
400 if (EnableLogging) {
401 Str.reset(createLoggingStreamer(Str.take(), errs()));
402 }
403
404 OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
405 *Str.get(), *MAI));
406 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*STI, *Parser));
407 if (!TAP) {
408 errs() << ProgName
409 << ": error: this target does not support assembly parsing.\n";
410 return 1;
411 }
412
413 Parser->setShowParsedOperands(ShowInstOperands);
414 Parser->setTargetParser(*TAP.get());
415
416 int Res = Parser->Run(NoInitialTextSection);
417
418 // Keep output if no errors.
419 if (Res == 0) Out->keep();
420
421 return Res;
422 }
423
DisassembleInput(const char * ProgName,bool Enhanced)424 static int DisassembleInput(const char *ProgName, bool Enhanced) {
425 const Target *TheTarget = GetTarget(ProgName);
426 if (!TheTarget)
427 return 0;
428
429 OwningPtr<MemoryBuffer> Buffer;
430 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, Buffer)) {
431 errs() << ProgName << ": " << ec.message() << '\n';
432 return 1;
433 }
434
435 OwningPtr<tool_output_file> Out(GetOutputStream());
436 if (!Out)
437 return 1;
438
439 int Res;
440 if (Enhanced) {
441 Res =
442 Disassembler::disassembleEnhanced(TripleName, *Buffer.take(), Out->os());
443 } else {
444 Res = Disassembler::disassemble(*TheTarget, TripleName,
445 *Buffer.take(), Out->os());
446 }
447
448 // Keep output if no errors.
449 if (Res == 0) Out->keep();
450
451 return Res;
452 }
453
454
main(int argc,char ** argv)455 int main(int argc, char **argv) {
456 // Print a stack trace if we signal out.
457 sys::PrintStackTraceOnErrorSignal();
458 PrettyStackTraceProgram X(argc, argv);
459 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
460
461 // Initialize targets and assembly printers/parsers.
462 llvm::InitializeAllTargetInfos();
463 // FIXME: We shouldn't need to initialize the Target(Machine)s.
464 llvm::InitializeAllTargets();
465 llvm::InitializeAllMCAsmInfos();
466 llvm::InitializeAllMCCodeGenInfos();
467 llvm::InitializeAllMCInstrInfos();
468 llvm::InitializeAllMCRegisterInfos();
469 llvm::InitializeAllMCSubtargetInfos();
470 llvm::InitializeAllAsmPrinters();
471 llvm::InitializeAllAsmParsers();
472 llvm::InitializeAllDisassemblers();
473
474 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
475 TripleName = Triple::normalize(TripleName);
476
477 switch (Action) {
478 default:
479 case AC_AsLex:
480 return AsLexInput(argv[0]);
481 case AC_Assemble:
482 return AssembleInput(argv[0]);
483 case AC_Disassemble:
484 return DisassembleInput(argv[0], false);
485 case AC_EDisassemble:
486 return DisassembleInput(argv[0], true);
487 }
488
489 return 0;
490 }
491
492