1 //===-- llvm-mc.cpp - Machine Code Hacking Driver ---------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This utility is a simple driver that allows command line hacking on machine
10 // code.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Disassembler.h"
15 #include "llvm/MC/MCAsmBackend.h"
16 #include "llvm/MC/MCAsmInfo.h"
17 #include "llvm/MC/MCCodeEmitter.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/MCObjectWriter.h"
23 #include "llvm/MC/MCParser/AsmLexer.h"
24 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
25 #include "llvm/MC/MCRegisterInfo.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/MC/MCTargetOptionsCommandFlags.h"
29 #include "llvm/MC/TargetRegistry.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Compression.h"
32 #include "llvm/Support/FileUtilities.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/InitLLVM.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/TargetSelect.h"
38 #include "llvm/Support/ToolOutputFile.h"
39 #include "llvm/Support/WithColor.h"
40 #include "llvm/TargetParser/Host.h"
41
42 using namespace llvm;
43
44 static mc::RegisterMCTargetOptionsFlags MOF;
45
46 static cl::OptionCategory MCCategory("MC Options");
47
48 static cl::opt<std::string> InputFilename(cl::Positional,
49 cl::desc("<input file>"),
50 cl::init("-"), cl::cat(MCCategory));
51
52 static cl::list<std::string>
53 DisassemblerOptions("M", cl::desc("Disassembler options"),
54 cl::cat(MCCategory));
55
56 static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
57 cl::value_desc("filename"),
58 cl::init("-"), cl::cat(MCCategory));
59
60 static cl::opt<std::string> SplitDwarfFile("split-dwarf-file",
61 cl::desc("DWO output filename"),
62 cl::value_desc("filename"),
63 cl::cat(MCCategory));
64
65 static cl::opt<bool> ShowEncoding("show-encoding",
66 cl::desc("Show instruction encodings"),
67 cl::cat(MCCategory));
68
69 static cl::opt<bool> RelaxELFRel(
70 "relax-relocations", cl::init(true),
71 cl::desc("Emit R_X86_64_GOTPCRELX instead of R_X86_64_GOTPCREL"),
72 cl::cat(MCCategory));
73
74 static cl::opt<DebugCompressionType> CompressDebugSections(
75 "compress-debug-sections", cl::ValueOptional,
76 cl::init(DebugCompressionType::None),
77 cl::desc("Choose DWARF debug sections compression:"),
78 cl::values(clEnumValN(DebugCompressionType::None, "none", "No compression"),
79 clEnumValN(DebugCompressionType::Zlib, "zlib", "Use zlib"),
80 clEnumValN(DebugCompressionType::Zstd, "zstd", "Use zstd")),
81 cl::cat(MCCategory));
82
83 static cl::opt<bool>
84 ShowInst("show-inst", cl::desc("Show internal instruction representation"),
85 cl::cat(MCCategory));
86
87 static cl::opt<bool>
88 ShowInstOperands("show-inst-operands",
89 cl::desc("Show instructions operands as parsed"),
90 cl::cat(MCCategory));
91
92 static cl::opt<unsigned>
93 OutputAsmVariant("output-asm-variant",
94 cl::desc("Syntax variant to use for output printing"),
95 cl::cat(MCCategory));
96
97 static cl::opt<bool>
98 PrintImmHex("print-imm-hex", cl::init(false),
99 cl::desc("Prefer hex format for immediate values"),
100 cl::cat(MCCategory));
101
102 static cl::list<std::string>
103 DefineSymbol("defsym",
104 cl::desc("Defines a symbol to be an integer constant"),
105 cl::cat(MCCategory));
106
107 static cl::opt<bool>
108 PreserveComments("preserve-comments",
109 cl::desc("Preserve Comments in outputted assembly"),
110 cl::cat(MCCategory));
111
112 enum OutputFileType {
113 OFT_Null,
114 OFT_AssemblyFile,
115 OFT_ObjectFile
116 };
117 static cl::opt<OutputFileType>
118 FileType("filetype", cl::init(OFT_AssemblyFile),
119 cl::desc("Choose an output file type:"),
120 cl::values(clEnumValN(OFT_AssemblyFile, "asm",
121 "Emit an assembly ('.s') file"),
122 clEnumValN(OFT_Null, "null",
123 "Don't emit anything (for timing purposes)"),
124 clEnumValN(OFT_ObjectFile, "obj",
125 "Emit a native object ('.o') file")),
126 cl::cat(MCCategory));
127
128 static cl::list<std::string> IncludeDirs("I",
129 cl::desc("Directory of include files"),
130 cl::value_desc("directory"),
131 cl::Prefix, cl::cat(MCCategory));
132
133 static cl::opt<std::string>
134 ArchName("arch",
135 cl::desc("Target arch to assemble for, "
136 "see -version for available targets"),
137 cl::cat(MCCategory));
138
139 static cl::opt<std::string>
140 TripleName("triple",
141 cl::desc("Target triple to assemble for, "
142 "see -version for available targets"),
143 cl::cat(MCCategory));
144
145 static cl::opt<std::string>
146 MCPU("mcpu",
147 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
148 cl::value_desc("cpu-name"), cl::init(""), cl::cat(MCCategory));
149
150 static cl::list<std::string>
151 MAttrs("mattr", cl::CommaSeparated,
152 cl::desc("Target specific attributes (-mattr=help for details)"),
153 cl::value_desc("a1,+a2,-a3,..."), cl::cat(MCCategory));
154
155 static cl::opt<bool> PIC("position-independent",
156 cl::desc("Position independent"), cl::init(false),
157 cl::cat(MCCategory));
158
159 static cl::opt<bool>
160 LargeCodeModel("large-code-model",
161 cl::desc("Create cfi directives that assume the code might "
162 "be more than 2gb away"),
163 cl::cat(MCCategory));
164
165 static cl::opt<bool>
166 NoInitialTextSection("n",
167 cl::desc("Don't assume assembly file starts "
168 "in the text section"),
169 cl::cat(MCCategory));
170
171 static cl::opt<bool>
172 GenDwarfForAssembly("g",
173 cl::desc("Generate dwarf debugging info for assembly "
174 "source files"),
175 cl::cat(MCCategory));
176
177 static cl::opt<std::string>
178 DebugCompilationDir("fdebug-compilation-dir",
179 cl::desc("Specifies the debug info's compilation dir"),
180 cl::cat(MCCategory));
181
182 static cl::list<std::string> DebugPrefixMap(
183 "fdebug-prefix-map", cl::desc("Map file source paths in debug info"),
184 cl::value_desc("= separated key-value pairs"), cl::cat(MCCategory));
185
186 static cl::opt<std::string> MainFileName(
187 "main-file-name",
188 cl::desc("Specifies the name we should consider the input file"),
189 cl::cat(MCCategory));
190
191 static cl::opt<bool> SaveTempLabels("save-temp-labels",
192 cl::desc("Don't discard temporary labels"),
193 cl::cat(MCCategory));
194
195 static cl::opt<bool> LexMasmIntegers(
196 "masm-integers",
197 cl::desc("Enable binary and hex masm integers (0b110 and 0ABCh)"),
198 cl::cat(MCCategory));
199
200 static cl::opt<bool> LexMasmHexFloats(
201 "masm-hexfloats",
202 cl::desc("Enable MASM-style hex float initializers (3F800000r)"),
203 cl::cat(MCCategory));
204
205 static cl::opt<bool> LexMotorolaIntegers(
206 "motorola-integers",
207 cl::desc("Enable binary and hex Motorola integers (%110 and $ABC)"),
208 cl::cat(MCCategory));
209
210 static cl::opt<bool> NoExecStack("no-exec-stack",
211 cl::desc("File doesn't need an exec stack"),
212 cl::cat(MCCategory));
213
214 enum ActionType {
215 AC_AsLex,
216 AC_Assemble,
217 AC_Disassemble,
218 AC_MDisassemble,
219 AC_CDisassemble,
220 };
221
222 static cl::opt<ActionType> Action(
223 cl::desc("Action to perform:"), cl::init(AC_Assemble),
224 cl::values(clEnumValN(AC_AsLex, "as-lex", "Lex tokens from a .s file"),
225 clEnumValN(AC_Assemble, "assemble",
226 "Assemble a .s file (default)"),
227 clEnumValN(AC_Disassemble, "disassemble",
228 "Disassemble strings of hex bytes"),
229 clEnumValN(AC_MDisassemble, "mdis",
230 "Marked up disassembly of strings of hex bytes"),
231 clEnumValN(AC_CDisassemble, "cdis",
232 "Colored disassembly of strings of hex bytes")),
233 cl::cat(MCCategory));
234
GetTarget(const char * ProgName)235 static const Target *GetTarget(const char *ProgName) {
236 // Figure out the target triple.
237 if (TripleName.empty())
238 TripleName = sys::getDefaultTargetTriple();
239 Triple TheTriple(Triple::normalize(TripleName));
240
241 // Get the target specific parser.
242 std::string Error;
243 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
244 Error);
245 if (!TheTarget) {
246 WithColor::error(errs(), ProgName) << Error;
247 return nullptr;
248 }
249
250 // Update the triple name and return the found target.
251 TripleName = TheTriple.getTriple();
252 return TheTarget;
253 }
254
GetOutputStream(StringRef Path,sys::fs::OpenFlags Flags)255 static std::unique_ptr<ToolOutputFile> GetOutputStream(StringRef Path,
256 sys::fs::OpenFlags Flags) {
257 std::error_code EC;
258 auto Out = std::make_unique<ToolOutputFile>(Path, EC, Flags);
259 if (EC) {
260 WithColor::error() << EC.message() << '\n';
261 return nullptr;
262 }
263
264 return Out;
265 }
266
267 static std::string DwarfDebugFlags;
setDwarfDebugFlags(int argc,char ** argv)268 static void setDwarfDebugFlags(int argc, char **argv) {
269 if (!getenv("RC_DEBUG_OPTIONS"))
270 return;
271 for (int i = 0; i < argc; i++) {
272 DwarfDebugFlags += argv[i];
273 if (i + 1 < argc)
274 DwarfDebugFlags += " ";
275 }
276 }
277
278 static std::string DwarfDebugProducer;
setDwarfDebugProducer()279 static void setDwarfDebugProducer() {
280 if(!getenv("DEBUG_PRODUCER"))
281 return;
282 DwarfDebugProducer += getenv("DEBUG_PRODUCER");
283 }
284
AsLexInput(SourceMgr & SrcMgr,MCAsmInfo & MAI,raw_ostream & OS)285 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
286 raw_ostream &OS) {
287
288 AsmLexer Lexer(MAI);
289 Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
290
291 bool Error = false;
292 while (Lexer.Lex().isNot(AsmToken::Eof)) {
293 Lexer.getTok().dump(OS);
294 OS << "\n";
295 if (Lexer.getTok().getKind() == AsmToken::Error)
296 Error = true;
297 }
298
299 return Error;
300 }
301
fillCommandLineSymbols(MCAsmParser & Parser)302 static int fillCommandLineSymbols(MCAsmParser &Parser) {
303 for (auto &I: DefineSymbol) {
304 auto Pair = StringRef(I).split('=');
305 auto Sym = Pair.first;
306 auto Val = Pair.second;
307
308 if (Sym.empty() || Val.empty()) {
309 WithColor::error() << "defsym must be of the form: sym=value: " << I
310 << "\n";
311 return 1;
312 }
313 int64_t Value;
314 if (Val.getAsInteger(0, Value)) {
315 WithColor::error() << "value is not an integer: " << Val << "\n";
316 return 1;
317 }
318 Parser.getContext().setSymbolValue(Parser.getStreamer(), Sym, Value);
319 }
320 return 0;
321 }
322
AssembleInput(const char * ProgName,const Target * TheTarget,SourceMgr & SrcMgr,MCContext & Ctx,MCStreamer & Str,MCAsmInfo & MAI,MCSubtargetInfo & STI,MCInstrInfo & MCII,MCTargetOptions const & MCOptions)323 static int AssembleInput(const char *ProgName, const Target *TheTarget,
324 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
325 MCAsmInfo &MAI, MCSubtargetInfo &STI,
326 MCInstrInfo &MCII, MCTargetOptions const &MCOptions) {
327 std::unique_ptr<MCAsmParser> Parser(
328 createMCAsmParser(SrcMgr, Ctx, Str, MAI));
329 std::unique_ptr<MCTargetAsmParser> TAP(
330 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
331
332 if (!TAP) {
333 WithColor::error(errs(), ProgName)
334 << "this target does not support assembly parsing.\n";
335 return 1;
336 }
337
338 int SymbolResult = fillCommandLineSymbols(*Parser);
339 if(SymbolResult)
340 return SymbolResult;
341 Parser->setShowParsedOperands(ShowInstOperands);
342 Parser->setTargetParser(*TAP);
343 Parser->getLexer().setLexMasmIntegers(LexMasmIntegers);
344 Parser->getLexer().setLexMasmHexFloats(LexMasmHexFloats);
345 Parser->getLexer().setLexMotorolaIntegers(LexMotorolaIntegers);
346
347 int Res = Parser->Run(NoInitialTextSection);
348
349 return Res;
350 }
351
main(int argc,char ** argv)352 int main(int argc, char **argv) {
353 InitLLVM X(argc, argv);
354
355 // Initialize targets and assembly printers/parsers.
356 llvm::InitializeAllTargetInfos();
357 llvm::InitializeAllTargetMCs();
358 llvm::InitializeAllAsmParsers();
359 llvm::InitializeAllDisassemblers();
360
361 // Register the target printer for --version.
362 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
363
364 cl::HideUnrelatedOptions({&MCCategory, &getColorCategory()});
365 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
366 const MCTargetOptions MCOptions = mc::InitMCTargetOptionsFromFlags();
367 setDwarfDebugFlags(argc, argv);
368
369 setDwarfDebugProducer();
370
371 const char *ProgName = argv[0];
372 const Target *TheTarget = GetTarget(ProgName);
373 if (!TheTarget)
374 return 1;
375 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
376 // construct the Triple object.
377 Triple TheTriple(TripleName);
378
379 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
380 MemoryBuffer::getFileOrSTDIN(InputFilename, /*IsText=*/true);
381 if (std::error_code EC = BufferPtr.getError()) {
382 WithColor::error(errs(), ProgName)
383 << InputFilename << ": " << EC.message() << '\n';
384 return 1;
385 }
386 MemoryBuffer *Buffer = BufferPtr->get();
387
388 SourceMgr SrcMgr;
389
390 // Tell SrcMgr about this buffer, which is what the parser will pick up.
391 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
392
393 // Record the location of the include directories so that the lexer can find
394 // it later.
395 SrcMgr.setIncludeDirs(IncludeDirs);
396
397 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
398 assert(MRI && "Unable to create target register info!");
399
400 std::unique_ptr<MCAsmInfo> MAI(
401 TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
402 assert(MAI && "Unable to create target asm info!");
403
404 MAI->setRelaxELFRelocations(RelaxELFRel);
405 if (CompressDebugSections != DebugCompressionType::None) {
406 if (const char *Reason = compression::getReasonIfUnsupported(
407 compression::formatFor(CompressDebugSections))) {
408 WithColor::error(errs(), ProgName)
409 << "--compress-debug-sections: " << Reason;
410 return 1;
411 }
412 }
413 MAI->setCompressDebugSections(CompressDebugSections);
414 MAI->setPreserveAsmComments(PreserveComments);
415
416 // Package up features to be passed to target/subtarget
417 std::string FeaturesStr;
418 if (MAttrs.size()) {
419 SubtargetFeatures Features;
420 for (unsigned i = 0; i != MAttrs.size(); ++i)
421 Features.AddFeature(MAttrs[i]);
422 FeaturesStr = Features.getString();
423 }
424
425 std::unique_ptr<MCSubtargetInfo> STI(
426 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
427 assert(STI && "Unable to create subtarget info!");
428
429 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
430 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
431 MCContext Ctx(TheTriple, MAI.get(), MRI.get(), STI.get(), &SrcMgr,
432 &MCOptions);
433 std::unique_ptr<MCObjectFileInfo> MOFI(
434 TheTarget->createMCObjectFileInfo(Ctx, PIC, LargeCodeModel));
435 Ctx.setObjectFileInfo(MOFI.get());
436
437 if (SaveTempLabels)
438 Ctx.setAllowTemporaryLabels(false);
439
440 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
441 // Default to 4 for dwarf version.
442 unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
443 if (DwarfVersion < 2 || DwarfVersion > 5) {
444 errs() << ProgName << ": Dwarf version " << DwarfVersion
445 << " is not supported." << '\n';
446 return 1;
447 }
448 Ctx.setDwarfVersion(DwarfVersion);
449 if (MCOptions.Dwarf64) {
450 // The 64-bit DWARF format was introduced in DWARFv3.
451 if (DwarfVersion < 3) {
452 errs() << ProgName
453 << ": the 64-bit DWARF format is not supported for DWARF versions "
454 "prior to 3\n";
455 return 1;
456 }
457 // 32-bit targets don't support DWARF64, which requires 64-bit relocations.
458 if (MAI->getCodePointerSize() < 8) {
459 errs() << ProgName
460 << ": the 64-bit DWARF format is only supported for 64-bit "
461 "targets\n";
462 return 1;
463 }
464 // If needsDwarfSectionOffsetDirective is true, we would eventually call
465 // MCStreamer::emitSymbolValue() with IsSectionRelative = true, but that
466 // is supported only for 4-byte long references.
467 if (MAI->needsDwarfSectionOffsetDirective()) {
468 errs() << ProgName << ": the 64-bit DWARF format is not supported for "
469 << TheTriple.normalize() << "\n";
470 return 1;
471 }
472 Ctx.setDwarfFormat(dwarf::DWARF64);
473 }
474 if (!DwarfDebugFlags.empty())
475 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
476 if (!DwarfDebugProducer.empty())
477 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
478 if (!DebugCompilationDir.empty())
479 Ctx.setCompilationDir(DebugCompilationDir);
480 else {
481 // If no compilation dir is set, try to use the current directory.
482 SmallString<128> CWD;
483 if (!sys::fs::current_path(CWD))
484 Ctx.setCompilationDir(CWD);
485 }
486 for (const auto &Arg : DebugPrefixMap) {
487 const auto &KV = StringRef(Arg).split('=');
488 Ctx.addDebugPrefixMapEntry(std::string(KV.first), std::string(KV.second));
489 }
490 if (!MainFileName.empty())
491 Ctx.setMainFileName(MainFileName);
492 if (GenDwarfForAssembly)
493 Ctx.setGenDwarfRootFile(InputFilename, Buffer->getBuffer());
494
495 sys::fs::OpenFlags Flags = (FileType == OFT_AssemblyFile)
496 ? sys::fs::OF_TextWithCRLF
497 : sys::fs::OF_None;
498 std::unique_ptr<ToolOutputFile> Out = GetOutputStream(OutputFilename, Flags);
499 if (!Out)
500 return 1;
501
502 std::unique_ptr<ToolOutputFile> DwoOut;
503 if (!SplitDwarfFile.empty()) {
504 if (FileType != OFT_ObjectFile) {
505 WithColor::error() << "dwo output only supported with object files\n";
506 return 1;
507 }
508 DwoOut = GetOutputStream(SplitDwarfFile, sys::fs::OF_None);
509 if (!DwoOut)
510 return 1;
511 }
512
513 std::unique_ptr<buffer_ostream> BOS;
514 raw_pwrite_stream *OS = &Out->os();
515 std::unique_ptr<MCStreamer> Str;
516
517 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
518 assert(MCII && "Unable to create instruction info!");
519
520 MCInstPrinter *IP = nullptr;
521 if (FileType == OFT_AssemblyFile) {
522 IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
523 *MAI, *MCII, *MRI);
524
525 if (!IP) {
526 WithColor::error()
527 << "unable to create instruction printer for target triple '"
528 << TheTriple.normalize() << "' with assembly variant "
529 << OutputAsmVariant << ".\n";
530 return 1;
531 }
532
533 for (StringRef Opt : DisassemblerOptions)
534 if (!IP->applyTargetSpecificCLOption(Opt)) {
535 WithColor::error() << "invalid disassembler option '" << Opt << "'\n";
536 return 1;
537 }
538
539 // Set the display preference for hex vs. decimal immediates.
540 IP->setPrintImmHex(PrintImmHex);
541
542 // Set up the AsmStreamer.
543 std::unique_ptr<MCCodeEmitter> CE;
544 if (ShowEncoding)
545 CE.reset(TheTarget->createMCCodeEmitter(*MCII, Ctx));
546
547 std::unique_ptr<MCAsmBackend> MAB(
548 TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
549 auto FOut = std::make_unique<formatted_raw_ostream>(*OS);
550 Str.reset(
551 TheTarget->createAsmStreamer(Ctx, std::move(FOut), /*asmverbose*/ true,
552 /*useDwarfDirectory*/ true, IP,
553 std::move(CE), std::move(MAB), ShowInst));
554
555 } else if (FileType == OFT_Null) {
556 Str.reset(TheTarget->createNullStreamer(Ctx));
557 } else {
558 assert(FileType == OFT_ObjectFile && "Invalid file type!");
559
560 if (!Out->os().supportsSeeking()) {
561 BOS = std::make_unique<buffer_ostream>(Out->os());
562 OS = BOS.get();
563 }
564
565 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, Ctx);
566 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions);
567 Str.reset(TheTarget->createMCObjectStreamer(
568 TheTriple, Ctx, std::unique_ptr<MCAsmBackend>(MAB),
569 DwoOut ? MAB->createDwoObjectWriter(*OS, DwoOut->os())
570 : MAB->createObjectWriter(*OS),
571 std::unique_ptr<MCCodeEmitter>(CE), *STI, MCOptions.MCRelaxAll,
572 MCOptions.MCIncrementalLinkerCompatible,
573 /*DWARFMustBeAtTheEnd*/ false));
574 if (NoExecStack)
575 Str->initSections(true, *STI);
576 }
577
578 // Use Assembler information for parsing.
579 Str->setUseAssemblerInfoForParsing(true);
580
581 int Res = 1;
582 bool disassemble = false;
583 switch (Action) {
584 case AC_AsLex:
585 Res = AsLexInput(SrcMgr, *MAI, Out->os());
586 break;
587 case AC_Assemble:
588 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
589 *MCII, MCOptions);
590 break;
591 case AC_MDisassemble:
592 IP->setUseMarkup(true);
593 disassemble = true;
594 break;
595 case AC_CDisassemble:
596 IP->setUseColor(true);
597 disassemble = true;
598 break;
599 case AC_Disassemble:
600 disassemble = true;
601 break;
602 }
603 if (disassemble)
604 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str, *Buffer,
605 SrcMgr, Ctx, MCOptions);
606
607 // Keep output if no errors.
608 if (Res == 0) {
609 Out->keep();
610 if (DwoOut)
611 DwoOut->keep();
612 }
613 return Res;
614 }
615