1
//===-- llvm-mc.cpp - Machine Code Hacking Driver -------------------------===//
3
// The LLVM Compiler Infrastructure
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
8
//===----------------------------------------------------------------------===//
10
// This utility is a simple driver that allows command line hacking on machine
13
//===----------------------------------------------------------------------===//
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"
44
static cl::opt<std::string>
45
InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
47
static cl::opt<std::string>
48
OutputFilename("o", cl::desc("Output filename"),
49
cl::value_desc("filename"));
52
ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
55
CompressDebugSections("compress-debug-sections",
56
cl::desc("Compress DWARF debug sections"));
59
ShowInst("show-inst", cl::desc("Show internal instruction representation"));
62
ShowInstOperands("show-inst-operands",
63
cl::desc("Show instructions operands as parsed"));
65
static cl::opt<unsigned>
66
OutputAsmVariant("output-asm-variant",
67
cl::desc("Syntax variant to use for output printing"));
70
PrintImmHex("print-imm-hex", cl::init(false),
71
cl::desc("Prefer hex format for immediate values"));
73
static cl::list<std::string>
74
DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
81
static cl::opt<OutputFileType>
82
FileType("filetype", cl::init(OFT_AssemblyFile),
83
cl::desc("Choose an output file type:"),
85
clEnumValN(OFT_AssemblyFile, "asm",
86
"Emit an assembly ('.s') file"),
87
clEnumValN(OFT_Null, "null",
88
"Don't emit anything (for timing purposes)"),
89
clEnumValN(OFT_ObjectFile, "obj",
90
"Emit a native object ('.o') file"),
93
static cl::list<std::string>
94
IncludeDirs("I", cl::desc("Directory of include files"),
95
cl::value_desc("directory"), cl::Prefix);
97
static cl::opt<std::string>
98
ArchName("arch", cl::desc("Target arch to assemble for, "
99
"see -version for available targets"));
101
static cl::opt<std::string>
102
TripleName("triple", cl::desc("Target triple to assemble for, "
103
"see -version for available targets"));
105
static cl::opt<std::string>
107
cl::desc("Target a specific cpu type (-mcpu=help for details)"),
108
cl::value_desc("cpu-name"),
111
static cl::list<std::string>
114
cl::desc("Target specific attributes (-mattr=help for details)"),
115
cl::value_desc("a1,+a2,-a3,..."));
117
static cl::opt<Reloc::Model>
118
RelocModel("relocation-model",
119
cl::desc("Choose relocation model"),
120
cl::init(Reloc::Default),
122
clEnumValN(Reloc::Default, "default",
123
"Target default relocation model"),
124
clEnumValN(Reloc::Static, "static",
125
"Non-relocatable code"),
126
clEnumValN(Reloc::PIC_, "pic",
127
"Fully relocatable, position independent code"),
128
clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
129
"Relocatable external references, non-relocatable code"),
132
static cl::opt<llvm::CodeModel::Model>
133
CMModel("code-model",
134
cl::desc("Choose code model"),
135
cl::init(CodeModel::Default),
136
cl::values(clEnumValN(CodeModel::Default, "default",
137
"Target default code model"),
138
clEnumValN(CodeModel::Small, "small",
140
clEnumValN(CodeModel::Kernel, "kernel",
141
"Kernel code model"),
142
clEnumValN(CodeModel::Medium, "medium",
143
"Medium code model"),
144
clEnumValN(CodeModel::Large, "large",
149
NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
150
"in the text section"));
153
GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
156
static cl::opt<std::string>
157
DebugCompilationDir("fdebug-compilation-dir",
158
cl::desc("Specifies the debug info's compilation dir"));
160
static cl::opt<std::string>
161
MainFileName("main-file-name",
162
cl::desc("Specifies the name we should consider the input file"));
164
static cl::opt<bool> SaveTempLabels("save-temp-labels",
165
cl::desc("Don't discard temporary labels"));
167
static cl::opt<bool> NoExecStack("no-exec-stack",
168
cl::desc("File doesn't need an exec stack"));
177
static cl::opt<ActionType>
178
Action(cl::desc("Action to perform:"),
179
cl::init(AC_Assemble),
180
cl::values(clEnumValN(AC_AsLex, "as-lex",
181
"Lex tokens from a .s file"),
182
clEnumValN(AC_Assemble, "assemble",
183
"Assemble a .s file (default)"),
184
clEnumValN(AC_Disassemble, "disassemble",
185
"Disassemble strings of hex bytes"),
186
clEnumValN(AC_MDisassemble, "mdis",
187
"Marked up disassembly of strings of hex bytes"),
190
static const Target *GetTarget(const char *ProgName) {
191
// Figure out the target triple.
192
if (TripleName.empty())
193
TripleName = sys::getDefaultTargetTriple();
194
Triple TheTriple(Triple::normalize(TripleName));
196
// Get the target specific parser.
198
const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
201
errs() << ProgName << ": " << Error;
205
// Update the triple name and return the found target.
206
TripleName = TheTriple.getTriple();
210
static std::unique_ptr<tool_output_file> GetOutputStream() {
211
if (OutputFilename == "")
212
OutputFilename = "-";
215
auto Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
218
errs() << EC.message() << '\n';
225
static std::string DwarfDebugFlags;
226
static void setDwarfDebugFlags(int argc, char **argv) {
227
if (!getenv("RC_DEBUG_OPTIONS"))
229
for (int i = 0; i < argc; i++) {
230
DwarfDebugFlags += argv[i];
232
DwarfDebugFlags += " ";
236
static std::string DwarfDebugProducer;
237
static void setDwarfDebugProducer(void) {
238
if(!getenv("DEBUG_PRODUCER"))
240
DwarfDebugProducer += getenv("DEBUG_PRODUCER");
243
static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
247
Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
250
while (Lexer.Lex().isNot(AsmToken::Eof)) {
251
AsmToken Tok = Lexer.getTok();
253
switch (Tok.getKind()) {
255
SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
259
case AsmToken::Error:
260
Error = true; // error already printed.
262
case AsmToken::Identifier:
263
OS << "identifier: " << Lexer.getTok().getString();
265
case AsmToken::Integer:
266
OS << "int: " << Lexer.getTok().getString();
269
OS << "real: " << Lexer.getTok().getString();
271
case AsmToken::String:
272
OS << "string: " << Lexer.getTok().getString();
275
case AsmToken::Amp: OS << "Amp"; break;
276
case AsmToken::AmpAmp: OS << "AmpAmp"; break;
277
case AsmToken::At: OS << "At"; break;
278
case AsmToken::Caret: OS << "Caret"; break;
279
case AsmToken::Colon: OS << "Colon"; break;
280
case AsmToken::Comma: OS << "Comma"; break;
281
case AsmToken::Dollar: OS << "Dollar"; break;
282
case AsmToken::Dot: OS << "Dot"; break;
283
case AsmToken::EndOfStatement: OS << "EndOfStatement"; break;
284
case AsmToken::Eof: OS << "Eof"; break;
285
case AsmToken::Equal: OS << "Equal"; break;
286
case AsmToken::EqualEqual: OS << "EqualEqual"; break;
287
case AsmToken::Exclaim: OS << "Exclaim"; break;
288
case AsmToken::ExclaimEqual: OS << "ExclaimEqual"; break;
289
case AsmToken::Greater: OS << "Greater"; break;
290
case AsmToken::GreaterEqual: OS << "GreaterEqual"; break;
291
case AsmToken::GreaterGreater: OS << "GreaterGreater"; break;
292
case AsmToken::Hash: OS << "Hash"; break;
293
case AsmToken::LBrac: OS << "LBrac"; break;
294
case AsmToken::LCurly: OS << "LCurly"; break;
295
case AsmToken::LParen: OS << "LParen"; break;
296
case AsmToken::Less: OS << "Less"; break;
297
case AsmToken::LessEqual: OS << "LessEqual"; break;
298
case AsmToken::LessGreater: OS << "LessGreater"; break;
299
case AsmToken::LessLess: OS << "LessLess"; break;
300
case AsmToken::Minus: OS << "Minus"; break;
301
case AsmToken::Percent: OS << "Percent"; break;
302
case AsmToken::Pipe: OS << "Pipe"; break;
303
case AsmToken::PipePipe: OS << "PipePipe"; break;
304
case AsmToken::Plus: OS << "Plus"; break;
305
case AsmToken::RBrac: OS << "RBrac"; break;
306
case AsmToken::RCurly: OS << "RCurly"; break;
307
case AsmToken::RParen: OS << "RParen"; break;
308
case AsmToken::Slash: OS << "Slash"; break;
309
case AsmToken::Star: OS << "Star"; break;
310
case AsmToken::Tilde: OS << "Tilde"; break;
313
// Print the token string.
315
OS.write_escaped(Tok.getString());
322
static int fillCommandLineSymbols(MCAsmParser &Parser){
323
for(auto &I: DefineSymbol){
324
auto Pair = StringRef(I).split('=');
325
if(Pair.second.empty()){
326
errs() << "error: defsym must be of the form: sym=value: " << I;
330
if(Pair.second.getAsInteger(0, Value)){
331
errs() << "error: Value is not an integer: " << Pair.second;
334
auto &Context = Parser.getContext();
335
auto Symbol = Context.getOrCreateSymbol(Pair.first);
336
Parser.getStreamer().EmitAssignment(Symbol,
337
MCConstantExpr::create(Value, Context));
342
static int AssembleInput(const char *ProgName, const Target *TheTarget,
343
SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
344
MCAsmInfo &MAI, MCSubtargetInfo &STI,
345
MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
346
std::unique_ptr<MCAsmParser> Parser(
347
createMCAsmParser(SrcMgr, Ctx, Str, MAI));
348
std::unique_ptr<MCTargetAsmParser> TAP(
349
TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
353
<< ": error: this target does not support assembly parsing.\n";
357
int SymbolResult = fillCommandLineSymbols(*Parser);
360
Parser->setShowParsedOperands(ShowInstOperands);
361
Parser->setTargetParser(*TAP);
363
int Res = Parser->Run(NoInitialTextSection);
368
int main(int argc, char **argv) {
369
// Print a stack trace if we signal out.
370
sys::PrintStackTraceOnErrorSignal();
371
PrettyStackTraceProgram X(argc, argv);
372
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
374
// Initialize targets and assembly printers/parsers.
375
llvm::InitializeAllTargetInfos();
376
llvm::InitializeAllTargetMCs();
377
llvm::InitializeAllAsmParsers();
378
llvm::InitializeAllDisassemblers();
380
// Register the target printer for --version.
381
cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
383
cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
384
MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
385
TripleName = Triple::normalize(TripleName);
386
setDwarfDebugFlags(argc, argv);
388
setDwarfDebugProducer();
390
const char *ProgName = argv[0];
391
const Target *TheTarget = GetTarget(ProgName);
394
// Now that GetTarget() has (potentially) replaced TripleName, it's safe to
395
// construct the Triple object.
396
Triple TheTriple(TripleName);
398
ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
399
MemoryBuffer::getFileOrSTDIN(InputFilename);
400
if (std::error_code EC = BufferPtr.getError()) {
401
errs() << ProgName << ": " << EC.message() << '\n';
404
MemoryBuffer *Buffer = BufferPtr->get();
408
// Tell SrcMgr about this buffer, which is what the parser will pick up.
409
SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
411
// Record the location of the include directories so that the lexer can find
413
SrcMgr.setIncludeDirs(IncludeDirs);
415
std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
416
assert(MRI && "Unable to create target register info!");
418
std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
419
assert(MAI && "Unable to create target asm info!");
421
if (CompressDebugSections) {
422
if (!zlib::isAvailable()) {
424
<< ": build tools with zlib to enable -compress-debug-sections";
427
MAI->setCompressDebugSections(true);
430
// FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
431
// MCObjectFileInfo needs a MCContext reference in order to initialize itself.
432
MCObjectFileInfo MOFI;
433
MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
434
MOFI.InitMCObjectFileInfo(TheTriple, RelocModel, CMModel, Ctx);
437
Ctx.setAllowTemporaryLabels(false);
439
Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
440
// Default to 4 for dwarf version.
441
unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
442
if (DwarfVersion < 2 || DwarfVersion > 4) {
443
errs() << ProgName << ": Dwarf version " << DwarfVersion
444
<< " is not supported." << '\n';
447
Ctx.setDwarfVersion(DwarfVersion);
448
if (!DwarfDebugFlags.empty())
449
Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
450
if (!DwarfDebugProducer.empty())
451
Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
452
if (!DebugCompilationDir.empty())
453
Ctx.setCompilationDir(DebugCompilationDir);
454
if (!MainFileName.empty())
455
Ctx.setMainFileName(MainFileName);
457
// Package up features to be passed to target/subtarget
458
std::string FeaturesStr;
460
SubtargetFeatures Features;
461
for (unsigned i = 0; i != MAttrs.size(); ++i)
462
Features.AddFeature(MAttrs[i]);
463
FeaturesStr = Features.getString();
466
std::unique_ptr<tool_output_file> Out = GetOutputStream();
470
std::unique_ptr<buffer_ostream> BOS;
471
raw_pwrite_stream *OS = &Out->os();
472
std::unique_ptr<MCStreamer> Str;
474
std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
475
std::unique_ptr<MCSubtargetInfo> STI(
476
TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
478
MCInstPrinter *IP = nullptr;
479
if (FileType == OFT_AssemblyFile) {
480
IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
483
// Set the display preference for hex vs. decimal immediates.
484
IP->setPrintImmHex(PrintImmHex);
486
// Set up the AsmStreamer.
487
MCCodeEmitter *CE = nullptr;
488
MCAsmBackend *MAB = nullptr;
490
CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
491
MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
493
auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
494
Str.reset(TheTarget->createAsmStreamer(
495
Ctx, std::move(FOut), /*asmverbose*/ true,
496
/*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst));
498
} else if (FileType == OFT_Null) {
499
Str.reset(TheTarget->createNullStreamer(Ctx));
501
assert(FileType == OFT_ObjectFile && "Invalid file type!");
503
// Don't waste memory on names of temp labels.
504
Ctx.setUseNamesOnTempLabels(false);
506
if (!Out->os().supportsSeeking()) {
507
BOS = make_unique<buffer_ostream>(Out->os());
511
MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
512
MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
513
Str.reset(TheTarget->createMCObjectStreamer(TheTriple, Ctx, *MAB, *OS, CE,
515
/*DWARFMustBeAtTheEnd*/ false));
517
Str->InitSections(true);
521
bool disassemble = false;
524
Res = AsLexInput(SrcMgr, *MAI, Out->os());
527
Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
530
case AC_MDisassemble:
531
assert(IP && "Expected assembly output");
540
Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
541
*Buffer, SrcMgr, Out->os());
543
// Keep output if no errors.
544
if (Res == 0) Out->keep();