1//===- ELFObjcopy.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 "llvm/ObjCopy/ELF/ELFObjcopy.h"
10#include "ELFObject.h"
11#include "llvm/ADT/BitmaskEnum.h"
12#include "llvm/ADT/DenseSet.h"
13#include "llvm/ADT/SmallVector.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/ADT/Twine.h"
16#include "llvm/BinaryFormat/ELF.h"
17#include "llvm/MC/MCTargetOptions.h"
18#include "llvm/ObjCopy/CommonConfig.h"
19#include "llvm/ObjCopy/ELF/ELFConfig.h"
20#include "llvm/Object/Binary.h"
21#include "llvm/Object/ELFObjectFile.h"
22#include "llvm/Object/ELFTypes.h"
23#include "llvm/Object/Error.h"
24#include "llvm/Option/Option.h"
25#include "llvm/Support/Casting.h"
26#include "llvm/Support/Compression.h"
27#include "llvm/Support/Errc.h"
28#include "llvm/Support/Error.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/Memory.h"
31#include "llvm/Support/raw_ostream.h"
32#include <algorithm>
33#include <cassert>
34#include <cstdlib>
35#include <functional>
36#include <memory>
37#include <string>
38#include <system_error>
39#include <utility>
40
41using namespace llvm;
42using namespace llvm::ELF;
43using namespace llvm::objcopy;
44using namespace llvm::objcopy::elf;
45using namespace llvm::object;
46
47using SectionPred = std::function<bool(const SectionBase &Sec)>;
48
49static bool isDebugSection(const SectionBase &Sec) {
50 return StringRef(Sec.Name).starts_with(Prefix: ".debug") || Sec.Name == ".gdb_index";
51}
52
53static bool isDWOSection(const SectionBase &Sec) {
54 return StringRef(Sec.Name).ends_with(Suffix: ".dwo");
55}
56
57static bool onlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
58 // We can't remove the section header string table.
59 if (&Sec == Obj.SectionNames)
60 return false;
61 // Short of keeping the string table we want to keep everything that is a DWO
62 // section and remove everything else.
63 return !isDWOSection(Sec);
64}
65
66static Expected<uint64_t> getNewShfFlags(SectionFlag AllFlags,
67 uint16_t EMachine) {
68 uint64_t NewFlags = 0;
69 if (AllFlags & SectionFlag::SecAlloc)
70 NewFlags |= ELF::SHF_ALLOC;
71 if (!(AllFlags & SectionFlag::SecReadonly))
72 NewFlags |= ELF::SHF_WRITE;
73 if (AllFlags & SectionFlag::SecCode)
74 NewFlags |= ELF::SHF_EXECINSTR;
75 if (AllFlags & SectionFlag::SecMerge)
76 NewFlags |= ELF::SHF_MERGE;
77 if (AllFlags & SectionFlag::SecStrings)
78 NewFlags |= ELF::SHF_STRINGS;
79 if (AllFlags & SectionFlag::SecExclude)
80 NewFlags |= ELF::SHF_EXCLUDE;
81 if (AllFlags & SectionFlag::SecLarge) {
82 if (EMachine != EM_X86_64)
83 return createStringError(EC: errc::invalid_argument,
84 S: "section flag SHF_X86_64_LARGE can only be used "
85 "with x86_64 architecture");
86 NewFlags |= ELF::SHF_X86_64_LARGE;
87 }
88 return NewFlags;
89}
90
91static uint64_t getSectionFlagsPreserveMask(uint64_t OldFlags,
92 uint64_t NewFlags,
93 uint16_t EMachine) {
94 // Preserve some flags which should not be dropped when setting flags.
95 // Also, preserve anything OS/processor dependant.
96 const uint64_t PreserveMask =
97 (ELF::SHF_COMPRESSED | ELF::SHF_GROUP | ELF::SHF_LINK_ORDER |
98 ELF::SHF_MASKOS | ELF::SHF_MASKPROC | ELF::SHF_TLS |
99 ELF::SHF_INFO_LINK) &
100 ~ELF::SHF_EXCLUDE &
101 ~(EMachine == EM_X86_64 ? (uint64_t)ELF::SHF_X86_64_LARGE : 0UL);
102 return (OldFlags & PreserveMask) | (NewFlags & ~PreserveMask);
103}
104
105static void setSectionType(SectionBase &Sec, uint64_t Type) {
106 // If Sec's type is changed from SHT_NOBITS due to --set-section-flags,
107 // Offset may not be aligned. Align it to max(Align, 1).
108 if (Sec.Type == ELF::SHT_NOBITS && Type != ELF::SHT_NOBITS)
109 Sec.Offset = alignTo(Value: Sec.Offset, Align: std::max(a: Sec.Align, b: uint64_t(1)));
110 Sec.Type = Type;
111}
112
113static Error setSectionFlagsAndType(SectionBase &Sec, SectionFlag Flags,
114 uint16_t EMachine) {
115 Expected<uint64_t> NewFlags = getNewShfFlags(AllFlags: Flags, EMachine);
116 if (!NewFlags)
117 return NewFlags.takeError();
118 Sec.Flags = getSectionFlagsPreserveMask(OldFlags: Sec.Flags, NewFlags: *NewFlags, EMachine);
119
120 // In GNU objcopy, certain flags promote SHT_NOBITS to SHT_PROGBITS. This rule
121 // may promote more non-ALLOC sections than GNU objcopy, but it is fine as
122 // non-ALLOC SHT_NOBITS sections do not make much sense.
123 if (Sec.Type == SHT_NOBITS &&
124 (!(Sec.Flags & ELF::SHF_ALLOC) ||
125 Flags & (SectionFlag::SecContents | SectionFlag::SecLoad)))
126 setSectionType(Sec, Type: ELF::SHT_PROGBITS);
127
128 return Error::success();
129}
130
131static ElfType getOutputElfType(const Binary &Bin) {
132 // Infer output ELF type from the input ELF object
133 if (isa<ELFObjectFile<ELF32LE>>(Val: Bin))
134 return ELFT_ELF32LE;
135 if (isa<ELFObjectFile<ELF64LE>>(Val: Bin))
136 return ELFT_ELF64LE;
137 if (isa<ELFObjectFile<ELF32BE>>(Val: Bin))
138 return ELFT_ELF32BE;
139 if (isa<ELFObjectFile<ELF64BE>>(Val: Bin))
140 return ELFT_ELF64BE;
141 llvm_unreachable("Invalid ELFType");
142}
143
144static ElfType getOutputElfType(const MachineInfo &MI) {
145 // Infer output ELF type from the binary arch specified
146 if (MI.Is64Bit)
147 return MI.IsLittleEndian ? ELFT_ELF64LE : ELFT_ELF64BE;
148 else
149 return MI.IsLittleEndian ? ELFT_ELF32LE : ELFT_ELF32BE;
150}
151
152static std::unique_ptr<Writer> createELFWriter(const CommonConfig &Config,
153 Object &Obj, raw_ostream &Out,
154 ElfType OutputElfType) {
155 // Depending on the initial ELFT and OutputFormat we need a different Writer.
156 switch (OutputElfType) {
157 case ELFT_ELF32LE:
158 return std::make_unique<ELFWriter<ELF32LE>>(args&: Obj, args&: Out, args: !Config.StripSections,
159 args: Config.OnlyKeepDebug);
160 case ELFT_ELF64LE:
161 return std::make_unique<ELFWriter<ELF64LE>>(args&: Obj, args&: Out, args: !Config.StripSections,
162 args: Config.OnlyKeepDebug);
163 case ELFT_ELF32BE:
164 return std::make_unique<ELFWriter<ELF32BE>>(args&: Obj, args&: Out, args: !Config.StripSections,
165 args: Config.OnlyKeepDebug);
166 case ELFT_ELF64BE:
167 return std::make_unique<ELFWriter<ELF64BE>>(args&: Obj, args&: Out, args: !Config.StripSections,
168 args: Config.OnlyKeepDebug);
169 }
170 llvm_unreachable("Invalid output format");
171}
172
173static std::unique_ptr<Writer> createWriter(const CommonConfig &Config,
174 Object &Obj, raw_ostream &Out,
175 ElfType OutputElfType) {
176 switch (Config.OutputFormat) {
177 case FileFormat::Binary:
178 return std::make_unique<BinaryWriter>(args&: Obj, args&: Out, args: Config);
179 case FileFormat::IHex:
180 return std::make_unique<IHexWriter>(args&: Obj, args&: Out, args: Config.OutputFilename);
181 case FileFormat::SREC:
182 return std::make_unique<SRECWriter>(args&: Obj, args&: Out, args: Config.OutputFilename);
183 default:
184 return createELFWriter(Config, Obj, Out, OutputElfType);
185 }
186}
187
188static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
189 StringRef InputFilename, Object &Obj) {
190 for (auto &Sec : Obj.sections()) {
191 if (Sec.Name == SecName) {
192 if (Sec.Type == SHT_NOBITS)
193 return createFileError(F: InputFilename, EC: object_error::parse_failed,
194 Fmt: "cannot dump section '%s': it has no contents",
195 Vals: SecName.str().c_str());
196 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
197 FileOutputBuffer::create(FilePath: Filename, Size: Sec.OriginalData.size());
198 if (!BufferOrErr)
199 return createFileError(F: Filename, E: BufferOrErr.takeError());
200 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
201 llvm::copy(Range&: Sec.OriginalData, Out: Buf->getBufferStart());
202 if (Error E = Buf->commit())
203 return createFileError(F: Filename, E: std::move(E));
204 return Error::success();
205 }
206 }
207
208 return createFileError(F: InputFilename, EC: object_error::parse_failed,
209 Fmt: "section '%s' not found", Vals: SecName.str().c_str());
210}
211
212Error Object::compressOrDecompressSections(const CommonConfig &Config) {
213 // Build a list of sections we are going to replace.
214 // We can't call `addSection` while iterating over sections,
215 // because it would mutate the sections array.
216 SmallVector<std::pair<SectionBase *, std::function<SectionBase *()>>, 0>
217 ToReplace;
218 for (SectionBase &Sec : sections()) {
219 std::optional<DebugCompressionType> CType;
220 for (auto &[Matcher, T] : Config.compressSections)
221 if (Matcher.matches(S: Sec.Name))
222 CType = T;
223 // Handle --compress-debug-sections and --decompress-debug-sections, which
224 // apply to non-ALLOC debug sections.
225 if (!(Sec.Flags & SHF_ALLOC) && StringRef(Sec.Name).starts_with(Prefix: ".debug")) {
226 if (Config.CompressionType != DebugCompressionType::None)
227 CType = Config.CompressionType;
228 else if (Config.DecompressDebugSections)
229 CType = DebugCompressionType::None;
230 }
231 if (!CType)
232 continue;
233
234 if (Sec.ParentSegment)
235 return createStringError(
236 EC: errc::invalid_argument,
237 S: "section '" + Sec.Name +
238 "' within a segment cannot be (de)compressed");
239
240 if (auto *CS = dyn_cast<CompressedSection>(Val: &Sec)) {
241 if (*CType == DebugCompressionType::None)
242 ToReplace.emplace_back(
243 Args: &Sec, Args: [=] { return &addSection<DecompressedSection>(Args&: *CS); });
244 } else if (*CType != DebugCompressionType::None) {
245 ToReplace.emplace_back(Args: &Sec, Args: [=, S = &Sec] {
246 return &addSection<CompressedSection>(
247 Args: CompressedSection(*S, *CType, Is64Bits));
248 });
249 }
250 }
251
252 DenseMap<SectionBase *, SectionBase *> FromTo;
253 for (auto [S, Func] : ToReplace)
254 FromTo[S] = Func();
255 return replaceSections(FromTo);
256}
257
258static bool isAArch64MappingSymbol(const Symbol &Sym) {
259 if (Sym.Binding != STB_LOCAL || Sym.Type != STT_NOTYPE ||
260 Sym.getShndx() == SHN_UNDEF)
261 return false;
262 StringRef Name = Sym.Name;
263 if (!Name.consume_front(Prefix: "$x") && !Name.consume_front(Prefix: "$d"))
264 return false;
265 return Name.empty() || Name.starts_with(Prefix: ".");
266}
267
268static bool isArmMappingSymbol(const Symbol &Sym) {
269 if (Sym.Binding != STB_LOCAL || Sym.Type != STT_NOTYPE ||
270 Sym.getShndx() == SHN_UNDEF)
271 return false;
272 StringRef Name = Sym.Name;
273 if (!Name.consume_front(Prefix: "$a") && !Name.consume_front(Prefix: "$d") &&
274 !Name.consume_front(Prefix: "$t"))
275 return false;
276 return Name.empty() || Name.starts_with(Prefix: ".");
277}
278
279// Check if the symbol should be preserved because it is required by ABI.
280static bool isRequiredByABISymbol(const Object &Obj, const Symbol &Sym) {
281 switch (Obj.Machine) {
282 case EM_AARCH64:
283 // Mapping symbols should be preserved for a relocatable object file.
284 return Obj.isRelocatable() && isAArch64MappingSymbol(Sym);
285 case EM_ARM:
286 // Mapping symbols should be preserved for a relocatable object file.
287 return Obj.isRelocatable() && isArmMappingSymbol(Sym);
288 default:
289 return false;
290 }
291}
292
293static bool isUnneededSymbol(const Symbol &Sym) {
294 return !Sym.Referenced &&
295 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
296 Sym.Type != STT_SECTION;
297}
298
299static Error updateAndRemoveSymbols(const CommonConfig &Config,
300 const ELFConfig &ELFConfig, Object &Obj) {
301 // TODO: update or remove symbols only if there is an option that affects
302 // them.
303 if (!Obj.SymbolTable)
304 return Error::success();
305
306 Obj.SymbolTable->updateSymbols(Callable: [&](Symbol &Sym) {
307 if (Config.SymbolsToSkip.matches(S: Sym.Name))
308 return;
309
310 // Common and undefined symbols don't make sense as local symbols, and can
311 // even cause crashes if we localize those, so skip them.
312 if (!Sym.isCommon() && Sym.getShndx() != SHN_UNDEF &&
313 ((ELFConfig.LocalizeHidden &&
314 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
315 Config.SymbolsToLocalize.matches(S: Sym.Name)))
316 Sym.Binding = STB_LOCAL;
317
318 for (auto &[Matcher, Visibility] : ELFConfig.SymbolsToSetVisibility)
319 if (Matcher.matches(S: Sym.Name))
320 Sym.Visibility = Visibility;
321
322 // Note: these two globalize flags have very similar names but different
323 // meanings:
324 //
325 // --globalize-symbol: promote a symbol to global
326 // --keep-global-symbol: all symbols except for these should be made local
327 //
328 // If --globalize-symbol is specified for a given symbol, it will be
329 // global in the output file even if it is not included via
330 // --keep-global-symbol. Because of that, make sure to check
331 // --globalize-symbol second.
332 if (!Config.SymbolsToKeepGlobal.empty() &&
333 !Config.SymbolsToKeepGlobal.matches(S: Sym.Name) &&
334 Sym.getShndx() != SHN_UNDEF)
335 Sym.Binding = STB_LOCAL;
336
337 if (Config.SymbolsToGlobalize.matches(S: Sym.Name) &&
338 Sym.getShndx() != SHN_UNDEF)
339 Sym.Binding = STB_GLOBAL;
340
341 // SymbolsToWeaken applies to both STB_GLOBAL and STB_GNU_UNIQUE.
342 if (Config.SymbolsToWeaken.matches(S: Sym.Name) && Sym.Binding != STB_LOCAL)
343 Sym.Binding = STB_WEAK;
344
345 if (Config.Weaken && Sym.Binding != STB_LOCAL &&
346 Sym.getShndx() != SHN_UNDEF)
347 Sym.Binding = STB_WEAK;
348
349 const auto I = Config.SymbolsToRename.find(Key: Sym.Name);
350 if (I != Config.SymbolsToRename.end())
351 Sym.Name = std::string(I->getValue());
352
353 if (!Config.SymbolsPrefixRemove.empty() && Sym.Type != STT_SECTION)
354 if (StringRef(Sym.Name).starts_with(Prefix: Config.SymbolsPrefixRemove))
355 Sym.Name = Sym.Name.substr(pos: Config.SymbolsPrefixRemove.size());
356
357 if (!Config.SymbolsPrefix.empty() && Sym.Type != STT_SECTION)
358 Sym.Name = (Config.SymbolsPrefix + Sym.Name).str();
359 });
360
361 // The purpose of this loop is to mark symbols referenced by sections
362 // (like GroupSection or RelocationSection). This way, we know which
363 // symbols are still 'needed' and which are not.
364 if (Config.StripUnneeded || !Config.UnneededSymbolsToRemove.empty() ||
365 !Config.OnlySection.empty() || Config.DiscardMode != DiscardType::None) {
366 for (SectionBase &Sec : Obj.sections())
367 Sec.markSymbols();
368 }
369
370 auto RemoveSymbolsPred = [&](const Symbol &Sym) {
371 if (Config.SymbolsToKeep.matches(S: Sym.Name) ||
372 (ELFConfig.KeepFileSymbols && Sym.Type == STT_FILE))
373 return false;
374
375 if (Config.SymbolsToRemove.matches(S: Sym.Name))
376 return true;
377
378 if (Config.StripAll || Config.StripAllGNU)
379 return true;
380
381 if (isRequiredByABISymbol(Obj, Sym))
382 return false;
383
384 if (Config.StripDebug && Sym.Type == STT_FILE)
385 return true;
386
387 if ((Config.StripUnneeded ||
388 Config.UnneededSymbolsToRemove.matches(S: Sym.Name)) &&
389 (!Obj.isRelocatable() || isUnneededSymbol(Sym)))
390 return true;
391
392 if (!Sym.Referenced) {
393 if ((Config.DiscardMode == DiscardType::All ||
394 (Config.DiscardMode == DiscardType::Locals &&
395 StringRef(Sym.Name).starts_with(Prefix: ".L"))) &&
396 Sym.Binding == STB_LOCAL && Sym.getShndx() != SHN_UNDEF &&
397 Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
398 return true;
399 // We want to remove undefined symbols if all references have been
400 // stripped.
401 if (!Config.OnlySection.empty() && Sym.getShndx() == SHN_UNDEF)
402 return true;
403 }
404
405 return false;
406 };
407
408 return Obj.removeSymbols(ToRemove: RemoveSymbolsPred);
409}
410
411static Error replaceAndRemoveSections(const CommonConfig &Config,
412 const ELFConfig &ELFConfig, Object &Obj) {
413 SectionPred RemovePred = [](const SectionBase &) { return false; };
414
415 // Removes:
416 if (!Config.ToRemove.empty()) {
417 RemovePred = [&Config](const SectionBase &Sec) {
418 return Config.ToRemove.matches(S: Sec.Name);
419 };
420 }
421
422 if (Config.StripDWO)
423 RemovePred = [RemovePred](const SectionBase &Sec) {
424 return isDWOSection(Sec) || RemovePred(Sec);
425 };
426
427 if (Config.ExtractDWO)
428 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
429 return onlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
430 };
431
432 if (Config.StripAllGNU)
433 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
434 if (RemovePred(Sec))
435 return true;
436 if ((Sec.Flags & SHF_ALLOC) != 0)
437 return false;
438 if (&Sec == Obj.SectionNames)
439 return false;
440 switch (Sec.Type) {
441 case SHT_SYMTAB:
442 case SHT_REL:
443 case SHT_RELA:
444 case SHT_STRTAB:
445 return true;
446 }
447 return isDebugSection(Sec);
448 };
449
450 if (Config.StripSections) {
451 RemovePred = [RemovePred](const SectionBase &Sec) {
452 return RemovePred(Sec) || Sec.ParentSegment == nullptr;
453 };
454 }
455
456 if (Config.StripDebug || Config.StripUnneeded) {
457 RemovePred = [RemovePred](const SectionBase &Sec) {
458 return RemovePred(Sec) || isDebugSection(Sec);
459 };
460 }
461
462 if (Config.StripNonAlloc)
463 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
464 if (RemovePred(Sec))
465 return true;
466 if (&Sec == Obj.SectionNames)
467 return false;
468 return (Sec.Flags & SHF_ALLOC) == 0 && Sec.ParentSegment == nullptr;
469 };
470
471 if (Config.StripAll)
472 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
473 if (RemovePred(Sec))
474 return true;
475 if (&Sec == Obj.SectionNames)
476 return false;
477 if (StringRef(Sec.Name).starts_with(Prefix: ".gnu.warning"))
478 return false;
479 if (StringRef(Sec.Name).starts_with(Prefix: ".gnu_debuglink"))
480 return false;
481 // We keep the .ARM.attribute section to maintain compatibility
482 // with Debian derived distributions. This is a bug in their
483 // patchset as documented here:
484 // https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=943798
485 if (Sec.Type == SHT_ARM_ATTRIBUTES)
486 return false;
487 if (Sec.ParentSegment != nullptr)
488 return false;
489 return (Sec.Flags & SHF_ALLOC) == 0;
490 };
491
492 if (Config.ExtractPartition || Config.ExtractMainPartition) {
493 RemovePred = [RemovePred](const SectionBase &Sec) {
494 if (RemovePred(Sec))
495 return true;
496 if (Sec.Type == SHT_LLVM_PART_EHDR || Sec.Type == SHT_LLVM_PART_PHDR)
497 return true;
498 return (Sec.Flags & SHF_ALLOC) != 0 && !Sec.ParentSegment;
499 };
500 }
501
502 // Explicit copies:
503 if (!Config.OnlySection.empty()) {
504 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
505 // Explicitly keep these sections regardless of previous removes.
506 if (Config.OnlySection.matches(S: Sec.Name))
507 return false;
508
509 // Allow all implicit removes.
510 if (RemovePred(Sec))
511 return true;
512
513 // Keep special sections.
514 if (Obj.SectionNames == &Sec)
515 return false;
516 if (Obj.SymbolTable == &Sec ||
517 (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
518 return false;
519
520 // Remove everything else.
521 return true;
522 };
523 }
524
525 if (!Config.KeepSection.empty()) {
526 RemovePred = [&Config, RemovePred](const SectionBase &Sec) {
527 // Explicitly keep these sections regardless of previous removes.
528 if (Config.KeepSection.matches(S: Sec.Name))
529 return false;
530 // Otherwise defer to RemovePred.
531 return RemovePred(Sec);
532 };
533 }
534
535 // This has to be the last predicate assignment.
536 // If the option --keep-symbol has been specified
537 // and at least one of those symbols is present
538 // (equivalently, the updated symbol table is not empty)
539 // the symbol table and the string table should not be removed.
540 if ((!Config.SymbolsToKeep.empty() || ELFConfig.KeepFileSymbols) &&
541 Obj.SymbolTable && !Obj.SymbolTable->empty()) {
542 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
543 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
544 return false;
545 return RemovePred(Sec);
546 };
547 }
548
549 if (Error E = Obj.removeSections(AllowBrokenLinks: ELFConfig.AllowBrokenLinks, ToRemove: RemovePred))
550 return E;
551
552 if (Error E = Obj.compressOrDecompressSections(Config))
553 return E;
554
555 return Error::success();
556}
557
558// Add symbol to the Object symbol table with the specified properties.
559static void addSymbol(Object &Obj, const NewSymbolInfo &SymInfo,
560 uint8_t DefaultVisibility) {
561 SectionBase *Sec = Obj.findSection(Name: SymInfo.SectionName);
562 uint64_t Value = Sec ? Sec->Addr + SymInfo.Value : SymInfo.Value;
563
564 uint8_t Bind = ELF::STB_GLOBAL;
565 uint8_t Type = ELF::STT_NOTYPE;
566 uint8_t Visibility = DefaultVisibility;
567
568 for (SymbolFlag FlagValue : SymInfo.Flags)
569 switch (FlagValue) {
570 case SymbolFlag::Global:
571 Bind = ELF::STB_GLOBAL;
572 break;
573 case SymbolFlag::Local:
574 Bind = ELF::STB_LOCAL;
575 break;
576 case SymbolFlag::Weak:
577 Bind = ELF::STB_WEAK;
578 break;
579 case SymbolFlag::Default:
580 Visibility = ELF::STV_DEFAULT;
581 break;
582 case SymbolFlag::Hidden:
583 Visibility = ELF::STV_HIDDEN;
584 break;
585 case SymbolFlag::Protected:
586 Visibility = ELF::STV_PROTECTED;
587 break;
588 case SymbolFlag::File:
589 Type = ELF::STT_FILE;
590 break;
591 case SymbolFlag::Section:
592 Type = ELF::STT_SECTION;
593 break;
594 case SymbolFlag::Object:
595 Type = ELF::STT_OBJECT;
596 break;
597 case SymbolFlag::Function:
598 Type = ELF::STT_FUNC;
599 break;
600 case SymbolFlag::IndirectFunction:
601 Type = ELF::STT_GNU_IFUNC;
602 break;
603 default: /* Other flag values are ignored for ELF. */
604 break;
605 };
606
607 Obj.SymbolTable->addSymbol(
608 Name: SymInfo.SymbolName, Bind, Type, DefinedIn: Sec, Value, Visibility,
609 Shndx: Sec ? (uint16_t)SYMBOL_SIMPLE_INDEX : (uint16_t)SHN_ABS, SymbolSize: 0);
610}
611
612namespace {
613struct RemoveNoteDetail {
614 struct DeletedRange {
615 uint64_t OldFrom;
616 uint64_t OldTo;
617 };
618
619 template <class ELFT>
620 static std::vector<DeletedRange>
621 findNotesToRemove(ArrayRef<uint8_t> Data, size_t Align,
622 ArrayRef<RemoveNoteInfo> NotesToRemove);
623 static std::vector<uint8_t> updateData(ArrayRef<uint8_t> OldData,
624 ArrayRef<DeletedRange> ToRemove);
625};
626} // namespace
627
628template <class ELFT>
629std::vector<RemoveNoteDetail::DeletedRange>
630RemoveNoteDetail::findNotesToRemove(ArrayRef<uint8_t> Data, size_t Align,
631 ArrayRef<RemoveNoteInfo> NotesToRemove) {
632 using Elf_Nhdr = typename ELFT::Nhdr;
633 using Elf_Note = typename ELFT::Note;
634 std::vector<DeletedRange> ToRemove;
635 uint64_t CurPos = 0;
636 while (CurPos + sizeof(Elf_Nhdr) <= Data.size()) {
637 auto Nhdr = reinterpret_cast<const Elf_Nhdr *>(Data.data() + CurPos);
638 size_t FullSize = Nhdr->getSize(Align);
639 if (CurPos + FullSize > Data.size())
640 break;
641 Elf_Note Note(*Nhdr);
642 bool ShouldRemove =
643 llvm::any_of(NotesToRemove, [&Note](const RemoveNoteInfo &NoteInfo) {
644 return NoteInfo.TypeId == Note.getType() &&
645 (NoteInfo.Name.empty() || NoteInfo.Name == Note.getName());
646 });
647 if (ShouldRemove)
648 ToRemove.push_back(x: {.OldFrom: CurPos, .OldTo: CurPos + FullSize});
649 CurPos += FullSize;
650 }
651 return ToRemove;
652}
653
654std::vector<uint8_t>
655RemoveNoteDetail::updateData(ArrayRef<uint8_t> OldData,
656 ArrayRef<DeletedRange> ToRemove) {
657 std::vector<uint8_t> NewData;
658 NewData.reserve(n: OldData.size());
659 uint64_t CurPos = 0;
660 for (const DeletedRange &RemRange : ToRemove) {
661 if (CurPos < RemRange.OldFrom) {
662 auto Slice = OldData.slice(N: CurPos, M: RemRange.OldFrom - CurPos);
663 llvm::append_range(C&: NewData, R&: Slice);
664 }
665 CurPos = RemRange.OldTo;
666 }
667 if (CurPos < OldData.size()) {
668 auto Slice = OldData.slice(N: CurPos);
669 llvm::append_range(C&: NewData, R&: Slice);
670 }
671 return NewData;
672}
673
674static Error removeNotes(Object &Obj, endianness Endianness,
675 ArrayRef<RemoveNoteInfo> NotesToRemove,
676 function_ref<Error(Error)> ErrorCallback) {
677 // TODO: Support note segments.
678 if (ErrorCallback) {
679 for (Segment &Seg : Obj.segments()) {
680 if (Seg.Type == PT_NOTE) {
681 if (Error E = ErrorCallback(createStringError(
682 EC: errc::not_supported, S: "note segments are not supported")))
683 return E;
684 break;
685 }
686 }
687 }
688
689 // updateSectionData below can reallocate the object sections, invalidating
690 // range-for iterators.
691 SmallVector<SectionBase *, 8> NoteSections;
692 for (auto &Sec : Obj.sections()) {
693 if (Sec.Type == SHT_NOTE && Sec.hasContents())
694 NoteSections.push_back(Elt: &Sec);
695 }
696
697 for (SectionBase *Sec : NoteSections) {
698 // TODO: Support note sections in segments.
699 if (Sec->ParentSegment) {
700 if (ErrorCallback)
701 if (Error E = ErrorCallback(createStringError(
702 EC: errc::not_supported,
703 S: "cannot remove note(s) from " + Sec->Name +
704 ": sections in segments are not supported")))
705 return E;
706 continue;
707 }
708 ArrayRef<uint8_t> OldData = Sec->getContents();
709 size_t Align = std::max<size_t>(a: 4, b: Sec->Align);
710 // Note: notes for both 32-bit and 64-bit ELF files use 4-byte words in the
711 // header, so the parsers are the same.
712 auto ToRemove = (Endianness == endianness::little)
713 ? RemoveNoteDetail::findNotesToRemove<ELF64LE>(
714 Data: OldData, Align, NotesToRemove)
715 : RemoveNoteDetail::findNotesToRemove<ELF64BE>(
716 Data: OldData, Align, NotesToRemove);
717 if (!ToRemove.empty()) {
718 if (Error E = Obj.updateSectionData(
719 S&: *Sec, Data: RemoveNoteDetail::updateData(OldData, ToRemove)))
720 return E;
721 }
722 }
723 return Error::success();
724}
725
726static Error
727handleUserSection(const NewSectionInfo &NewSection,
728 function_ref<Error(StringRef, ArrayRef<uint8_t>)> F) {
729 ArrayRef<uint8_t> Data(reinterpret_cast<const uint8_t *>(
730 NewSection.SectionData->getBufferStart()),
731 NewSection.SectionData->getBufferSize());
732 return F(NewSection.SectionName, Data);
733}
734
735static Error verifyNoteSection(StringRef Name, endianness Endianness,
736 ArrayRef<uint8_t> Data) {
737 // An ELF note has the following structure:
738 // Name Size: 4 bytes (integer)
739 // Desc Size: 4 bytes (integer)
740 // Type : 4 bytes
741 // Name : variable size, padded to a 4 byte boundary
742 // Desc : variable size, padded to a 4 byte boundary
743
744 if (Data.empty())
745 return Error::success();
746
747 if (Data.size() < 12) {
748 std::string msg;
749 raw_string_ostream(msg)
750 << Name << " data must be either empty or at least 12 bytes long";
751 return createStringError(EC: errc::invalid_argument, S: msg);
752 }
753 if (Data.size() % 4 != 0) {
754 std::string msg;
755 raw_string_ostream(msg)
756 << Name << " data size must be a multiple of 4 bytes";
757 return createStringError(EC: errc::invalid_argument, S: msg);
758 }
759 ArrayRef<uint8_t> NameSize = Data.slice(N: 0, M: 4);
760 ArrayRef<uint8_t> DescSize = Data.slice(N: 4, M: 4);
761
762 uint32_t NameSizeValue = support::endian::read32(P: NameSize.data(), E: Endianness);
763 uint32_t DescSizeValue = support::endian::read32(P: DescSize.data(), E: Endianness);
764
765 uint64_t ExpectedDataSize =
766 /*NameSize=*/4 + /*DescSize=*/4 + /*Type=*/4 +
767 /*Name=*/alignTo(Value: NameSizeValue, Align: 4) +
768 /*Desc=*/alignTo(Value: DescSizeValue, Align: 4);
769 uint64_t ActualDataSize = Data.size();
770 if (ActualDataSize != ExpectedDataSize) {
771 std::string msg;
772 raw_string_ostream(msg)
773 << Name
774 << " data size is incompatible with the content of "
775 "the name and description size fields:"
776 << " expecting " << ExpectedDataSize << ", found " << ActualDataSize;
777 return createStringError(EC: errc::invalid_argument, S: msg);
778 }
779
780 return Error::success();
781}
782
783// This function handles the high level operations of GNU objcopy including
784// handling command line options. It's important to outline certain properties
785// we expect to hold of the command line operations. Any operation that "keeps"
786// should keep regardless of a remove. Additionally any removal should respect
787// any previous removals. Lastly whether or not something is removed shouldn't
788// depend a) on the order the options occur in or b) on some opaque priority
789// system. The only priority is that keeps/copies overrule removes.
790static Error handleArgs(const CommonConfig &Config, const ELFConfig &ELFConfig,
791 ElfType OutputElfType, Object &Obj) {
792 if (Config.OutputArch) {
793 Obj.Machine = Config.OutputArch->EMachine;
794 Obj.OSABI = Config.OutputArch->OSABI;
795 }
796
797 if (!Config.SplitDWO.empty() && Config.ExtractDWO) {
798 return Obj.removeSections(
799 AllowBrokenLinks: ELFConfig.AllowBrokenLinks,
800 ToRemove: [&Obj](const SectionBase &Sec) { return onlyKeepDWOPred(Obj, Sec); });
801 }
802
803 // Dump sections before add/remove for compatibility with GNU objcopy.
804 for (StringRef Flag : Config.DumpSection) {
805 StringRef SectionName;
806 StringRef FileName;
807 std::tie(args&: SectionName, args&: FileName) = Flag.split(Separator: '=');
808 if (Error E =
809 dumpSectionToFile(SecName: SectionName, Filename: FileName, InputFilename: Config.InputFilename, Obj))
810 return E;
811 }
812
813 // It is important to remove the sections first. For example, we want to
814 // remove the relocation sections before removing the symbols. That allows
815 // us to avoid reporting the inappropriate errors about removing symbols
816 // named in relocations.
817 if (Error E = replaceAndRemoveSections(Config, ELFConfig, Obj))
818 return createFileError(F: Config.InputFilename, E: std::move(E));
819
820 if (Error E = updateAndRemoveSymbols(Config, ELFConfig, Obj))
821 return createFileError(F: Config.InputFilename, E: std::move(E));
822
823 if (!Config.SetSectionAlignment.empty()) {
824 for (SectionBase &Sec : Obj.sections()) {
825 auto I = Config.SetSectionAlignment.find(Key: Sec.Name);
826 if (I != Config.SetSectionAlignment.end())
827 Sec.Align = I->second;
828 }
829 }
830
831 if (Config.ChangeSectionLMAValAll != 0) {
832 for (Segment &Seg : Obj.segments()) {
833 if (Seg.MemSize > 0) {
834 if (Config.ChangeSectionLMAValAll > 0 &&
835 Seg.PAddr > std::numeric_limits<uint64_t>::max() -
836 Config.ChangeSectionLMAValAll) {
837 return createFileError(
838 F: Config.InputFilename, EC: errc::invalid_argument,
839 S: "address 0x" + Twine::utohexstr(Val: Seg.PAddr) +
840 " cannot be increased by 0x" +
841 Twine::utohexstr(Val: Config.ChangeSectionLMAValAll) +
842 ". The result would overflow");
843 } else if (Config.ChangeSectionLMAValAll < 0 &&
844 Seg.PAddr < std::numeric_limits<uint64_t>::min() -
845 Config.ChangeSectionLMAValAll) {
846 return createFileError(
847 F: Config.InputFilename, EC: errc::invalid_argument,
848 S: "address 0x" + Twine::utohexstr(Val: Seg.PAddr) +
849 " cannot be decreased by 0x" +
850 Twine::utohexstr(Val: std::abs(i: Config.ChangeSectionLMAValAll)) +
851 ". The result would underflow");
852 }
853 Seg.PAddr += Config.ChangeSectionLMAValAll;
854 }
855 }
856 }
857
858 if (!Config.ChangeSectionAddress.empty()) {
859 if (Obj.Type != ELF::ET_REL)
860 return createFileError(
861 F: Config.InputFilename, EC: object_error::invalid_file_type,
862 Fmt: "cannot change section address in a non-relocatable file");
863 StringMap<AddressUpdate> SectionsToUpdateAddress;
864 for (const SectionPatternAddressUpdate &PatternUpdate :
865 reverse(C: Config.ChangeSectionAddress)) {
866 for (SectionBase &Sec : Obj.sections()) {
867 if (PatternUpdate.SectionPattern.matches(S: Sec.Name) &&
868 SectionsToUpdateAddress.try_emplace(Key: Sec.Name, Args: PatternUpdate.Update)
869 .second) {
870 if (PatternUpdate.Update.Kind == AdjustKind::Subtract &&
871 Sec.Addr < PatternUpdate.Update.Value) {
872 return createFileError(
873 F: Config.InputFilename, EC: errc::invalid_argument,
874 S: "address 0x" + Twine::utohexstr(Val: Sec.Addr) +
875 " cannot be decreased by 0x" +
876 Twine::utohexstr(Val: PatternUpdate.Update.Value) +
877 ". The result would underflow");
878 }
879 if (PatternUpdate.Update.Kind == AdjustKind::Add &&
880 Sec.Addr > std::numeric_limits<uint64_t>::max() -
881 PatternUpdate.Update.Value) {
882 return createFileError(
883 F: Config.InputFilename, EC: errc::invalid_argument,
884 S: "address 0x" + Twine::utohexstr(Val: Sec.Addr) +
885 " cannot be increased by 0x" +
886 Twine::utohexstr(Val: PatternUpdate.Update.Value) +
887 ". The result would overflow");
888 }
889
890 switch (PatternUpdate.Update.Kind) {
891 case (AdjustKind::Set):
892 Sec.Addr = PatternUpdate.Update.Value;
893 break;
894 case (AdjustKind::Subtract):
895 Sec.Addr -= PatternUpdate.Update.Value;
896 break;
897 case (AdjustKind::Add):
898 Sec.Addr += PatternUpdate.Update.Value;
899 break;
900 }
901 }
902 }
903 }
904 }
905
906 if (Config.OnlyKeepDebug)
907 for (auto &Sec : Obj.sections())
908 if (Sec.Flags & SHF_ALLOC && Sec.Type != SHT_NOTE)
909 Sec.Type = SHT_NOBITS;
910
911 endianness E = OutputElfType == ELFT_ELF32LE || OutputElfType == ELFT_ELF64LE
912 ? endianness::little
913 : endianness::big;
914
915 if (!ELFConfig.NotesToRemove.empty()) {
916 if (Error Err =
917 removeNotes(Obj, Endianness: E, NotesToRemove: ELFConfig.NotesToRemove, ErrorCallback: Config.ErrorCallback))
918 return createFileError(F: Config.InputFilename, E: std::move(Err));
919 }
920
921 for (const NewSectionInfo &AddedSection : Config.AddSection) {
922 auto AddSection = [&](StringRef Name, ArrayRef<uint8_t> Data) -> Error {
923 OwnedDataSection &NewSection =
924 Obj.addSection<OwnedDataSection>(Args&: Name, Args&: Data);
925 if (Name.starts_with(Prefix: ".note") && Name != ".note.GNU-stack") {
926 NewSection.Type = SHT_NOTE;
927 if (ELFConfig.VerifyNoteSections)
928 return verifyNoteSection(Name, Endianness: E, Data);
929 }
930 return Error::success();
931 };
932 if (Error E = handleUserSection(NewSection: AddedSection, F: AddSection))
933 return createFileError(F: Config.InputFilename, E: std::move(E));
934 }
935
936 for (const NewSectionInfo &NewSection : Config.UpdateSection) {
937 auto UpdateSection = [&](StringRef Name, ArrayRef<uint8_t> Data) {
938 return Obj.updateSection(Name, Data);
939 };
940 if (Error E = handleUserSection(NewSection, F: UpdateSection))
941 return createFileError(F: Config.InputFilename, E: std::move(E));
942 }
943
944 if (!Config.AddGnuDebugLink.empty())
945 Obj.addSection<GnuDebugLinkSection>(Args: Config.AddGnuDebugLink,
946 Args: Config.GnuDebugLinkCRC32);
947
948 // If the symbol table was previously removed, we need to create a new one
949 // before adding new symbols.
950 if (!Obj.SymbolTable && !Config.SymbolsToAdd.empty())
951 if (Error E = Obj.addNewSymbolTable())
952 return createFileError(F: Config.InputFilename, E: std::move(E));
953
954 for (const NewSymbolInfo &SI : Config.SymbolsToAdd)
955 addSymbol(Obj, SymInfo: SI, DefaultVisibility: ELFConfig.NewSymbolVisibility);
956
957 // --set-section-{flags,type} work with sections added by --add-section.
958 if (!Config.SetSectionFlags.empty() || !Config.SetSectionType.empty()) {
959 for (auto &Sec : Obj.sections()) {
960 const auto Iter = Config.SetSectionFlags.find(Key: Sec.Name);
961 if (Iter != Config.SetSectionFlags.end()) {
962 const SectionFlagsUpdate &SFU = Iter->second;
963 if (Error E = setSectionFlagsAndType(Sec, Flags: SFU.NewFlags, EMachine: Obj.Machine))
964 return createFileError(F: Config.InputFilename, E: std::move(E));
965 }
966 auto It2 = Config.SetSectionType.find(Key: Sec.Name);
967 if (It2 != Config.SetSectionType.end())
968 setSectionType(Sec, Type: It2->second);
969 }
970 }
971
972 if (!Config.SectionsToRename.empty()) {
973 std::vector<RelocationSectionBase *> RelocSections;
974 DenseSet<SectionBase *> RenamedSections;
975 for (SectionBase &Sec : Obj.sections()) {
976 auto *RelocSec = dyn_cast<RelocationSectionBase>(Val: &Sec);
977 const auto Iter = Config.SectionsToRename.find(Key: Sec.Name);
978 if (Iter != Config.SectionsToRename.end()) {
979 const SectionRename &SR = Iter->second;
980 Sec.Name = std::string(SR.NewName);
981 if (SR.NewFlags) {
982 if (Error E = setSectionFlagsAndType(Sec, Flags: *SR.NewFlags, EMachine: Obj.Machine))
983 return createFileError(F: Config.InputFilename, E: std::move(E));
984 }
985 RenamedSections.insert(V: &Sec);
986 } else if (RelocSec && !(Sec.Flags & SHF_ALLOC))
987 // Postpone processing relocation sections which are not specified in
988 // their explicit '--rename-section' commands until after their target
989 // sections are renamed.
990 // Dynamic relocation sections (i.e. ones with SHF_ALLOC) should be
991 // renamed only explicitly. Otherwise, renaming, for example, '.got.plt'
992 // would affect '.rela.plt', which is not desirable.
993 RelocSections.push_back(x: RelocSec);
994 }
995
996 // Rename relocation sections according to their target sections.
997 for (RelocationSectionBase *RelocSec : RelocSections) {
998 auto Iter = RenamedSections.find(V: RelocSec->getSection());
999 if (Iter != RenamedSections.end())
1000 RelocSec->Name = (RelocSec->getNamePrefix() + (*Iter)->Name).str();
1001 }
1002 }
1003
1004 // Add a prefix to allocated sections and their relocation sections. This
1005 // should be done after renaming the section by Config.SectionToRename to
1006 // imitate the GNU objcopy behavior.
1007 if (!Config.AllocSectionsPrefix.empty()) {
1008 DenseSet<SectionBase *> PrefixedSections;
1009 for (SectionBase &Sec : Obj.sections()) {
1010 if (Sec.Flags & SHF_ALLOC) {
1011 Sec.Name = (Config.AllocSectionsPrefix + Sec.Name).str();
1012 PrefixedSections.insert(V: &Sec);
1013 } else if (auto *RelocSec = dyn_cast<RelocationSectionBase>(Val: &Sec)) {
1014 // Rename relocation sections associated to the allocated sections.
1015 // For example, if we rename .text to .prefix.text, we also rename
1016 // .rel.text to .rel.prefix.text.
1017 //
1018 // Dynamic relocation sections (SHT_REL[A] with SHF_ALLOC) are handled
1019 // above, e.g., .rela.plt is renamed to .prefix.rela.plt, not
1020 // .rela.prefix.plt since GNU objcopy does so.
1021 const SectionBase *TargetSec = RelocSec->getSection();
1022 if (TargetSec && (TargetSec->Flags & SHF_ALLOC)) {
1023 // If the relocation section comes *after* the target section, we
1024 // don't add Config.AllocSectionsPrefix because we've already added
1025 // the prefix to TargetSec->Name. Otherwise, if the relocation
1026 // section comes *before* the target section, we add the prefix.
1027 if (PrefixedSections.count(V: TargetSec))
1028 Sec.Name = (RelocSec->getNamePrefix() + TargetSec->Name).str();
1029 else
1030 Sec.Name = (RelocSec->getNamePrefix() + Config.AllocSectionsPrefix +
1031 TargetSec->Name)
1032 .str();
1033 }
1034 }
1035 }
1036 }
1037
1038 if (ELFConfig.EntryExpr)
1039 Obj.Entry = ELFConfig.EntryExpr(Obj.Entry);
1040 return Error::success();
1041}
1042
1043static Error writeOutput(const CommonConfig &Config, Object &Obj,
1044 raw_ostream &Out, ElfType OutputElfType) {
1045 std::unique_ptr<Writer> Writer =
1046 createWriter(Config, Obj, Out, OutputElfType);
1047 if (Error E = Writer->finalize())
1048 return E;
1049 return Writer->write();
1050}
1051
1052Error objcopy::elf::executeObjcopyOnIHex(const CommonConfig &Config,
1053 const ELFConfig &ELFConfig,
1054 MemoryBuffer &In, raw_ostream &Out) {
1055 IHexReader Reader(&In);
1056 Expected<std::unique_ptr<Object>> Obj = Reader.create(EnsureSymtab: true);
1057 if (!Obj)
1058 return Obj.takeError();
1059
1060 const ElfType OutputElfType =
1061 getOutputElfType(MI: Config.OutputArch.value_or(u: MachineInfo()));
1062 if (Error E = handleArgs(Config, ELFConfig, OutputElfType, Obj&: **Obj))
1063 return E;
1064 return writeOutput(Config, Obj&: **Obj, Out, OutputElfType);
1065}
1066
1067Error objcopy::elf::executeObjcopyOnRawBinary(const CommonConfig &Config,
1068 const ELFConfig &ELFConfig,
1069 MemoryBuffer &In,
1070 raw_ostream &Out) {
1071 BinaryReader Reader(&In, ELFConfig.NewSymbolVisibility);
1072 Expected<std::unique_ptr<Object>> Obj = Reader.create(EnsureSymtab: true);
1073 if (!Obj)
1074 return Obj.takeError();
1075
1076 // Prefer OutputArch (-O<format>) if set, otherwise fallback to BinaryArch
1077 // (-B<arch>).
1078 const ElfType OutputElfType =
1079 getOutputElfType(MI: Config.OutputArch.value_or(u: MachineInfo()));
1080 if (Error E = handleArgs(Config, ELFConfig, OutputElfType, Obj&: **Obj))
1081 return E;
1082 return writeOutput(Config, Obj&: **Obj, Out, OutputElfType);
1083}
1084
1085Error objcopy::elf::executeObjcopyOnBinary(const CommonConfig &Config,
1086 const ELFConfig &ELFConfig,
1087 object::ELFObjectFileBase &In,
1088 raw_ostream &Out) {
1089 ELFReader Reader(&In, Config.ExtractPartition);
1090 Expected<std::unique_ptr<Object>> Obj =
1091 Reader.create(EnsureSymtab: !Config.SymbolsToAdd.empty());
1092 if (!Obj)
1093 return Obj.takeError();
1094 // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
1095 const ElfType OutputElfType = Config.OutputArch
1096 ? getOutputElfType(MI: *Config.OutputArch)
1097 : getOutputElfType(Bin: In);
1098
1099 if (Error E = handleArgs(Config, ELFConfig, OutputElfType, Obj&: **Obj))
1100 return E;
1101
1102 if (Error E = writeOutput(Config, Obj&: **Obj, Out, OutputElfType))
1103 return createFileError(F: Config.InputFilename, E: std::move(E));
1104
1105 return Error::success();
1106}
1107