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 enum ActionType { 163 AC_AsLex, 164 AC_Assemble, 165 AC_Disassemble, 166 AC_MDisassemble, 167 AC_HDisassemble 168 }; 169 170 static cl::opt<ActionType> 171 Action(cl::desc("Action to perform:"), 172 cl::init(AC_Assemble), 173 cl::values(clEnumValN(AC_AsLex, "as-lex", 174 "Lex tokens from a .s file"), 175 clEnumValN(AC_Assemble, "assemble", 176 "Assemble a .s file (default)"), 177 clEnumValN(AC_Disassemble, "disassemble", 178 "Disassemble strings of hex bytes"), 179 clEnumValN(AC_MDisassemble, "mdis", 180 "Marked up disassembly of strings of hex bytes"), 181 clEnumValN(AC_HDisassemble, "hdis", 182 "Disassemble strings of hex bytes printing " 183 "immediates as hex"), 184 clEnumValEnd)); 185 186 static const Target *GetTarget(const char *ProgName) { 187 // Figure out the target triple. 188 if (TripleName.empty()) 189 TripleName = sys::getDefaultTargetTriple(); 190 Triple TheTriple(Triple::normalize(TripleName)); 191 192 // Get the target specific parser. 193 std::string Error; 194 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple, 195 Error); 196 if (!TheTarget) { 197 errs() << ProgName << ": " << Error; 198 return nullptr; 199 } 200 201 // Update the triple name and return the found target. 202 TripleName = TheTriple.getTriple(); 203 return TheTarget; 204 } 205 206 static tool_output_file *GetOutputStream() { 207 if (OutputFilename == "") 208 OutputFilename = "-"; 209 210 std::string Err; 211 tool_output_file *Out = 212 new tool_output_file(OutputFilename.c_str(), Err, sys::fs::F_None); 213 if (!Err.empty()) { 214 errs() << Err << '\n'; 215 delete Out; 216 return nullptr; 217 } 218 219 return Out; 220 } 221 222 static std::string DwarfDebugFlags; 223 static void setDwarfDebugFlags(int argc, char **argv) { 224 if (!getenv("RC_DEBUG_OPTIONS")) 225 return; 226 for (int i = 0; i < argc; i++) { 227 DwarfDebugFlags += argv[i]; 228 if (i + 1 < argc) 229 DwarfDebugFlags += " "; 230 } 231 } 232 233 static std::string DwarfDebugProducer; 234 static void setDwarfDebugProducer(void) { 235 if(!getenv("DEBUG_PRODUCER")) 236 return; 237 DwarfDebugProducer += getenv("DEBUG_PRODUCER"); 238 } 239 240 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI, tool_output_file *Out) { 241 242 AsmLexer Lexer(MAI); 243 Lexer.setBuffer(SrcMgr.getMemoryBuffer(0)); 244 245 bool Error = false; 246 while (Lexer.Lex().isNot(AsmToken::Eof)) { 247 AsmToken Tok = Lexer.getTok(); 248 249 switch (Tok.getKind()) { 250 default: 251 SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning, 252 "unknown token"); 253 Error = true; 254 break; 255 case AsmToken::Error: 256 Error = true; // error already printed. 257 break; 258 case AsmToken::Identifier: 259 Out->os() << "identifier: " << Lexer.getTok().getString(); 260 break; 261 case AsmToken::Integer: 262 Out->os() << "int: " << Lexer.getTok().getString(); 263 break; 264 case AsmToken::Real: 265 Out->os() << "real: " << Lexer.getTok().getString(); 266 break; 267 case AsmToken::String: 268 Out->os() << "string: " << Lexer.getTok().getString(); 269 break; 270 271 case AsmToken::Amp: Out->os() << "Amp"; break; 272 case AsmToken::AmpAmp: Out->os() << "AmpAmp"; break; 273 case AsmToken::At: Out->os() << "At"; break; 274 case AsmToken::Caret: Out->os() << "Caret"; break; 275 case AsmToken::Colon: Out->os() << "Colon"; break; 276 case AsmToken::Comma: Out->os() << "Comma"; break; 277 case AsmToken::Dollar: Out->os() << "Dollar"; break; 278 case AsmToken::Dot: Out->os() << "Dot"; break; 279 case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break; 280 case AsmToken::Eof: Out->os() << "Eof"; break; 281 case AsmToken::Equal: Out->os() << "Equal"; break; 282 case AsmToken::EqualEqual: Out->os() << "EqualEqual"; break; 283 case AsmToken::Exclaim: Out->os() << "Exclaim"; break; 284 case AsmToken::ExclaimEqual: Out->os() << "ExclaimEqual"; break; 285 case AsmToken::Greater: Out->os() << "Greater"; break; 286 case AsmToken::GreaterEqual: Out->os() << "GreaterEqual"; break; 287 case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break; 288 case AsmToken::Hash: Out->os() << "Hash"; break; 289 case AsmToken::LBrac: Out->os() << "LBrac"; break; 290 case AsmToken::LCurly: Out->os() << "LCurly"; break; 291 case AsmToken::LParen: Out->os() << "LParen"; break; 292 case AsmToken::Less: Out->os() << "Less"; break; 293 case AsmToken::LessEqual: Out->os() << "LessEqual"; break; 294 case AsmToken::LessGreater: Out->os() << "LessGreater"; break; 295 case AsmToken::LessLess: Out->os() << "LessLess"; break; 296 case AsmToken::Minus: Out->os() << "Minus"; break; 297 case AsmToken::Percent: Out->os() << "Percent"; break; 298 case AsmToken::Pipe: Out->os() << "Pipe"; break; 299 case AsmToken::PipePipe: Out->os() << "PipePipe"; break; 300 case AsmToken::Plus: Out->os() << "Plus"; break; 301 case AsmToken::RBrac: Out->os() << "RBrac"; break; 302 case AsmToken::RCurly: Out->os() << "RCurly"; break; 303 case AsmToken::RParen: Out->os() << "RParen"; break; 304 case AsmToken::Slash: Out->os() << "Slash"; break; 305 case AsmToken::Star: Out->os() << "Star"; break; 306 case AsmToken::Tilde: Out->os() << "Tilde"; break; 307 } 308 309 // Print the token string. 310 Out->os() << " (\""; 311 Out->os().write_escaped(Tok.getString()); 312 Out->os() << "\")\n"; 313 } 314 315 return Error; 316 } 317 318 static int AssembleInput(const char *ProgName, const Target *TheTarget, 319 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str, 320 MCAsmInfo &MAI, MCSubtargetInfo &STI, MCInstrInfo &MCII) { 321 std::unique_ptr<MCAsmParser> Parser( 322 createMCAsmParser(SrcMgr, Ctx, Str, MAI)); 323 std::unique_ptr<MCTargetAsmParser> TAP( 324 TheTarget->createMCAsmParser(STI, *Parser, MCII, 325 InitMCTargetOptionsFromFlags())); 326 if (!TAP) { 327 errs() << ProgName 328 << ": error: this target does not support assembly parsing.\n"; 329 return 1; 330 } 331 332 Parser->setShowParsedOperands(ShowInstOperands); 333 Parser->setTargetParser(*TAP.get()); 334 335 int Res = Parser->Run(NoInitialTextSection); 336 337 return Res; 338 } 339 340 int main(int argc, char **argv) { 341 // Print a stack trace if we signal out. 342 sys::PrintStackTraceOnErrorSignal(); 343 PrettyStackTraceProgram X(argc, argv); 344 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 345 346 // Initialize targets and assembly printers/parsers. 347 llvm::InitializeAllTargetInfos(); 348 llvm::InitializeAllTargetMCs(); 349 llvm::InitializeAllAsmParsers(); 350 llvm::InitializeAllDisassemblers(); 351 352 // Register the target printer for --version. 353 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 354 355 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n"); 356 TripleName = Triple::normalize(TripleName); 357 setDwarfDebugFlags(argc, argv); 358 359 setDwarfDebugProducer(); 360 361 const char *ProgName = argv[0]; 362 const Target *TheTarget = GetTarget(ProgName); 363 if (!TheTarget) 364 return 1; 365 366 std::unique_ptr<MemoryBuffer> BufferPtr; 367 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) { 368 errs() << ProgName << ": " << ec.message() << '\n'; 369 return 1; 370 } 371 MemoryBuffer *Buffer = BufferPtr.release(); 372 373 SourceMgr SrcMgr; 374 375 // Tell SrcMgr about this buffer, which is what the parser will pick up. 376 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc()); 377 378 // Record the location of the include directories so that the lexer can find 379 // it later. 380 SrcMgr.setIncludeDirs(IncludeDirs); 381 382 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName)); 383 assert(MRI && "Unable to create target register info!"); 384 385 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName)); 386 assert(MAI && "Unable to create target asm info!"); 387 388 if (CompressDebugSections) { 389 if (!zlib::isAvailable()) { 390 errs() << ProgName << ": build tools with zlib to enable -compress-debug-sections"; 391 return 1; 392 } 393 MAI->setCompressDebugSections(true); 394 } 395 396 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and 397 // MCObjectFileInfo needs a MCContext reference in order to initialize itself. 398 std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo()); 399 MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr); 400 MOFI->InitMCObjectFileInfo(TripleName, RelocModel, CMModel, Ctx); 401 402 if (SaveTempLabels) 403 Ctx.setAllowTemporaryLabels(false); 404 405 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly); 406 if (DwarfVersion < 2 || DwarfVersion > 4) { 407 errs() << ProgName << ": Dwarf version " << DwarfVersion 408 << " is not supported." << '\n'; 409 return 1; 410 } 411 Ctx.setDwarfVersion(DwarfVersion); 412 if (!DwarfDebugFlags.empty()) 413 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags)); 414 if (!DwarfDebugProducer.empty()) 415 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer)); 416 if (!DebugCompilationDir.empty()) 417 Ctx.setCompilationDir(DebugCompilationDir); 418 if (!MainFileName.empty()) 419 Ctx.setMainFileName(MainFileName); 420 421 // Package up features to be passed to target/subtarget 422 std::string FeaturesStr; 423 if (MAttrs.size()) { 424 SubtargetFeatures Features; 425 for (unsigned i = 0; i != MAttrs.size(); ++i) 426 Features.AddFeature(MAttrs[i]); 427 FeaturesStr = Features.getString(); 428 } 429 430 std::unique_ptr<tool_output_file> Out(GetOutputStream()); 431 if (!Out) 432 return 1; 433 434 formatted_raw_ostream FOS(Out->os()); 435 std::unique_ptr<MCStreamer> Str; 436 437 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo()); 438 std::unique_ptr<MCSubtargetInfo> STI( 439 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr)); 440 441 MCInstPrinter *IP = nullptr; 442 if (FileType == OFT_AssemblyFile) { 443 IP = 444 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *MCII, *MRI, *STI); 445 MCCodeEmitter *CE = nullptr; 446 MCAsmBackend *MAB = nullptr; 447 if (ShowEncoding) { 448 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx); 449 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU); 450 } 451 Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/ true, 452 /*useDwarfDirectory*/ true, IP, CE, 453 MAB, ShowInst)); 454 455 } else if (FileType == OFT_Null) { 456 Str.reset(createNullStreamer(Ctx)); 457 } else { 458 assert(FileType == OFT_ObjectFile && "Invalid file type!"); 459 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx); 460 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU); 461 Str.reset(TheTarget->createMCObjectStreamer(TripleName, Ctx, *MAB, 462 FOS, CE, *STI, RelaxAll, 463 NoExecStack)); 464 } 465 466 int Res = 1; 467 bool disassemble = false; 468 switch (Action) { 469 case AC_AsLex: 470 Res = AsLexInput(SrcMgr, *MAI, Out.get()); 471 break; 472 case AC_Assemble: 473 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI, *MCII); 474 break; 475 case AC_MDisassemble: 476 assert(IP && "Expected assembly output"); 477 IP->setUseMarkup(1); 478 disassemble = true; 479 break; 480 case AC_HDisassemble: 481 assert(IP && "Expected assembly output"); 482 IP->setPrintImmHex(1); 483 disassemble = true; 484 break; 485 case AC_Disassemble: 486 disassemble = true; 487 break; 488 } 489 if (disassemble) 490 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str, 491 *Buffer, SrcMgr, Out->os()); 492 493 // Keep output if no errors. 494 if (Res == 0) Out->keep(); 495 return Res; 496 } 497