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