1 //===- ELFObjcopy.cpp -----------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "ELFObjcopy.h"
11 #include "CopyConfig.h"
13 #include "llvm-objcopy.h"
15 #include "llvm/ADT/BitmaskEnum.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/BinaryFormat/ELF.h"
23 #include "llvm/MC/MCTargetOptions.h"
24 #include "llvm/Object/Binary.h"
25 #include "llvm/Object/ELFObjectFile.h"
26 #include "llvm/Object/ELFTypes.h"
27 #include "llvm/Object/Error.h"
28 #include "llvm/Option/Option.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/Compression.h"
31 #include "llvm/Support/Errc.h"
32 #include "llvm/Support/Error.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/ErrorOr.h"
35 #include "llvm/Support/Memory.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/raw_ostream.h"
45 #include <system_error>
52 using namespace object
;
54 using SectionPred
= std::function
<bool(const SectionBase
&Sec
)>;
56 static bool isDebugSection(const SectionBase
&Sec
) {
57 return StringRef(Sec
.Name
).startswith(".debug") ||
58 StringRef(Sec
.Name
).startswith(".zdebug") || Sec
.Name
== ".gdb_index";
61 static bool isDWOSection(const SectionBase
&Sec
) {
62 return StringRef(Sec
.Name
).endswith(".dwo");
65 static bool onlyKeepDWOPred(const Object
&Obj
, const SectionBase
&Sec
) {
66 // We can't remove the section header string table.
67 if (&Sec
== Obj
.SectionNames
)
69 // Short of keeping the string table we want to keep everything that is a DWO
70 // section and remove everything else.
71 return !isDWOSection(Sec
);
74 uint64_t getNewShfFlags(SectionFlag AllFlags
) {
75 uint64_t NewFlags
= 0;
76 if (AllFlags
& SectionFlag::SecAlloc
)
77 NewFlags
|= ELF::SHF_ALLOC
;
78 if (!(AllFlags
& SectionFlag::SecReadonly
))
79 NewFlags
|= ELF::SHF_WRITE
;
80 if (AllFlags
& SectionFlag::SecCode
)
81 NewFlags
|= ELF::SHF_EXECINSTR
;
82 if (AllFlags
& SectionFlag::SecMerge
)
83 NewFlags
|= ELF::SHF_MERGE
;
84 if (AllFlags
& SectionFlag::SecStrings
)
85 NewFlags
|= ELF::SHF_STRINGS
;
89 static uint64_t getSectionFlagsPreserveMask(uint64_t OldFlags
,
91 // Preserve some flags which should not be dropped when setting flags.
92 // Also, preserve anything OS/processor dependant.
93 const uint64_t PreserveMask
= ELF::SHF_COMPRESSED
| ELF::SHF_EXCLUDE
|
94 ELF::SHF_GROUP
| ELF::SHF_LINK_ORDER
|
95 ELF::SHF_MASKOS
| ELF::SHF_MASKPROC
|
96 ELF::SHF_TLS
| ELF::SHF_INFO_LINK
;
97 return (OldFlags
& PreserveMask
) | (NewFlags
& ~PreserveMask
);
100 static void setSectionFlagsAndType(SectionBase
&Sec
, SectionFlag Flags
) {
101 Sec
.Flags
= getSectionFlagsPreserveMask(Sec
.Flags
, getNewShfFlags(Flags
));
103 // In GNU objcopy, certain flags promote SHT_NOBITS to SHT_PROGBITS. This rule
104 // may promote more non-ALLOC sections than GNU objcopy, but it is fine as
105 // non-ALLOC SHT_NOBITS sections do not make much sense.
106 if (Sec
.Type
== SHT_NOBITS
&&
107 (!(Sec
.Flags
& ELF::SHF_ALLOC
) ||
108 Flags
& (SectionFlag::SecContents
| SectionFlag::SecLoad
)))
109 Sec
.Type
= SHT_PROGBITS
;
112 static ElfType
getOutputElfType(const Binary
&Bin
) {
113 // Infer output ELF type from the input ELF object
114 if (isa
<ELFObjectFile
<ELF32LE
>>(Bin
))
116 if (isa
<ELFObjectFile
<ELF64LE
>>(Bin
))
118 if (isa
<ELFObjectFile
<ELF32BE
>>(Bin
))
120 if (isa
<ELFObjectFile
<ELF64BE
>>(Bin
))
122 llvm_unreachable("Invalid ELFType");
125 static ElfType
getOutputElfType(const MachineInfo
&MI
) {
126 // Infer output ELF type from the binary arch specified
128 return MI
.IsLittleEndian
? ELFT_ELF64LE
: ELFT_ELF64BE
;
130 return MI
.IsLittleEndian
? ELFT_ELF32LE
: ELFT_ELF32BE
;
133 static std::unique_ptr
<Writer
> createELFWriter(const CopyConfig
&Config
,
134 Object
&Obj
, Buffer
&Buf
,
135 ElfType OutputElfType
) {
136 // Depending on the initial ELFT and OutputFormat we need a different Writer.
137 switch (OutputElfType
) {
139 return llvm::make_unique
<ELFWriter
<ELF32LE
>>(Obj
, Buf
,
140 !Config
.StripSections
);
142 return llvm::make_unique
<ELFWriter
<ELF64LE
>>(Obj
, Buf
,
143 !Config
.StripSections
);
145 return llvm::make_unique
<ELFWriter
<ELF32BE
>>(Obj
, Buf
,
146 !Config
.StripSections
);
148 return llvm::make_unique
<ELFWriter
<ELF64BE
>>(Obj
, Buf
,
149 !Config
.StripSections
);
151 llvm_unreachable("Invalid output format");
154 static std::unique_ptr
<Writer
> createWriter(const CopyConfig
&Config
,
155 Object
&Obj
, Buffer
&Buf
,
156 ElfType OutputElfType
) {
157 switch (Config
.OutputFormat
) {
158 case FileFormat::Binary
:
159 return llvm::make_unique
<BinaryWriter
>(Obj
, Buf
);
160 case FileFormat::IHex
:
161 return llvm::make_unique
<IHexWriter
>(Obj
, Buf
);
163 return createELFWriter(Config
, Obj
, Buf
, OutputElfType
);
167 template <class ELFT
>
168 static Expected
<ArrayRef
<uint8_t>>
169 findBuildID(const CopyConfig
&Config
, const object::ELFFile
<ELFT
> &In
) {
170 auto PhdrsOrErr
= In
.program_headers();
171 if (auto Err
= PhdrsOrErr
.takeError())
172 return createFileError(Config
.InputFilename
, std::move(Err
));
174 for (const auto &Phdr
: *PhdrsOrErr
) {
175 if (Phdr
.p_type
!= PT_NOTE
)
177 Error Err
= Error::success();
178 for (const auto &Note
: In
.notes(Phdr
, Err
))
179 if (Note
.getType() == NT_GNU_BUILD_ID
&& Note
.getName() == ELF_NOTE_GNU
)
180 return Note
.getDesc();
182 return createFileError(Config
.InputFilename
, std::move(Err
));
185 return createFileError(
186 Config
.InputFilename
,
187 createStringError(llvm::errc::invalid_argument
,
188 "could not find build ID"));
191 static Expected
<ArrayRef
<uint8_t>>
192 findBuildID(const CopyConfig
&Config
, const object::ELFObjectFileBase
&In
) {
193 if (auto *O
= dyn_cast
<ELFObjectFile
<ELF32LE
>>(&In
))
194 return findBuildID(Config
, *O
->getELFFile());
195 else if (auto *O
= dyn_cast
<ELFObjectFile
<ELF64LE
>>(&In
))
196 return findBuildID(Config
, *O
->getELFFile());
197 else if (auto *O
= dyn_cast
<ELFObjectFile
<ELF32BE
>>(&In
))
198 return findBuildID(Config
, *O
->getELFFile());
199 else if (auto *O
= dyn_cast
<ELFObjectFile
<ELF64BE
>>(&In
))
200 return findBuildID(Config
, *O
->getELFFile());
202 llvm_unreachable("Bad file format");
205 template <class... Ts
>
206 static Error
makeStringError(std::error_code EC
, const Twine
&Msg
, Ts
&&... Args
) {
207 std::string FullMsg
= (EC
.message() + ": " + Msg
).str();
208 return createStringError(EC
, FullMsg
.c_str(), std::forward
<Ts
>(Args
)...);
211 #define MODEL_8 "%%%%%%%%"
212 #define MODEL_16 MODEL_8 MODEL_8
213 #define MODEL_32 (MODEL_16 MODEL_16)
215 static Error
linkToBuildIdDir(const CopyConfig
&Config
, StringRef ToLink
,
217 ArrayRef
<uint8_t> BuildIdBytes
) {
218 SmallString
<128> Path
= Config
.BuildIdLinkDir
;
219 sys::path::append(Path
, llvm::toHex(BuildIdBytes
[0], /*LowerCase*/ true));
220 if (auto EC
= sys::fs::create_directories(Path
))
221 return createFileError(
223 makeStringError(EC
, "cannot create build ID link directory"));
225 sys::path::append(Path
,
226 llvm::toHex(BuildIdBytes
.slice(1), /*LowerCase*/ true));
228 SmallString
<128> TmpPath
;
229 // create_hard_link races so we need to link to a temporary path but
230 // we want to make sure that we choose a filename that does not exist.
231 // By using 32 model characters we get 128-bits of entropy. It is
232 // unlikely that this string has ever existed before much less exists
233 // on this disk or in the current working directory.
234 // Additionally we prepend the original Path for debugging but also
235 // because it ensures that we're linking within a directory on the same
236 // partition on the same device which is critical. It has the added
237 // win of yet further decreasing the odds of a conflict.
238 sys::fs::createUniquePath(Twine(Path
) + "-" + MODEL_32
+ ".tmp", TmpPath
,
239 /*MakeAbsolute*/ false);
240 if (auto EC
= sys::fs::create_hard_link(ToLink
, TmpPath
)) {
241 Path
.push_back('\0');
242 return makeStringError(EC
, "cannot link '%s' to '%s'", ToLink
.data(),
245 // We then atomically rename the link into place which will just move the
246 // link. If rename fails something is more seriously wrong so just return
248 if (auto EC
= sys::fs::rename(TmpPath
, Path
)) {
249 Path
.push_back('\0');
250 return makeStringError(EC
, "cannot link '%s' to '%s'", ToLink
.data(),
253 // If `Path` was already a hard-link to the same underlying file then the
254 // temp file will be left so we need to remove it. Remove will not cause
255 // an error by default if the file is already gone so just blindly remove
256 // it rather than checking.
257 if (auto EC
= sys::fs::remove(TmpPath
)) {
258 TmpPath
.push_back('\0');
259 return makeStringError(EC
, "could not remove '%s'", TmpPath
.data());
261 return Error::success();
264 static Error
splitDWOToFile(const CopyConfig
&Config
, const Reader
&Reader
,
265 StringRef File
, ElfType OutputElfType
) {
266 auto DWOFile
= Reader
.create();
267 auto OnlyKeepDWOPred
= [&DWOFile
](const SectionBase
&Sec
) {
268 return onlyKeepDWOPred(*DWOFile
, Sec
);
270 if (Error E
= DWOFile
->removeSections(Config
.AllowBrokenLinks
,
273 if (Config
.OutputArch
) {
274 DWOFile
->Machine
= Config
.OutputArch
.getValue().EMachine
;
275 DWOFile
->OSABI
= Config
.OutputArch
.getValue().OSABI
;
278 auto Writer
= createWriter(Config
, *DWOFile
, FB
, OutputElfType
);
279 if (Error E
= Writer
->finalize())
281 return Writer
->write();
284 static Error
dumpSectionToFile(StringRef SecName
, StringRef Filename
,
286 for (auto &Sec
: Obj
.sections()) {
287 if (Sec
.Name
== SecName
) {
288 if (Sec
.OriginalData
.empty())
289 return createStringError(object_error::parse_failed
,
290 "cannot dump section '%s': it has no contents",
291 SecName
.str().c_str());
292 Expected
<std::unique_ptr
<FileOutputBuffer
>> BufferOrErr
=
293 FileOutputBuffer::create(Filename
, Sec
.OriginalData
.size());
295 return BufferOrErr
.takeError();
296 std::unique_ptr
<FileOutputBuffer
> Buf
= std::move(*BufferOrErr
);
297 std::copy(Sec
.OriginalData
.begin(), Sec
.OriginalData
.end(),
298 Buf
->getBufferStart());
299 if (Error E
= Buf
->commit())
301 return Error::success();
304 return createStringError(object_error::parse_failed
, "section '%s' not found",
305 SecName
.str().c_str());
308 static bool isCompressable(const SectionBase
&Section
) {
309 return !(Section
.Flags
& ELF::SHF_COMPRESSED
) &&
310 StringRef(Section
.Name
).startswith(".debug");
313 static void replaceDebugSections(
314 Object
&Obj
, SectionPred
&RemovePred
,
315 function_ref
<bool(const SectionBase
&)> shouldReplace
,
316 function_ref
<SectionBase
*(const SectionBase
*)> addSection
) {
317 // Build a list of the debug sections we are going to replace.
318 // We can't call `addSection` while iterating over sections,
319 // because it would mutate the sections array.
320 SmallVector
<SectionBase
*, 13> ToReplace
;
321 for (auto &Sec
: Obj
.sections())
322 if (shouldReplace(Sec
))
323 ToReplace
.push_back(&Sec
);
325 // Build a mapping from original section to a new one.
326 DenseMap
<SectionBase
*, SectionBase
*> FromTo
;
327 for (SectionBase
*S
: ToReplace
)
328 FromTo
[S
] = addSection(S
);
330 // Now we want to update the target sections of relocation
331 // sections. Also we will update the relocations themselves
332 // to update the symbol references.
333 for (auto &Sec
: Obj
.sections())
334 Sec
.replaceSectionReferences(FromTo
);
336 RemovePred
= [shouldReplace
, RemovePred
](const SectionBase
&Sec
) {
337 return shouldReplace(Sec
) || RemovePred(Sec
);
341 static bool isUnneededSymbol(const Symbol
&Sym
) {
342 return !Sym
.Referenced
&&
343 (Sym
.Binding
== STB_LOCAL
|| Sym
.getShndx() == SHN_UNDEF
) &&
344 Sym
.Type
!= STT_SECTION
;
347 static Error
updateAndRemoveSymbols(const CopyConfig
&Config
, Object
&Obj
) {
348 // TODO: update or remove symbols only if there is an option that affects
350 if (!Obj
.SymbolTable
)
351 return Error::success();
353 Obj
.SymbolTable
->updateSymbols([&](Symbol
&Sym
) {
354 // Common and undefined symbols don't make sense as local symbols, and can
355 // even cause crashes if we localize those, so skip them.
356 if (!Sym
.isCommon() && Sym
.getShndx() != SHN_UNDEF
&&
357 ((Config
.LocalizeHidden
&&
358 (Sym
.Visibility
== STV_HIDDEN
|| Sym
.Visibility
== STV_INTERNAL
)) ||
359 is_contained(Config
.SymbolsToLocalize
, Sym
.Name
)))
360 Sym
.Binding
= STB_LOCAL
;
362 // Note: these two globalize flags have very similar names but different
365 // --globalize-symbol: promote a symbol to global
366 // --keep-global-symbol: all symbols except for these should be made local
368 // If --globalize-symbol is specified for a given symbol, it will be
369 // global in the output file even if it is not included via
370 // --keep-global-symbol. Because of that, make sure to check
371 // --globalize-symbol second.
372 if (!Config
.SymbolsToKeepGlobal
.empty() &&
373 !is_contained(Config
.SymbolsToKeepGlobal
, Sym
.Name
) &&
374 Sym
.getShndx() != SHN_UNDEF
)
375 Sym
.Binding
= STB_LOCAL
;
377 if (is_contained(Config
.SymbolsToGlobalize
, Sym
.Name
) &&
378 Sym
.getShndx() != SHN_UNDEF
)
379 Sym
.Binding
= STB_GLOBAL
;
381 if (is_contained(Config
.SymbolsToWeaken
, Sym
.Name
) &&
382 Sym
.Binding
== STB_GLOBAL
)
383 Sym
.Binding
= STB_WEAK
;
385 if (Config
.Weaken
&& Sym
.Binding
== STB_GLOBAL
&&
386 Sym
.getShndx() != SHN_UNDEF
)
387 Sym
.Binding
= STB_WEAK
;
389 const auto I
= Config
.SymbolsToRename
.find(Sym
.Name
);
390 if (I
!= Config
.SymbolsToRename
.end())
391 Sym
.Name
= I
->getValue();
393 if (!Config
.SymbolsPrefix
.empty() && Sym
.Type
!= STT_SECTION
)
394 Sym
.Name
= (Config
.SymbolsPrefix
+ Sym
.Name
).str();
397 // The purpose of this loop is to mark symbols referenced by sections
398 // (like GroupSection or RelocationSection). This way, we know which
399 // symbols are still 'needed' and which are not.
400 if (Config
.StripUnneeded
|| !Config
.UnneededSymbolsToRemove
.empty() ||
401 !Config
.OnlySection
.empty()) {
402 for (auto &Section
: Obj
.sections())
403 Section
.markSymbols();
406 auto RemoveSymbolsPred
= [&](const Symbol
&Sym
) {
407 if (is_contained(Config
.SymbolsToKeep
, Sym
.Name
) ||
408 (Config
.KeepFileSymbols
&& Sym
.Type
== STT_FILE
))
411 if ((Config
.DiscardMode
== DiscardType::All
||
412 (Config
.DiscardMode
== DiscardType::Locals
&&
413 StringRef(Sym
.Name
).startswith(".L"))) &&
414 Sym
.Binding
== STB_LOCAL
&& Sym
.getShndx() != SHN_UNDEF
&&
415 Sym
.Type
!= STT_FILE
&& Sym
.Type
!= STT_SECTION
)
418 if (Config
.StripAll
|| Config
.StripAllGNU
)
421 if (is_contained(Config
.SymbolsToRemove
, Sym
.Name
))
424 if ((Config
.StripUnneeded
||
425 is_contained(Config
.UnneededSymbolsToRemove
, Sym
.Name
)) &&
426 (!Obj
.isRelocatable() || isUnneededSymbol(Sym
)))
429 // We want to remove undefined symbols if all references have been stripped.
430 if (!Config
.OnlySection
.empty() && !Sym
.Referenced
&&
431 Sym
.getShndx() == SHN_UNDEF
)
437 return Obj
.removeSymbols(RemoveSymbolsPred
);
440 static Error
replaceAndRemoveSections(const CopyConfig
&Config
, Object
&Obj
) {
441 SectionPred RemovePred
= [](const SectionBase
&) { return false; };
444 if (!Config
.ToRemove
.empty()) {
445 RemovePred
= [&Config
](const SectionBase
&Sec
) {
446 return is_contained(Config
.ToRemove
, Sec
.Name
);
450 if (Config
.StripDWO
|| !Config
.SplitDWO
.empty())
451 RemovePred
= [RemovePred
](const SectionBase
&Sec
) {
452 return isDWOSection(Sec
) || RemovePred(Sec
);
455 if (Config
.ExtractDWO
)
456 RemovePred
= [RemovePred
, &Obj
](const SectionBase
&Sec
) {
457 return onlyKeepDWOPred(Obj
, Sec
) || RemovePred(Sec
);
460 if (Config
.StripAllGNU
)
461 RemovePred
= [RemovePred
, &Obj
](const SectionBase
&Sec
) {
464 if ((Sec
.Flags
& SHF_ALLOC
) != 0)
466 if (&Sec
== Obj
.SectionNames
)
475 return isDebugSection(Sec
);
478 if (Config
.StripSections
) {
479 RemovePred
= [RemovePred
](const SectionBase
&Sec
) {
480 return RemovePred(Sec
) || Sec
.ParentSegment
== nullptr;
484 if (Config
.StripDebug
) {
485 RemovePred
= [RemovePred
](const SectionBase
&Sec
) {
486 return RemovePred(Sec
) || isDebugSection(Sec
);
490 if (Config
.StripNonAlloc
)
491 RemovePred
= [RemovePred
, &Obj
](const SectionBase
&Sec
) {
494 if (&Sec
== Obj
.SectionNames
)
496 return (Sec
.Flags
& SHF_ALLOC
) == 0 && Sec
.ParentSegment
== nullptr;
500 RemovePred
= [RemovePred
, &Obj
](const SectionBase
&Sec
) {
503 if (&Sec
== Obj
.SectionNames
)
505 if (StringRef(Sec
.Name
).startswith(".gnu.warning"))
507 if (Sec
.ParentSegment
!= nullptr)
509 return (Sec
.Flags
& SHF_ALLOC
) == 0;
512 if (Config
.ExtractPartition
|| Config
.ExtractMainPartition
) {
513 RemovePred
= [RemovePred
](const SectionBase
&Sec
) {
516 if (Sec
.Type
== SHT_LLVM_PART_EHDR
|| Sec
.Type
== SHT_LLVM_PART_PHDR
)
518 return (Sec
.Flags
& SHF_ALLOC
) != 0 && !Sec
.ParentSegment
;
523 if (!Config
.OnlySection
.empty()) {
524 RemovePred
= [&Config
, RemovePred
, &Obj
](const SectionBase
&Sec
) {
525 // Explicitly keep these sections regardless of previous removes.
526 if (is_contained(Config
.OnlySection
, Sec
.Name
))
529 // Allow all implicit removes.
533 // Keep special sections.
534 if (Obj
.SectionNames
== &Sec
)
536 if (Obj
.SymbolTable
== &Sec
||
537 (Obj
.SymbolTable
&& Obj
.SymbolTable
->getStrTab() == &Sec
))
540 // Remove everything else.
545 if (!Config
.KeepSection
.empty()) {
546 RemovePred
= [&Config
, RemovePred
](const SectionBase
&Sec
) {
547 // Explicitly keep these sections regardless of previous removes.
548 if (is_contained(Config
.KeepSection
, Sec
.Name
))
550 // Otherwise defer to RemovePred.
551 return RemovePred(Sec
);
555 // This has to be the last predicate assignment.
556 // If the option --keep-symbol has been specified
557 // and at least one of those symbols is present
558 // (equivalently, the updated symbol table is not empty)
559 // the symbol table and the string table should not be removed.
560 if ((!Config
.SymbolsToKeep
.empty() || Config
.KeepFileSymbols
) &&
561 Obj
.SymbolTable
&& !Obj
.SymbolTable
->empty()) {
562 RemovePred
= [&Obj
, RemovePred
](const SectionBase
&Sec
) {
563 if (&Sec
== Obj
.SymbolTable
|| &Sec
== Obj
.SymbolTable
->getStrTab())
565 return RemovePred(Sec
);
569 if (Config
.CompressionType
!= DebugCompressionType::None
)
570 replaceDebugSections(Obj
, RemovePred
, isCompressable
,
571 [&Config
, &Obj
](const SectionBase
*S
) {
572 return &Obj
.addSection
<CompressedSection
>(
573 *S
, Config
.CompressionType
);
575 else if (Config
.DecompressDebugSections
)
576 replaceDebugSections(
578 [](const SectionBase
&S
) { return isa
<CompressedSection
>(&S
); },
579 [&Obj
](const SectionBase
*S
) {
580 auto CS
= cast
<CompressedSection
>(S
);
581 return &Obj
.addSection
<DecompressedSection
>(*CS
);
584 return Obj
.removeSections(Config
.AllowBrokenLinks
, RemovePred
);
587 // This function handles the high level operations of GNU objcopy including
588 // handling command line options. It's important to outline certain properties
589 // we expect to hold of the command line operations. Any operation that "keeps"
590 // should keep regardless of a remove. Additionally any removal should respect
591 // any previous removals. Lastly whether or not something is removed shouldn't
592 // depend a) on the order the options occur in or b) on some opaque priority
593 // system. The only priority is that keeps/copies overrule removes.
594 static Error
handleArgs(const CopyConfig
&Config
, Object
&Obj
,
595 const Reader
&Reader
, ElfType OutputElfType
) {
597 if (!Config
.SplitDWO
.empty())
599 splitDWOToFile(Config
, Reader
, Config
.SplitDWO
, OutputElfType
))
602 if (Config
.OutputArch
) {
603 Obj
.Machine
= Config
.OutputArch
.getValue().EMachine
;
604 Obj
.OSABI
= Config
.OutputArch
.getValue().OSABI
;
607 // It is important to remove the sections first. For example, we want to
608 // remove the relocation sections before removing the symbols. That allows
609 // us to avoid reporting the inappropriate errors about removing symbols
610 // named in relocations.
611 if (Error E
= replaceAndRemoveSections(Config
, Obj
))
614 if (Error E
= updateAndRemoveSymbols(Config
, Obj
))
617 if (!Config
.SectionsToRename
.empty() || !Config
.AllocSectionsPrefix
.empty()) {
618 DenseSet
<SectionBase
*> PrefixedSections
;
619 for (auto &Sec
: Obj
.sections()) {
620 const auto Iter
= Config
.SectionsToRename
.find(Sec
.Name
);
621 if (Iter
!= Config
.SectionsToRename
.end()) {
622 const SectionRename
&SR
= Iter
->second
;
623 Sec
.Name
= SR
.NewName
;
624 if (SR
.NewFlags
.hasValue())
625 setSectionFlagsAndType(Sec
, SR
.NewFlags
.getValue());
628 // Add a prefix to allocated sections and their relocation sections. This
629 // should be done after renaming the section by Config.SectionToRename to
630 // imitate the GNU objcopy behavior.
631 if (!Config
.AllocSectionsPrefix
.empty()) {
632 if (Sec
.Flags
& SHF_ALLOC
) {
633 Sec
.Name
= (Config
.AllocSectionsPrefix
+ Sec
.Name
).str();
634 PrefixedSections
.insert(&Sec
);
636 // Rename relocation sections associated to the allocated sections.
637 // For example, if we rename .text to .prefix.text, we also rename
638 // .rel.text to .rel.prefix.text.
640 // Dynamic relocation sections (SHT_REL[A] with SHF_ALLOC) are handled
641 // above, e.g., .rela.plt is renamed to .prefix.rela.plt, not
642 // .rela.prefix.plt since GNU objcopy does so.
643 } else if (auto *RelocSec
= dyn_cast
<RelocationSectionBase
>(&Sec
)) {
644 auto *TargetSec
= RelocSec
->getSection();
645 if (TargetSec
&& (TargetSec
->Flags
& SHF_ALLOC
)) {
658 // If the relocation section comes *after* the target section, we
659 // don't add Config.AllocSectionsPrefix because we've already added
660 // the prefix to TargetSec->Name. Otherwise, if the relocation
661 // section comes *before* the target section, we add the prefix.
662 if (PrefixedSections
.count(TargetSec
)) {
663 Sec
.Name
= (prefix
+ TargetSec
->Name
).str();
665 const auto Iter
= Config
.SectionsToRename
.find(TargetSec
->Name
);
666 if (Iter
!= Config
.SectionsToRename
.end()) {
667 // Both `--rename-section` and `--prefix-alloc-sections` are
668 // given but the target section is not yet renamed.
670 (prefix
+ Config
.AllocSectionsPrefix
+ Iter
->second
.NewName
)
674 (prefix
+ Config
.AllocSectionsPrefix
+ TargetSec
->Name
)
684 if (!Config
.SetSectionFlags
.empty()) {
685 for (auto &Sec
: Obj
.sections()) {
686 const auto Iter
= Config
.SetSectionFlags
.find(Sec
.Name
);
687 if (Iter
!= Config
.SetSectionFlags
.end()) {
688 const SectionFlagsUpdate
&SFU
= Iter
->second
;
689 setSectionFlagsAndType(Sec
, SFU
.NewFlags
);
694 for (const auto &Flag
: Config
.AddSection
) {
695 std::pair
<StringRef
, StringRef
> SecPair
= Flag
.split("=");
696 StringRef SecName
= SecPair
.first
;
697 StringRef File
= SecPair
.second
;
698 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufOrErr
=
699 MemoryBuffer::getFile(File
);
701 return createFileError(File
, errorCodeToError(BufOrErr
.getError()));
702 std::unique_ptr
<MemoryBuffer
> Buf
= std::move(*BufOrErr
);
703 ArrayRef
<uint8_t> Data(
704 reinterpret_cast<const uint8_t *>(Buf
->getBufferStart()),
705 Buf
->getBufferSize());
706 OwnedDataSection
&NewSection
=
707 Obj
.addSection
<OwnedDataSection
>(SecName
, Data
);
708 if (SecName
.startswith(".note") && SecName
!= ".note.GNU-stack")
709 NewSection
.Type
= SHT_NOTE
;
712 for (const auto &Flag
: Config
.DumpSection
) {
713 std::pair
<StringRef
, StringRef
> SecPair
= Flag
.split("=");
714 StringRef SecName
= SecPair
.first
;
715 StringRef File
= SecPair
.second
;
716 if (Error E
= dumpSectionToFile(SecName
, File
, Obj
))
720 if (!Config
.AddGnuDebugLink
.empty())
721 Obj
.addSection
<GnuDebugLinkSection
>(Config
.AddGnuDebugLink
,
722 Config
.GnuDebugLinkCRC32
);
724 for (const NewSymbolInfo
&SI
: Config
.SymbolsToAdd
) {
725 SectionBase
*Sec
= Obj
.findSection(SI
.SectionName
);
726 uint64_t Value
= Sec
? Sec
->Addr
+ SI
.Value
: SI
.Value
;
727 Obj
.SymbolTable
->addSymbol(
728 SI
.SymbolName
, SI
.Bind
, SI
.Type
, Sec
, Value
, SI
.Visibility
,
729 Sec
? (uint16_t)SYMBOL_SIMPLE_INDEX
: (uint16_t)SHN_ABS
, 0);
732 if (Config
.EntryExpr
)
733 Obj
.Entry
= Config
.EntryExpr(Obj
.Entry
);
734 return Error::success();
737 static Error
writeOutput(const CopyConfig
&Config
, Object
&Obj
, Buffer
&Out
,
738 ElfType OutputElfType
) {
739 std::unique_ptr
<Writer
> Writer
=
740 createWriter(Config
, Obj
, Out
, OutputElfType
);
741 if (Error E
= Writer
->finalize())
743 return Writer
->write();
746 Error
executeObjcopyOnIHex(const CopyConfig
&Config
, MemoryBuffer
&In
,
748 IHexReader
Reader(&In
);
749 std::unique_ptr
<Object
> Obj
= Reader
.create();
750 const ElfType OutputElfType
=
751 getOutputElfType(Config
.OutputArch
.getValueOr(Config
.BinaryArch
));
752 if (Error E
= handleArgs(Config
, *Obj
, Reader
, OutputElfType
))
754 return writeOutput(Config
, *Obj
, Out
, OutputElfType
);
757 Error
executeObjcopyOnRawBinary(const CopyConfig
&Config
, MemoryBuffer
&In
,
759 BinaryReader
Reader(Config
.BinaryArch
, &In
);
760 std::unique_ptr
<Object
> Obj
= Reader
.create();
762 // Prefer OutputArch (-O<format>) if set, otherwise fallback to BinaryArch
764 const ElfType OutputElfType
=
765 getOutputElfType(Config
.OutputArch
.getValueOr(Config
.BinaryArch
));
766 if (Error E
= handleArgs(Config
, *Obj
, Reader
, OutputElfType
))
768 return writeOutput(Config
, *Obj
, Out
, OutputElfType
);
771 Error
executeObjcopyOnBinary(const CopyConfig
&Config
,
772 object::ELFObjectFileBase
&In
, Buffer
&Out
) {
773 ELFReader
Reader(&In
, Config
.ExtractPartition
);
774 std::unique_ptr
<Object
> Obj
= Reader
.create();
775 // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
776 const ElfType OutputElfType
=
777 Config
.OutputArch
? getOutputElfType(Config
.OutputArch
.getValue())
778 : getOutputElfType(In
);
779 ArrayRef
<uint8_t> BuildIdBytes
;
781 if (!Config
.BuildIdLinkDir
.empty()) {
782 auto BuildIdBytesOrErr
= findBuildID(Config
, In
);
783 if (auto E
= BuildIdBytesOrErr
.takeError())
785 BuildIdBytes
= *BuildIdBytesOrErr
;
787 if (BuildIdBytes
.size() < 2)
788 return createFileError(
789 Config
.InputFilename
,
790 createStringError(object_error::parse_failed
,
791 "build ID is smaller than two bytes"));
794 if (!Config
.BuildIdLinkDir
.empty() && Config
.BuildIdLinkInput
)
796 linkToBuildIdDir(Config
, Config
.InputFilename
,
797 Config
.BuildIdLinkInput
.getValue(), BuildIdBytes
))
800 if (Error E
= handleArgs(Config
, *Obj
, Reader
, OutputElfType
))
801 return createFileError(Config
.InputFilename
, std::move(E
));
803 if (Error E
= writeOutput(Config
, *Obj
, Out
, OutputElfType
))
804 return createFileError(Config
.InputFilename
, std::move(E
));
805 if (!Config
.BuildIdLinkDir
.empty() && Config
.BuildIdLinkOutput
)
807 linkToBuildIdDir(Config
, Config
.OutputFilename
,
808 Config
.BuildIdLinkOutput
.getValue(), BuildIdBytes
))
809 return createFileError(Config
.OutputFilename
, std::move(E
));
811 return Error::success();
814 } // end namespace elf
815 } // end namespace objcopy
816 } // end namespace llvm