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