1//=== llvm-dwarfutil.cpp --------------------------------------------------===//
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#include "DebugInfoLinker.h"
10#include "Error.h"
11#include "Options.h"
12#include "llvm/DebugInfo/DWARF/DWARFContext.h"
13#include "llvm/DebugInfo/DWARF/DWARFVerifier.h"
14#include "llvm/ObjCopy/CommonConfig.h"
15#include "llvm/ObjCopy/ConfigManager.h"
16#include "llvm/ObjCopy/ObjCopy.h"
17#include "llvm/Option/Arg.h"
18#include "llvm/Option/ArgList.h"
19#include "llvm/Option/Option.h"
20#include "llvm/Support/CRC.h"
21#include "llvm/Support/CommandLine.h"
22#include "llvm/Support/Endian.h"
23#include "llvm/Support/FileUtilities.h"
24#include "llvm/Support/FormatVariadic.h"
25#include "llvm/Support/InitLLVM.h"
26#include "llvm/Support/PrettyStackTrace.h"
27#include "llvm/Support/Process.h"
28#include "llvm/Support/Signals.h"
29#include "llvm/Support/TargetSelect.h"
30
31using namespace llvm;
32using namespace object;
33
34namespace {
35enum ID {
36 OPT_INVALID = 0, // This is not an option ID.
37#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
38#include "Options.inc"
39#undef OPTION
40};
41
42using namespace llvm::opt;
43#define OPTTABLE_CODE
44#include "Options.inc"
45
46class DwarfutilOptTable : public opt::OptTable {
47public:
48 DwarfutilOptTable() : opt::OptTable(optionTables()) {}
49};
50} // namespace
51
52namespace llvm {
53namespace dwarfutil {
54
55std::string ToolName;
56
57static Error validateAndSetOptions(opt::InputArgList &Args, Options &Options) {
58 auto UnknownArgs = Args.filtered(Ids: OPT_UNKNOWN);
59 if (!UnknownArgs.empty())
60 return createStringError(
61 EC: std::errc::invalid_argument,
62 Fmt: formatv(Fmt: "unknown option: {0}", Vals: (*UnknownArgs.begin())->getSpelling())
63 .str()
64 .c_str());
65
66 std::vector<std::string> InputFiles = Args.getAllArgValues(Id: OPT_INPUT);
67 if (InputFiles.size() != 2)
68 return createStringError(
69 EC: std::errc::invalid_argument,
70 Fmt: formatv(Fmt: "exactly two positional arguments expected, {0} provided",
71 Vals: InputFiles.size())
72 .str()
73 .c_str());
74
75 Options.InputFileName = InputFiles[0];
76 Options.OutputFileName = InputFiles[1];
77
78 Options.BuildSeparateDebugFile =
79 Args.hasFlag(Pos: OPT_separate_debug_file, Neg: OPT_no_separate_debug_file, Default: false);
80 Options.DoODRDeduplication =
81 Args.hasFlag(Pos: OPT_odr_deduplication, Neg: OPT_no_odr_deduplication, Default: true);
82 Options.DoGarbageCollection =
83 Args.hasFlag(Pos: OPT_garbage_collection, Neg: OPT_no_garbage_collection, Default: true);
84 Options.Verbose = Args.hasArg(Ids: OPT_verbose);
85 Options.Verify = Args.hasArg(Ids: OPT_verify);
86
87 if (opt::Arg *NumThreads = Args.getLastArg(Ids: OPT_threads))
88 Options.NumThreads = atoi(nptr: NumThreads->getValue());
89 else
90 Options.NumThreads = 0; // Use all available hardware threads
91
92 if (opt::Arg *Tombstone = Args.getLastArg(Ids: OPT_tombstone)) {
93 StringRef S = Tombstone->getValue();
94 if (S == "bfd")
95 Options.Tombstone = TombstoneKind::BFD;
96 else if (S == "maxpc")
97 Options.Tombstone = TombstoneKind::MaxPC;
98 else if (S == "universal")
99 Options.Tombstone = TombstoneKind::Universal;
100 else if (S == "exec")
101 Options.Tombstone = TombstoneKind::Exec;
102 else
103 return createStringError(
104 EC: std::errc::invalid_argument,
105 Fmt: formatv(Fmt: "unknown tombstone value: '{0}'", Vals&: S).str().c_str());
106 }
107
108 if (opt::Arg *LinkerKind = Args.getLastArg(Ids: OPT_linker)) {
109 StringRef S = LinkerKind->getValue();
110 if (S == "classic")
111 Options.UseDWARFLinkerParallel = false;
112 else if (S == "parallel")
113 Options.UseDWARFLinkerParallel = true;
114 else
115 return createStringError(
116 EC: std::errc::invalid_argument,
117 Fmt: formatv(Fmt: "unknown linker kind value: '{0}'", Vals&: S).str().c_str());
118 }
119
120 if (opt::Arg *BuildAccelerator = Args.getLastArg(Ids: OPT_build_accelerator)) {
121 StringRef S = BuildAccelerator->getValue();
122
123 if (S == "none")
124 Options.AccelTableKind = DwarfUtilAccelKind::None;
125 else if (S == "DWARF")
126 Options.AccelTableKind = DwarfUtilAccelKind::DWARF;
127 else
128 return createStringError(
129 EC: std::errc::invalid_argument,
130 Fmt: formatv(Fmt: "unknown build-accelerator value: '{0}'", Vals&: S).str().c_str());
131 }
132
133 if (opt::Arg *Compression = Args.getLastArg(Ids: OPT_compress_debug_sections)) {
134 StringRef S = Compression->getValue();
135
136 if (S == "none")
137 Options.CompressionType = DebugCompressionType::None;
138 else if (S == "zlib")
139 Options.CompressionType = DebugCompressionType::Zlib;
140 else if (S == "zstd")
141 Options.CompressionType = DebugCompressionType::Zstd;
142 else
143 return createStringError(
144 EC: std::errc::invalid_argument,
145 Fmt: formatv(Fmt: "unknown compress-debug-sections value: '{0}'", Vals&: S)
146 .str()
147 .c_str());
148
149 if (*Options.CompressionType != DebugCompressionType::None) {
150 if (const char *Reason = compression::getReasonIfUnsupported(
151 F: compression::formatFor(Type: *Options.CompressionType)))
152 return createStringError(EC: std::errc::invalid_argument, Fmt: Reason);
153 }
154 }
155
156 if (Options.Verbose) {
157 if (Options.NumThreads != 1 && Args.hasArg(Ids: OPT_threads))
158 warning(Message: "--num-threads set to 1 because verbose mode is specified");
159
160 Options.NumThreads = 1;
161 }
162
163 if (Options.DoODRDeduplication && Args.hasArg(Ids: OPT_odr_deduplication) &&
164 !Options.DoGarbageCollection)
165 return createStringError(
166 EC: std::errc::invalid_argument,
167 Fmt: "cannot use --odr-deduplication without --garbage-collection");
168
169 if (Options.BuildSeparateDebugFile && Options.OutputFileName == "-")
170 return createStringError(
171 EC: std::errc::invalid_argument,
172 Fmt: "unable to write to stdout when --separate-debug-file specified");
173
174 return Error::success();
175}
176
177static Error setConfigToAddNewDebugSections(objcopy::ConfigManager &Config,
178 ObjectFile &ObjFile) {
179 // Add new debug sections.
180 for (SectionRef Sec : ObjFile.sections()) {
181 Expected<StringRef> SecName = Sec.getName();
182 if (!SecName)
183 return SecName.takeError();
184
185 if (isDebugSection(SecName: *SecName)) {
186 Expected<StringRef> SecData = Sec.getContents();
187 if (!SecData)
188 return SecData.takeError();
189
190 Config.Common.AddSection.emplace_back(Args: objcopy::NewSectionInfo(
191 *SecName, MemoryBuffer::getMemBuffer(InputData: *SecData, BufferName: *SecName, RequiresNullTerminator: false)));
192 }
193 }
194
195 return Error::success();
196}
197
198static Error verifyOutput(const Options &Opts) {
199 if (Opts.OutputFileName == "-") {
200 warning(Message: "verification skipped because writing to stdout");
201 return Error::success();
202 }
203
204 std::string FileName = Opts.BuildSeparateDebugFile
205 ? Opts.getSeparateDebugFileName()
206 : Opts.OutputFileName;
207 Expected<OwningBinary<Binary>> BinOrErr = createBinary(Path: FileName);
208 if (!BinOrErr)
209 return createFileError(F: FileName, E: BinOrErr.takeError());
210
211 if (BinOrErr->getBinary()->isObject()) {
212 if (ObjectFile *Obj = static_cast<ObjectFile *>(BinOrErr->getBinary())) {
213 verbose(Message: "Verifying DWARF...", Verbose: Opts.Verbose);
214 std::unique_ptr<DWARFContext> DICtx = DWARFContext::create(Obj: *Obj);
215 DIDumpOptions DumpOpts;
216 if (!DICtx->verify(OS&: Opts.Verbose ? outs() : nulls(),
217 DumpOpts: DumpOpts.noImplicitRecursion()))
218 return createFileError(F: FileName,
219 E: createError(Err: "output verification failed"));
220
221 return Error::success();
222 }
223 }
224
225 // The file "FileName" was created by this utility in the previous steps
226 // (i.e. it is already known that it should pass the isObject check).
227 // If the createBinary() function does not return an error, the isObject
228 // check should also be successful.
229 llvm_unreachable(
230 formatv("tool unexpectedly did not emit a supported object file: '{0}'",
231 FileName)
232 .str()
233 .c_str());
234}
235
236class raw_crc_ostream : public raw_ostream {
237public:
238 explicit raw_crc_ostream(raw_ostream &O) : OS(O) { SetUnbuffered(); }
239
240 void reserveExtraSpace(uint64_t ExtraSize) override {
241 OS.reserveExtraSpace(ExtraSize);
242 }
243
244 uint32_t getCRC32() { return CRC32; }
245
246protected:
247 raw_ostream &OS;
248 uint32_t CRC32 = 0;
249
250 /// See raw_ostream::write_impl.
251 void write_impl(const char *Ptr, size_t Size) override {
252 CRC32 = crc32(
253 CRC: CRC32, Data: ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Ptr), Size));
254 OS.write(Ptr, Size);
255 }
256
257 /// Return the current position within the stream, not counting the bytes
258 /// currently in the buffer.
259 uint64_t current_pos() const override { return OS.tell(); }
260};
261
262// Returns the compression type for the linked debug sections. Unless it is
263// specified explicitly, the linked debug sections are compressed using the
264// same format as the input debug sections.
265static Expected<DebugCompressionType>
266getLinkedDebugInfoCompressionType(const Options &Opts, ObjectFile &InputFile) {
267 if (Opts.CompressionType)
268 return *Opts.CompressionType;
269
270 for (SectionRef Sec : InputFile.sections()) {
271 if (!Sec.isCompressed())
272 continue;
273
274 Expected<StringRef> SecName = Sec.getName();
275 if (!SecName)
276 return SecName.takeError();
277 if (!isDebugSection(SecName: *SecName))
278 continue;
279
280 Expected<StringRef> SecData = Sec.getContents();
281 if (!SecData)
282 return SecData.takeError();
283 // ch_type is a 32-bit field at offset 0 of both Elf32_Chdr and Elf64_Chdr.
284 if (SecData->size() < sizeof(uint32_t))
285 continue;
286 uint32_t ChType = InputFile.isLittleEndian()
287 ? support::endian::read32le(P: SecData->data())
288 : support::endian::read32be(P: SecData->data());
289
290 DebugCompressionType CompressionType;
291 switch (ChType) {
292 case ELF::ELFCOMPRESS_ZLIB:
293 CompressionType = DebugCompressionType::Zlib;
294 break;
295 case ELF::ELFCOMPRESS_ZSTD:
296 CompressionType = DebugCompressionType::Zstd;
297 break;
298 default:
299 continue;
300 }
301
302 if (compression::getReasonIfUnsupported(
303 F: compression::formatFor(Type: CompressionType)))
304 continue;
305
306 return CompressionType;
307 }
308
309 return DebugCompressionType::None;
310}
311
312// Executes objcopy. The debug sections copied from the input file are
313// (de)compressed by objcopy as requested by --[no-]compress-debug-sections, or
314// copied as is if the option is not specified. The linked debug sections
315// (Config.AddSection) are compressed using the compression type returned by
316// getLinkedDebugInfoCompressionType().
317static Error executeObjcopyAndCompress(objcopy::ConfigManager &Config,
318 const Options &Opts,
319 ObjectFile &InputFile,
320 raw_ostream &OutFile) {
321 if (Opts.CompressionType == DebugCompressionType::None)
322 Config.Common.DecompressDebugSections = true;
323 else if (Opts.CompressionType)
324 Config.Common.CompressionType = *Opts.CompressionType;
325
326 if (Config.Common.AddSection.empty())
327 return objcopy::executeObjcopyOnBinary(Config, In&: InputFile, Out&: OutFile);
328
329 Expected<DebugCompressionType> CompressionType =
330 getLinkedDebugInfoCompressionType(Opts, InputFile);
331 if (!CompressionType)
332 return CompressionType.takeError();
333 if (*CompressionType == DebugCompressionType::None)
334 return objcopy::executeObjcopyOnBinary(Config, In&: InputFile, Out&: OutFile);
335
336 // objcopy compresses debug sections before adding new ones, thus the linked
337 // debug sections would be left uncompressed. Compress them by running
338 // objcopy on the intermediate result.
339 SmallString<0> Buffer;
340 raw_svector_ostream BufferStream(Buffer);
341 if (Error Err =
342 objcopy::executeObjcopyOnBinary(Config, In&: InputFile, Out&: BufferStream))
343 return Err;
344
345 Expected<std::unique_ptr<ObjectFile>> Obj = ObjectFile::createObjectFile(
346 Object: MemoryBufferRef(Buffer, Config.Common.OutputFilename));
347 if (!Obj)
348 return Obj.takeError();
349
350 objcopy::ConfigManager CompressConfig;
351 CompressConfig.Common.InputFilename = Config.Common.OutputFilename;
352 CompressConfig.Common.OutputFilename = Config.Common.OutputFilename;
353 CompressConfig.Common.CompressionType = *CompressionType;
354 return objcopy::executeObjcopyOnBinary(Config: CompressConfig, In&: **Obj, Out&: OutFile);
355}
356
357static Expected<uint32_t> saveSeparateDebugInfo(const Options &Opts,
358 ObjectFile &InputFile) {
359 objcopy::ConfigManager Config;
360 std::string OutputFilename = Opts.getSeparateDebugFileName();
361 Config.Common.InputFilename = Opts.InputFileName;
362 Config.Common.OutputFilename = OutputFilename;
363 Config.Common.OnlyKeepDebug = true;
364 uint32_t WrittenFileCRC32 = 0;
365
366 if (Error Err = writeToOutput(
367 OutputFileName: Config.Common.OutputFilename, Write: [&](raw_ostream &OutFile) -> Error {
368 raw_crc_ostream CRCBuffer(OutFile);
369 if (Error Err = executeObjcopyAndCompress(Config, Opts, InputFile,
370 OutFile&: CRCBuffer))
371 return Err;
372
373 WrittenFileCRC32 = CRCBuffer.getCRC32();
374 return Error::success();
375 }))
376 return std::move(Err);
377
378 return WrittenFileCRC32;
379}
380
381static Error saveNonDebugInfo(const Options &Opts, ObjectFile &InputFile,
382 uint32_t GnuDebugLinkCRC32) {
383 objcopy::ConfigManager Config;
384 Config.Common.InputFilename = Opts.InputFileName;
385 Config.Common.OutputFilename = Opts.OutputFileName;
386 Config.Common.StripDebug = true;
387 std::string SeparateDebugFileName = Opts.getSeparateDebugFileName();
388 Config.Common.AddGnuDebugLink = sys::path::filename(path: SeparateDebugFileName);
389 Config.Common.GnuDebugLinkCRC32 = GnuDebugLinkCRC32;
390
391 if (Error Err = writeToOutput(
392 OutputFileName: Config.Common.OutputFilename, Write: [&](raw_ostream &OutFile) -> Error {
393 if (Error Err =
394 objcopy::executeObjcopyOnBinary(Config, In&: InputFile, Out&: OutFile))
395 return Err;
396
397 return Error::success();
398 }))
399 return Err;
400
401 return Error::success();
402}
403
404static Error splitDebugIntoSeparateFile(const Options &Opts,
405 ObjectFile &InputFile) {
406 Expected<uint32_t> SeparateDebugFileCRC32OrErr =
407 saveSeparateDebugInfo(Opts, InputFile);
408 if (!SeparateDebugFileCRC32OrErr)
409 return SeparateDebugFileCRC32OrErr.takeError();
410
411 if (Error Err =
412 saveNonDebugInfo(Opts, InputFile, GnuDebugLinkCRC32: *SeparateDebugFileCRC32OrErr))
413 return Err;
414
415 return Error::success();
416}
417
418using DebugInfoBits = SmallString<10000>;
419
420static Error addSectionsFromLinkedData(objcopy::ConfigManager &Config,
421 ObjectFile &InputFile,
422 DebugInfoBits &LinkedDebugInfoBits) {
423 if (isa<ELFObjectFile<ELF32LE>>(Val: &InputFile)) {
424 Expected<ELFObjectFile<ELF32LE>> MemFile = ELFObjectFile<ELF32LE>::create(
425 Object: MemoryBufferRef(LinkedDebugInfoBits, ""));
426 if (!MemFile)
427 return MemFile.takeError();
428
429 if (Error Err = setConfigToAddNewDebugSections(Config, ObjFile&: *MemFile))
430 return Err;
431 } else if (isa<ELFObjectFile<ELF64LE>>(Val: &InputFile)) {
432 Expected<ELFObjectFile<ELF64LE>> MemFile = ELFObjectFile<ELF64LE>::create(
433 Object: MemoryBufferRef(LinkedDebugInfoBits, ""));
434 if (!MemFile)
435 return MemFile.takeError();
436
437 if (Error Err = setConfigToAddNewDebugSections(Config, ObjFile&: *MemFile))
438 return Err;
439 } else if (isa<ELFObjectFile<ELF32BE>>(Val: &InputFile)) {
440 Expected<ELFObjectFile<ELF32BE>> MemFile = ELFObjectFile<ELF32BE>::create(
441 Object: MemoryBufferRef(LinkedDebugInfoBits, ""));
442 if (!MemFile)
443 return MemFile.takeError();
444
445 if (Error Err = setConfigToAddNewDebugSections(Config, ObjFile&: *MemFile))
446 return Err;
447 } else if (isa<ELFObjectFile<ELF64BE>>(Val: &InputFile)) {
448 Expected<ELFObjectFile<ELF64BE>> MemFile = ELFObjectFile<ELF64BE>::create(
449 Object: MemoryBufferRef(LinkedDebugInfoBits, ""));
450 if (!MemFile)
451 return MemFile.takeError();
452
453 if (Error Err = setConfigToAddNewDebugSections(Config, ObjFile&: *MemFile))
454 return Err;
455 } else
456 return createStringError(EC: std::errc::invalid_argument,
457 Fmt: "unsupported file format");
458
459 return Error::success();
460}
461
462static Expected<uint32_t>
463saveSeparateLinkedDebugInfo(const Options &Opts, ObjectFile &InputFile,
464 DebugInfoBits LinkedDebugInfoBits) {
465 objcopy::ConfigManager Config;
466 std::string OutputFilename = Opts.getSeparateDebugFileName();
467 Config.Common.InputFilename = Opts.InputFileName;
468 Config.Common.OutputFilename = OutputFilename;
469 Config.Common.StripDebug = true;
470 Config.Common.OnlyKeepDebug = true;
471 uint32_t WrittenFileCRC32 = 0;
472
473 if (Error Err =
474 addSectionsFromLinkedData(Config, InputFile, LinkedDebugInfoBits))
475 return std::move(Err);
476
477 if (Error Err = writeToOutput(
478 OutputFileName: Config.Common.OutputFilename, Write: [&](raw_ostream &OutFile) -> Error {
479 raw_crc_ostream CRCBuffer(OutFile);
480
481 if (Error Err = executeObjcopyAndCompress(Config, Opts, InputFile,
482 OutFile&: CRCBuffer))
483 return Err;
484
485 WrittenFileCRC32 = CRCBuffer.getCRC32();
486 return Error::success();
487 }))
488 return std::move(Err);
489
490 return WrittenFileCRC32;
491}
492
493static Error saveSingleLinkedDebugInfo(const Options &Opts,
494 ObjectFile &InputFile,
495 DebugInfoBits LinkedDebugInfoBits) {
496 objcopy::ConfigManager Config;
497
498 Config.Common.InputFilename = Opts.InputFileName;
499 Config.Common.OutputFilename = Opts.OutputFileName;
500 Config.Common.StripDebug = true;
501 if (Error Err =
502 addSectionsFromLinkedData(Config, InputFile, LinkedDebugInfoBits))
503 return Err;
504
505 if (Error Err = writeToOutput(
506 OutputFileName: Config.Common.OutputFilename, Write: [&](raw_ostream &OutFile) -> Error {
507 return executeObjcopyAndCompress(Config, Opts, InputFile, OutFile);
508 }))
509 return Err;
510
511 return Error::success();
512}
513
514static Error saveLinkedDebugInfo(const Options &Opts, ObjectFile &InputFile,
515 DebugInfoBits LinkedDebugInfoBits) {
516 if (Opts.BuildSeparateDebugFile) {
517 Expected<uint32_t> SeparateDebugFileCRC32OrErr =
518 saveSeparateLinkedDebugInfo(Opts, InputFile,
519 LinkedDebugInfoBits: std::move(LinkedDebugInfoBits));
520 if (!SeparateDebugFileCRC32OrErr)
521 return SeparateDebugFileCRC32OrErr.takeError();
522
523 if (Error Err =
524 saveNonDebugInfo(Opts, InputFile, GnuDebugLinkCRC32: *SeparateDebugFileCRC32OrErr))
525 return Err;
526 } else {
527 if (Error Err = saveSingleLinkedDebugInfo(Opts, InputFile,
528 LinkedDebugInfoBits: std::move(LinkedDebugInfoBits)))
529 return Err;
530 }
531
532 return Error::success();
533}
534
535static Error saveCopyOfFile(const Options &Opts, ObjectFile &InputFile) {
536 objcopy::ConfigManager Config;
537
538 Config.Common.InputFilename = Opts.InputFileName;
539 Config.Common.OutputFilename = Opts.OutputFileName;
540
541 if (Error Err = writeToOutput(
542 OutputFileName: Config.Common.OutputFilename, Write: [&](raw_ostream &OutFile) -> Error {
543 return executeObjcopyAndCompress(Config, Opts, InputFile, OutFile);
544 }))
545 return Err;
546
547 return Error::success();
548}
549
550static Error applyCLOptions(const struct Options &Opts, ObjectFile &InputFile) {
551 if (Opts.DoGarbageCollection ||
552 Opts.AccelTableKind != DwarfUtilAccelKind::None) {
553 verbose(Message: "Do debug info linking...", Verbose: Opts.Verbose);
554
555 DebugInfoBits LinkedDebugInfo;
556 raw_svector_ostream OutStream(LinkedDebugInfo);
557
558 if (Error Err = linkDebugInfo(file&: InputFile, Options: Opts, OutStream))
559 return Err;
560
561 if (Error Err =
562 saveLinkedDebugInfo(Opts, InputFile, LinkedDebugInfoBits: std::move(LinkedDebugInfo)))
563 return Err;
564
565 return Error::success();
566 } else if (Opts.BuildSeparateDebugFile) {
567 if (Error Err = splitDebugIntoSeparateFile(Opts, InputFile))
568 return Err;
569 } else {
570 if (Error Err = saveCopyOfFile(Opts, InputFile))
571 return Err;
572 }
573
574 return Error::success();
575}
576
577} // end of namespace dwarfutil
578} // end of namespace llvm
579
580int main(int Argc, char const *Argv[]) {
581 using namespace dwarfutil;
582
583 InitLLVM X(Argc, Argv);
584 ToolName = Argv[0];
585
586 // Parse arguments.
587 DwarfutilOptTable T;
588 unsigned MAI;
589 unsigned MAC;
590 ArrayRef<const char *> ArgsArr = ArrayRef(Argv + 1, Argc - 1);
591 opt::InputArgList Args = T.ParseArgs(Args: ArgsArr, MissingArgIndex&: MAI, MissingArgCount&: MAC);
592
593 if (Args.hasArg(Ids: OPT_help) || Args.size() == 0) {
594 T.printHelp(
595 OS&: outs(), Usage: (ToolName + " [options] <input file> <output file>").c_str(),
596 Title: "llvm-dwarfutil is a tool to copy and manipulate debug info", ShowHidden: false);
597 return EXIT_SUCCESS;
598 }
599
600 if (Args.hasArg(Ids: OPT_version)) {
601 cl::PrintVersionMessage();
602 return EXIT_SUCCESS;
603 }
604
605 Options Opts;
606 if (Error Err = validateAndSetOptions(Args, Options&: Opts))
607 error(Err: std::move(Err), Prefix: dwarfutil::ToolName);
608
609 InitializeAllTargets();
610 InitializeAllTargetMCs();
611 InitializeAllTargetInfos();
612 InitializeAllAsmPrinters();
613
614 ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr =
615 MemoryBuffer::getFileOrSTDIN(Filename: Opts.InputFileName);
616 if (BuffOrErr.getError())
617 error(Err: createFileError(F: Opts.InputFileName, EC: BuffOrErr.getError()));
618
619 Expected<std::unique_ptr<Binary>> BinOrErr =
620 object::createBinary(Source: **BuffOrErr);
621 if (!BinOrErr)
622 error(Err: createFileError(F: Opts.InputFileName, E: BinOrErr.takeError()));
623
624 Expected<FilePermissionsApplier> PermsApplierOrErr =
625 FilePermissionsApplier::create(InputFilename: Opts.InputFileName);
626 if (!PermsApplierOrErr)
627 error(Err: createFileError(F: Opts.InputFileName, E: PermsApplierOrErr.takeError()));
628
629 if (!(*BinOrErr)->isObject())
630 error(Err: createFileError(F: Opts.InputFileName,
631 E: createError(Err: "unsupported input file")));
632
633 if (Error Err =
634 applyCLOptions(Opts, InputFile&: *static_cast<ObjectFile *>((*BinOrErr).get())))
635 error(Err: createFileError(F: Opts.InputFileName, E: std::move(Err)));
636
637 BinOrErr->reset();
638 BuffOrErr->reset();
639
640 if (Error Err = PermsApplierOrErr->apply(OutputFilename: Opts.OutputFileName))
641 error(Err: std::move(Err));
642
643 if (Opts.BuildSeparateDebugFile)
644 if (Error Err = PermsApplierOrErr->apply(OutputFilename: Opts.getSeparateDebugFileName()))
645 error(Err: std::move(Err));
646
647 if (Opts.Verify) {
648 if (Error Err = verifyOutput(Opts))
649 error(Err: std::move(Err));
650 }
651
652 return EXIT_SUCCESS;
653}
654