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