1f75da0c8SAlexey Lapshin //===- ELFObjcopy.cpp -----------------------------------------------------===//
2f75da0c8SAlexey Lapshin //
3f75da0c8SAlexey Lapshin // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4f75da0c8SAlexey Lapshin // See https://llvm.org/LICENSE.txt for license information.
5f75da0c8SAlexey Lapshin // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6f75da0c8SAlexey Lapshin //
7f75da0c8SAlexey Lapshin //===----------------------------------------------------------------------===//
8f75da0c8SAlexey Lapshin 
9f75da0c8SAlexey Lapshin #include "llvm/ObjCopy/ELF/ELFObjcopy.h"
1025d7b4fbSAlexey Lapshin #include "ELFObject.h"
11f75da0c8SAlexey Lapshin #include "llvm/ADT/BitmaskEnum.h"
12f75da0c8SAlexey Lapshin #include "llvm/ADT/DenseSet.h"
13f75da0c8SAlexey Lapshin #include "llvm/ADT/Optional.h"
14f75da0c8SAlexey Lapshin #include "llvm/ADT/STLExtras.h"
15f75da0c8SAlexey Lapshin #include "llvm/ADT/SmallVector.h"
16f75da0c8SAlexey Lapshin #include "llvm/ADT/StringRef.h"
17f75da0c8SAlexey Lapshin #include "llvm/ADT/Twine.h"
18f75da0c8SAlexey Lapshin #include "llvm/BinaryFormat/ELF.h"
19f75da0c8SAlexey Lapshin #include "llvm/MC/MCTargetOptions.h"
20f75da0c8SAlexey Lapshin #include "llvm/ObjCopy/CommonConfig.h"
21f75da0c8SAlexey Lapshin #include "llvm/ObjCopy/ELF/ELFConfig.h"
22f75da0c8SAlexey Lapshin #include "llvm/Object/Binary.h"
23f75da0c8SAlexey Lapshin #include "llvm/Object/ELFObjectFile.h"
24f75da0c8SAlexey Lapshin #include "llvm/Object/ELFTypes.h"
25f75da0c8SAlexey Lapshin #include "llvm/Object/Error.h"
26f75da0c8SAlexey Lapshin #include "llvm/Option/Option.h"
27f75da0c8SAlexey Lapshin #include "llvm/Support/Casting.h"
28f75da0c8SAlexey Lapshin #include "llvm/Support/Compression.h"
29f75da0c8SAlexey Lapshin #include "llvm/Support/Errc.h"
30f75da0c8SAlexey Lapshin #include "llvm/Support/Error.h"
31f75da0c8SAlexey Lapshin #include "llvm/Support/ErrorHandling.h"
32f75da0c8SAlexey Lapshin #include "llvm/Support/ErrorOr.h"
33f75da0c8SAlexey Lapshin #include "llvm/Support/FileSystem.h"
34f75da0c8SAlexey Lapshin #include "llvm/Support/Memory.h"
35f75da0c8SAlexey Lapshin #include "llvm/Support/Path.h"
36f75da0c8SAlexey Lapshin #include "llvm/Support/raw_ostream.h"
37f75da0c8SAlexey Lapshin #include <algorithm>
38f75da0c8SAlexey Lapshin #include <cassert>
39f75da0c8SAlexey Lapshin #include <cstdlib>
40f75da0c8SAlexey Lapshin #include <functional>
41f75da0c8SAlexey Lapshin #include <iterator>
42f75da0c8SAlexey Lapshin #include <memory>
43f75da0c8SAlexey Lapshin #include <string>
44f75da0c8SAlexey Lapshin #include <system_error>
45f75da0c8SAlexey Lapshin #include <utility>
46f75da0c8SAlexey Lapshin 
47f75da0c8SAlexey Lapshin using namespace llvm;
48f75da0c8SAlexey Lapshin using namespace llvm::ELF;
49f75da0c8SAlexey Lapshin using namespace llvm::objcopy;
50f75da0c8SAlexey Lapshin using namespace llvm::objcopy::elf;
51f75da0c8SAlexey Lapshin using namespace llvm::object;
52f75da0c8SAlexey Lapshin 
53f75da0c8SAlexey Lapshin using SectionPred = std::function<bool(const SectionBase &Sec)>;
54f75da0c8SAlexey Lapshin 
55f75da0c8SAlexey Lapshin static bool isDebugSection(const SectionBase &Sec) {
56f75da0c8SAlexey Lapshin   return StringRef(Sec.Name).startswith(".debug") ||
57f75da0c8SAlexey Lapshin          StringRef(Sec.Name).startswith(".zdebug") || Sec.Name == ".gdb_index";
58f75da0c8SAlexey Lapshin }
59f75da0c8SAlexey Lapshin 
60f75da0c8SAlexey Lapshin static bool isDWOSection(const SectionBase &Sec) {
61f75da0c8SAlexey Lapshin   return StringRef(Sec.Name).endswith(".dwo");
62f75da0c8SAlexey Lapshin }
63f75da0c8SAlexey Lapshin 
64f75da0c8SAlexey Lapshin static bool onlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
65f75da0c8SAlexey Lapshin   // We can't remove the section header string table.
66f75da0c8SAlexey Lapshin   if (&Sec == Obj.SectionNames)
67f75da0c8SAlexey Lapshin     return false;
68f75da0c8SAlexey Lapshin   // Short of keeping the string table we want to keep everything that is a DWO
69f75da0c8SAlexey Lapshin   // section and remove everything else.
70f75da0c8SAlexey Lapshin   return !isDWOSection(Sec);
71f75da0c8SAlexey Lapshin }
72f75da0c8SAlexey Lapshin 
73f75da0c8SAlexey Lapshin static uint64_t getNewShfFlags(SectionFlag AllFlags) {
74f75da0c8SAlexey Lapshin   uint64_t NewFlags = 0;
75f75da0c8SAlexey Lapshin   if (AllFlags & SectionFlag::SecAlloc)
76f75da0c8SAlexey Lapshin     NewFlags |= ELF::SHF_ALLOC;
77f75da0c8SAlexey Lapshin   if (!(AllFlags & SectionFlag::SecReadonly))
78f75da0c8SAlexey Lapshin     NewFlags |= ELF::SHF_WRITE;
79f75da0c8SAlexey Lapshin   if (AllFlags & SectionFlag::SecCode)
80f75da0c8SAlexey Lapshin     NewFlags |= ELF::SHF_EXECINSTR;
81f75da0c8SAlexey Lapshin   if (AllFlags & SectionFlag::SecMerge)
82f75da0c8SAlexey Lapshin     NewFlags |= ELF::SHF_MERGE;
83f75da0c8SAlexey Lapshin   if (AllFlags & SectionFlag::SecStrings)
84f75da0c8SAlexey Lapshin     NewFlags |= ELF::SHF_STRINGS;
85f75da0c8SAlexey Lapshin   if (AllFlags & SectionFlag::SecExclude)
86f75da0c8SAlexey Lapshin     NewFlags |= ELF::SHF_EXCLUDE;
87f75da0c8SAlexey Lapshin   return NewFlags;
88f75da0c8SAlexey Lapshin }
89f75da0c8SAlexey Lapshin 
90f75da0c8SAlexey Lapshin static uint64_t getSectionFlagsPreserveMask(uint64_t OldFlags,
91f75da0c8SAlexey Lapshin                                             uint64_t NewFlags) {
92f75da0c8SAlexey Lapshin   // Preserve some flags which should not be dropped when setting flags.
93f75da0c8SAlexey Lapshin   // Also, preserve anything OS/processor dependant.
94f75da0c8SAlexey Lapshin   const uint64_t PreserveMask =
95f75da0c8SAlexey Lapshin       (ELF::SHF_COMPRESSED | ELF::SHF_GROUP | ELF::SHF_LINK_ORDER |
96f75da0c8SAlexey Lapshin        ELF::SHF_MASKOS | ELF::SHF_MASKPROC | ELF::SHF_TLS |
97f75da0c8SAlexey Lapshin        ELF::SHF_INFO_LINK) &
98f75da0c8SAlexey Lapshin       ~ELF::SHF_EXCLUDE;
99f75da0c8SAlexey Lapshin   return (OldFlags & PreserveMask) | (NewFlags & ~PreserveMask);
100f75da0c8SAlexey Lapshin }
101f75da0c8SAlexey Lapshin 
102f75da0c8SAlexey Lapshin static void setSectionFlagsAndType(SectionBase &Sec, SectionFlag Flags) {
103f75da0c8SAlexey Lapshin   Sec.Flags = getSectionFlagsPreserveMask(Sec.Flags, getNewShfFlags(Flags));
104f75da0c8SAlexey Lapshin 
105f75da0c8SAlexey Lapshin   // In GNU objcopy, certain flags promote SHT_NOBITS to SHT_PROGBITS. This rule
106f75da0c8SAlexey Lapshin   // may promote more non-ALLOC sections than GNU objcopy, but it is fine as
107f75da0c8SAlexey Lapshin   // non-ALLOC SHT_NOBITS sections do not make much sense.
108f75da0c8SAlexey Lapshin   if (Sec.Type == SHT_NOBITS &&
109f75da0c8SAlexey Lapshin       (!(Sec.Flags & ELF::SHF_ALLOC) ||
110f75da0c8SAlexey Lapshin        Flags & (SectionFlag::SecContents | SectionFlag::SecLoad)))
111f75da0c8SAlexey Lapshin     Sec.Type = SHT_PROGBITS;
112f75da0c8SAlexey Lapshin }
113f75da0c8SAlexey Lapshin 
114f75da0c8SAlexey Lapshin static ElfType getOutputElfType(const Binary &Bin) {
115f75da0c8SAlexey Lapshin   // Infer output ELF type from the input ELF object
116f75da0c8SAlexey Lapshin   if (isa<ELFObjectFile<ELF32LE>>(Bin))
117f75da0c8SAlexey Lapshin     return ELFT_ELF32LE;
118f75da0c8SAlexey Lapshin   if (isa<ELFObjectFile<ELF64LE>>(Bin))
119f75da0c8SAlexey Lapshin     return ELFT_ELF64LE;
120f75da0c8SAlexey Lapshin   if (isa<ELFObjectFile<ELF32BE>>(Bin))
121f75da0c8SAlexey Lapshin     return ELFT_ELF32BE;
122f75da0c8SAlexey Lapshin   if (isa<ELFObjectFile<ELF64BE>>(Bin))
123f75da0c8SAlexey Lapshin     return ELFT_ELF64BE;
124f75da0c8SAlexey Lapshin   llvm_unreachable("Invalid ELFType");
125f75da0c8SAlexey Lapshin }
126f75da0c8SAlexey Lapshin 
127f75da0c8SAlexey Lapshin static ElfType getOutputElfType(const MachineInfo &MI) {
128f75da0c8SAlexey Lapshin   // Infer output ELF type from the binary arch specified
129f75da0c8SAlexey Lapshin   if (MI.Is64Bit)
130f75da0c8SAlexey Lapshin     return MI.IsLittleEndian ? ELFT_ELF64LE : ELFT_ELF64BE;
131f75da0c8SAlexey Lapshin   else
132f75da0c8SAlexey Lapshin     return MI.IsLittleEndian ? ELFT_ELF32LE : ELFT_ELF32BE;
133f75da0c8SAlexey Lapshin }
134f75da0c8SAlexey Lapshin 
135f75da0c8SAlexey Lapshin static std::unique_ptr<Writer> createELFWriter(const CommonConfig &Config,
136f75da0c8SAlexey Lapshin                                                Object &Obj, raw_ostream &Out,
137f75da0c8SAlexey Lapshin                                                ElfType OutputElfType) {
138f75da0c8SAlexey Lapshin   // Depending on the initial ELFT and OutputFormat we need a different Writer.
139f75da0c8SAlexey Lapshin   switch (OutputElfType) {
140f75da0c8SAlexey Lapshin   case ELFT_ELF32LE:
141f75da0c8SAlexey Lapshin     return std::make_unique<ELFWriter<ELF32LE>>(Obj, Out, !Config.StripSections,
142f75da0c8SAlexey Lapshin                                                 Config.OnlyKeepDebug);
143f75da0c8SAlexey Lapshin   case ELFT_ELF64LE:
144f75da0c8SAlexey Lapshin     return std::make_unique<ELFWriter<ELF64LE>>(Obj, Out, !Config.StripSections,
145f75da0c8SAlexey Lapshin                                                 Config.OnlyKeepDebug);
146f75da0c8SAlexey Lapshin   case ELFT_ELF32BE:
147f75da0c8SAlexey Lapshin     return std::make_unique<ELFWriter<ELF32BE>>(Obj, Out, !Config.StripSections,
148f75da0c8SAlexey Lapshin                                                 Config.OnlyKeepDebug);
149f75da0c8SAlexey Lapshin   case ELFT_ELF64BE:
150f75da0c8SAlexey Lapshin     return std::make_unique<ELFWriter<ELF64BE>>(Obj, Out, !Config.StripSections,
151f75da0c8SAlexey Lapshin                                                 Config.OnlyKeepDebug);
152f75da0c8SAlexey Lapshin   }
153f75da0c8SAlexey Lapshin   llvm_unreachable("Invalid output format");
154f75da0c8SAlexey Lapshin }
155f75da0c8SAlexey Lapshin 
156f75da0c8SAlexey Lapshin static std::unique_ptr<Writer> createWriter(const CommonConfig &Config,
157f75da0c8SAlexey Lapshin                                             Object &Obj, raw_ostream &Out,
158f75da0c8SAlexey Lapshin                                             ElfType OutputElfType) {
159f75da0c8SAlexey Lapshin   switch (Config.OutputFormat) {
160f75da0c8SAlexey Lapshin   case FileFormat::Binary:
161f75da0c8SAlexey Lapshin     return std::make_unique<BinaryWriter>(Obj, Out);
162f75da0c8SAlexey Lapshin   case FileFormat::IHex:
163f75da0c8SAlexey Lapshin     return std::make_unique<IHexWriter>(Obj, Out);
164f75da0c8SAlexey Lapshin   default:
165f75da0c8SAlexey Lapshin     return createELFWriter(Config, Obj, Out, OutputElfType);
166f75da0c8SAlexey Lapshin   }
167f75da0c8SAlexey Lapshin }
168f75da0c8SAlexey Lapshin 
169f75da0c8SAlexey Lapshin template <class... Ts>
170f75da0c8SAlexey Lapshin static Error makeStringError(std::error_code EC, const Twine &Msg,
171f75da0c8SAlexey Lapshin                              Ts &&...Args) {
172f75da0c8SAlexey Lapshin   std::string FullMsg = (EC.message() + ": " + Msg).str();
173f75da0c8SAlexey Lapshin   return createStringError(EC, FullMsg.c_str(), std::forward<Ts>(Args)...);
174f75da0c8SAlexey Lapshin }
175f75da0c8SAlexey Lapshin 
176f75da0c8SAlexey Lapshin static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
177f75da0c8SAlexey Lapshin                                Object &Obj) {
178f75da0c8SAlexey Lapshin   for (auto &Sec : Obj.sections()) {
179f75da0c8SAlexey Lapshin     if (Sec.Name == SecName) {
180f75da0c8SAlexey Lapshin       if (Sec.Type == SHT_NOBITS)
181f75da0c8SAlexey Lapshin         return createStringError(object_error::parse_failed,
182f75da0c8SAlexey Lapshin                                  "cannot dump section '%s': it has no contents",
183f75da0c8SAlexey Lapshin                                  SecName.str().c_str());
184f75da0c8SAlexey Lapshin       Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
185f75da0c8SAlexey Lapshin           FileOutputBuffer::create(Filename, Sec.OriginalData.size());
186f75da0c8SAlexey Lapshin       if (!BufferOrErr)
187f75da0c8SAlexey Lapshin         return BufferOrErr.takeError();
188f75da0c8SAlexey Lapshin       std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
189f75da0c8SAlexey Lapshin       std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(),
190f75da0c8SAlexey Lapshin                 Buf->getBufferStart());
191f75da0c8SAlexey Lapshin       if (Error E = Buf->commit())
192f75da0c8SAlexey Lapshin         return E;
193f75da0c8SAlexey Lapshin       return Error::success();
194f75da0c8SAlexey Lapshin     }
195f75da0c8SAlexey Lapshin   }
196f75da0c8SAlexey Lapshin   return createStringError(object_error::parse_failed, "section '%s' not found",
197f75da0c8SAlexey Lapshin                            SecName.str().c_str());
198f75da0c8SAlexey Lapshin }
199f75da0c8SAlexey Lapshin 
200f75da0c8SAlexey Lapshin static bool isCompressable(const SectionBase &Sec) {
201f75da0c8SAlexey Lapshin   return !(Sec.Flags & ELF::SHF_COMPRESSED) &&
202f75da0c8SAlexey Lapshin          StringRef(Sec.Name).startswith(".debug");
203f75da0c8SAlexey Lapshin }
204f75da0c8SAlexey Lapshin 
205f75da0c8SAlexey Lapshin static Error replaceDebugSections(
206f75da0c8SAlexey Lapshin     Object &Obj, function_ref<bool(const SectionBase &)> ShouldReplace,
207f75da0c8SAlexey Lapshin     function_ref<Expected<SectionBase *>(const SectionBase *)> AddSection) {
208f75da0c8SAlexey Lapshin   // Build a list of the debug sections we are going to replace.
209f75da0c8SAlexey Lapshin   // We can't call `AddSection` while iterating over sections,
210f75da0c8SAlexey Lapshin   // because it would mutate the sections array.
211f75da0c8SAlexey Lapshin   SmallVector<SectionBase *, 13> ToReplace;
212f75da0c8SAlexey Lapshin   for (auto &Sec : Obj.sections())
213f75da0c8SAlexey Lapshin     if (ShouldReplace(Sec))
214f75da0c8SAlexey Lapshin       ToReplace.push_back(&Sec);
215f75da0c8SAlexey Lapshin 
216f75da0c8SAlexey Lapshin   // Build a mapping from original section to a new one.
217f75da0c8SAlexey Lapshin   DenseMap<SectionBase *, SectionBase *> FromTo;
218f75da0c8SAlexey Lapshin   for (SectionBase *S : ToReplace) {
219f75da0c8SAlexey Lapshin     Expected<SectionBase *> NewSection = AddSection(S);
220f75da0c8SAlexey Lapshin     if (!NewSection)
221f75da0c8SAlexey Lapshin       return NewSection.takeError();
222f75da0c8SAlexey Lapshin 
223f75da0c8SAlexey Lapshin     FromTo[S] = *NewSection;
224f75da0c8SAlexey Lapshin   }
225f75da0c8SAlexey Lapshin 
226f75da0c8SAlexey Lapshin   return Obj.replaceSections(FromTo);
227f75da0c8SAlexey Lapshin }
228f75da0c8SAlexey Lapshin 
229f75da0c8SAlexey Lapshin static bool isAArch64MappingSymbol(const Symbol &Sym) {
230f75da0c8SAlexey Lapshin   if (Sym.Binding != STB_LOCAL || Sym.Type != STT_NOTYPE ||
231f75da0c8SAlexey Lapshin       Sym.getShndx() == SHN_UNDEF)
232f75da0c8SAlexey Lapshin     return false;
233f75da0c8SAlexey Lapshin   StringRef Name = Sym.Name;
234f75da0c8SAlexey Lapshin   if (!Name.consume_front("$x") && !Name.consume_front("$d"))
235f75da0c8SAlexey Lapshin     return false;
236f75da0c8SAlexey Lapshin   return Name.empty() || Name.startswith(".");
237f75da0c8SAlexey Lapshin }
238f75da0c8SAlexey Lapshin 
239f75da0c8SAlexey Lapshin static bool isArmMappingSymbol(const Symbol &Sym) {
240f75da0c8SAlexey Lapshin   if (Sym.Binding != STB_LOCAL || Sym.Type != STT_NOTYPE ||
241f75da0c8SAlexey Lapshin       Sym.getShndx() == SHN_UNDEF)
242f75da0c8SAlexey Lapshin     return false;
243f75da0c8SAlexey Lapshin   StringRef Name = Sym.Name;
244f75da0c8SAlexey Lapshin   if (!Name.consume_front("$a") && !Name.consume_front("$d") &&
245f75da0c8SAlexey Lapshin       !Name.consume_front("$t"))
246f75da0c8SAlexey Lapshin     return false;
247f75da0c8SAlexey Lapshin   return Name.empty() || Name.startswith(".");
248f75da0c8SAlexey Lapshin }
249f75da0c8SAlexey Lapshin 
250f75da0c8SAlexey Lapshin // Check if the symbol should be preserved because it is required by ABI.
251f75da0c8SAlexey Lapshin static bool isRequiredByABISymbol(const Object &Obj, const Symbol &Sym) {
252f75da0c8SAlexey Lapshin   switch (Obj.Machine) {
253f75da0c8SAlexey Lapshin   case EM_AARCH64:
254f75da0c8SAlexey Lapshin     // Mapping symbols should be preserved for a relocatable object file.
255f75da0c8SAlexey Lapshin     return Obj.isRelocatable() && isAArch64MappingSymbol(Sym);
256f75da0c8SAlexey Lapshin   case EM_ARM:
257f75da0c8SAlexey Lapshin     // Mapping symbols should be preserved for a relocatable object file.
258f75da0c8SAlexey Lapshin     return Obj.isRelocatable() && isArmMappingSymbol(Sym);
259f75da0c8SAlexey Lapshin   default:
260f75da0c8SAlexey Lapshin     return false;
261f75da0c8SAlexey Lapshin   }
262f75da0c8SAlexey Lapshin }
263f75da0c8SAlexey Lapshin 
264f75da0c8SAlexey Lapshin static bool isUnneededSymbol(const Symbol &Sym) {
265f75da0c8SAlexey Lapshin   return !Sym.Referenced &&
266f75da0c8SAlexey Lapshin          (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
267f75da0c8SAlexey Lapshin          Sym.Type != STT_SECTION;
268f75da0c8SAlexey Lapshin }
269f75da0c8SAlexey Lapshin 
270f75da0c8SAlexey Lapshin static Error updateAndRemoveSymbols(const CommonConfig &Config,
271f75da0c8SAlexey Lapshin                                     const ELFConfig &ELFConfig, Object &Obj) {
272f75da0c8SAlexey Lapshin   // TODO: update or remove symbols only if there is an option that affects
273f75da0c8SAlexey Lapshin   // them.
274f75da0c8SAlexey Lapshin   if (!Obj.SymbolTable)
275f75da0c8SAlexey Lapshin     return Error::success();
276f75da0c8SAlexey Lapshin 
277f75da0c8SAlexey Lapshin   Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
278f75da0c8SAlexey Lapshin     // Common and undefined symbols don't make sense as local symbols, and can
279f75da0c8SAlexey Lapshin     // even cause crashes if we localize those, so skip them.
280f75da0c8SAlexey Lapshin     if (!Sym.isCommon() && Sym.getShndx() != SHN_UNDEF &&
281f75da0c8SAlexey Lapshin         ((ELFConfig.LocalizeHidden &&
282f75da0c8SAlexey Lapshin           (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
283f75da0c8SAlexey Lapshin          Config.SymbolsToLocalize.matches(Sym.Name)))
284f75da0c8SAlexey Lapshin       Sym.Binding = STB_LOCAL;
285f75da0c8SAlexey Lapshin 
286f75da0c8SAlexey Lapshin     // Note: these two globalize flags have very similar names but different
287f75da0c8SAlexey Lapshin     // meanings:
288f75da0c8SAlexey Lapshin     //
289f75da0c8SAlexey Lapshin     // --globalize-symbol: promote a symbol to global
290f75da0c8SAlexey Lapshin     // --keep-global-symbol: all symbols except for these should be made local
291f75da0c8SAlexey Lapshin     //
292f75da0c8SAlexey Lapshin     // If --globalize-symbol is specified for a given symbol, it will be
293f75da0c8SAlexey Lapshin     // global in the output file even if it is not included via
294f75da0c8SAlexey Lapshin     // --keep-global-symbol. Because of that, make sure to check
295f75da0c8SAlexey Lapshin     // --globalize-symbol second.
296f75da0c8SAlexey Lapshin     if (!Config.SymbolsToKeepGlobal.empty() &&
297f75da0c8SAlexey Lapshin         !Config.SymbolsToKeepGlobal.matches(Sym.Name) &&
298f75da0c8SAlexey Lapshin         Sym.getShndx() != SHN_UNDEF)
299f75da0c8SAlexey Lapshin       Sym.Binding = STB_LOCAL;
300f75da0c8SAlexey Lapshin 
301f75da0c8SAlexey Lapshin     if (Config.SymbolsToGlobalize.matches(Sym.Name) &&
302f75da0c8SAlexey Lapshin         Sym.getShndx() != SHN_UNDEF)
303f75da0c8SAlexey Lapshin       Sym.Binding = STB_GLOBAL;
304f75da0c8SAlexey Lapshin 
30530718f3aSFangrui Song     // SymbolsToWeaken applies to both STB_GLOBAL and STB_GNU_UNIQUE.
30630718f3aSFangrui Song     if (Config.SymbolsToWeaken.matches(Sym.Name) && Sym.Binding != STB_LOCAL)
307f75da0c8SAlexey Lapshin       Sym.Binding = STB_WEAK;
308f75da0c8SAlexey Lapshin 
30930718f3aSFangrui Song     if (Config.Weaken && Sym.Binding != STB_LOCAL &&
310f75da0c8SAlexey Lapshin         Sym.getShndx() != SHN_UNDEF)
311f75da0c8SAlexey Lapshin       Sym.Binding = STB_WEAK;
312f75da0c8SAlexey Lapshin 
313f75da0c8SAlexey Lapshin     const auto I = Config.SymbolsToRename.find(Sym.Name);
314f75da0c8SAlexey Lapshin     if (I != Config.SymbolsToRename.end())
315f75da0c8SAlexey Lapshin       Sym.Name = std::string(I->getValue());
316f75da0c8SAlexey Lapshin 
317f75da0c8SAlexey Lapshin     if (!Config.SymbolsPrefix.empty() && Sym.Type != STT_SECTION)
318f75da0c8SAlexey Lapshin       Sym.Name = (Config.SymbolsPrefix + Sym.Name).str();
319f75da0c8SAlexey Lapshin   });
320f75da0c8SAlexey Lapshin 
321f75da0c8SAlexey Lapshin   // The purpose of this loop is to mark symbols referenced by sections
322f75da0c8SAlexey Lapshin   // (like GroupSection or RelocationSection). This way, we know which
323f75da0c8SAlexey Lapshin   // symbols are still 'needed' and which are not.
324f75da0c8SAlexey Lapshin   if (Config.StripUnneeded || !Config.UnneededSymbolsToRemove.empty() ||
325f75da0c8SAlexey Lapshin       !Config.OnlySection.empty()) {
326f75da0c8SAlexey Lapshin     for (SectionBase &Sec : Obj.sections())
327f75da0c8SAlexey Lapshin       Sec.markSymbols();
328f75da0c8SAlexey Lapshin   }
329f75da0c8SAlexey Lapshin 
330f75da0c8SAlexey Lapshin   auto RemoveSymbolsPred = [&](const Symbol &Sym) {
331f75da0c8SAlexey Lapshin     if (Config.SymbolsToKeep.matches(Sym.Name) ||
332f75da0c8SAlexey Lapshin         (ELFConfig.KeepFileSymbols && Sym.Type == STT_FILE))
333f75da0c8SAlexey Lapshin       return false;
334f75da0c8SAlexey Lapshin 
335f75da0c8SAlexey Lapshin     if (Config.SymbolsToRemove.matches(Sym.Name))
336f75da0c8SAlexey Lapshin       return true;
337f75da0c8SAlexey Lapshin 
338f75da0c8SAlexey Lapshin     if (Config.StripAll || Config.StripAllGNU)
339f75da0c8SAlexey Lapshin       return true;
340f75da0c8SAlexey Lapshin 
341f75da0c8SAlexey Lapshin     if (isRequiredByABISymbol(Obj, Sym))
342f75da0c8SAlexey Lapshin       return false;
343f75da0c8SAlexey Lapshin 
344f75da0c8SAlexey Lapshin     if (Config.StripDebug && Sym.Type == STT_FILE)
345f75da0c8SAlexey Lapshin       return true;
346f75da0c8SAlexey Lapshin 
347f75da0c8SAlexey Lapshin     if ((Config.DiscardMode == DiscardType::All ||
348f75da0c8SAlexey Lapshin          (Config.DiscardMode == DiscardType::Locals &&
349f75da0c8SAlexey Lapshin           StringRef(Sym.Name).startswith(".L"))) &&
350f75da0c8SAlexey Lapshin         Sym.Binding == STB_LOCAL && Sym.getShndx() != SHN_UNDEF &&
351f75da0c8SAlexey Lapshin         Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
352f75da0c8SAlexey Lapshin       return true;
353f75da0c8SAlexey Lapshin 
354f75da0c8SAlexey Lapshin     if ((Config.StripUnneeded ||
355f75da0c8SAlexey Lapshin          Config.UnneededSymbolsToRemove.matches(Sym.Name)) &&
356f75da0c8SAlexey Lapshin         (!Obj.isRelocatable() || isUnneededSymbol(Sym)))
357f75da0c8SAlexey Lapshin       return true;
358f75da0c8SAlexey Lapshin 
359f75da0c8SAlexey Lapshin     // We want to remove undefined symbols if all references have been stripped.
360f75da0c8SAlexey Lapshin     if (!Config.OnlySection.empty() && !Sym.Referenced &&
361f75da0c8SAlexey Lapshin         Sym.getShndx() == SHN_UNDEF)
362f75da0c8SAlexey Lapshin       return true;
363f75da0c8SAlexey Lapshin 
364f75da0c8SAlexey Lapshin     return false;
365f75da0c8SAlexey Lapshin   };
366f75da0c8SAlexey Lapshin 
367f75da0c8SAlexey Lapshin   return Obj.removeSymbols(RemoveSymbolsPred);
368f75da0c8SAlexey Lapshin }
369f75da0c8SAlexey Lapshin 
370f75da0c8SAlexey Lapshin static Error replaceAndRemoveSections(const CommonConfig &Config,
371f75da0c8SAlexey Lapshin                                       const ELFConfig &ELFConfig, Object &Obj) {
372f75da0c8SAlexey Lapshin   SectionPred RemovePred = [](const SectionBase &) { return false; };
373f75da0c8SAlexey Lapshin 
374f75da0c8SAlexey Lapshin   // Removes:
375f75da0c8SAlexey Lapshin   if (!Config.ToRemove.empty()) {
376f75da0c8SAlexey Lapshin     RemovePred = [&Config](const SectionBase &Sec) {
377f75da0c8SAlexey Lapshin       return Config.ToRemove.matches(Sec.Name);
378f75da0c8SAlexey Lapshin     };
379f75da0c8SAlexey Lapshin   }
380f75da0c8SAlexey Lapshin 
381f75da0c8SAlexey Lapshin   if (Config.StripDWO)
382f75da0c8SAlexey Lapshin     RemovePred = [RemovePred](const SectionBase &Sec) {
383f75da0c8SAlexey Lapshin       return isDWOSection(Sec) || RemovePred(Sec);
384f75da0c8SAlexey Lapshin     };
385f75da0c8SAlexey Lapshin 
386f75da0c8SAlexey Lapshin   if (Config.ExtractDWO)
387f75da0c8SAlexey Lapshin     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
388f75da0c8SAlexey Lapshin       return onlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
389f75da0c8SAlexey Lapshin     };
390f75da0c8SAlexey Lapshin 
391f75da0c8SAlexey Lapshin   if (Config.StripAllGNU)
392f75da0c8SAlexey Lapshin     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
393f75da0c8SAlexey Lapshin       if (RemovePred(Sec))
394f75da0c8SAlexey Lapshin         return true;
395f75da0c8SAlexey Lapshin       if ((Sec.Flags & SHF_ALLOC) != 0)
396f75da0c8SAlexey Lapshin         return false;
397f75da0c8SAlexey Lapshin       if (&Sec == Obj.SectionNames)
398f75da0c8SAlexey Lapshin         return false;
399f75da0c8SAlexey Lapshin       switch (Sec.Type) {
400f75da0c8SAlexey Lapshin       case SHT_SYMTAB:
401f75da0c8SAlexey Lapshin       case SHT_REL:
402f75da0c8SAlexey Lapshin       case SHT_RELA:
403f75da0c8SAlexey Lapshin       case SHT_STRTAB:
404f75da0c8SAlexey Lapshin         return true;
405f75da0c8SAlexey Lapshin       }
406f75da0c8SAlexey Lapshin       return isDebugSection(Sec);
407f75da0c8SAlexey Lapshin     };
408f75da0c8SAlexey Lapshin 
409f75da0c8SAlexey Lapshin   if (Config.StripSections) {
410f75da0c8SAlexey Lapshin     RemovePred = [RemovePred](const SectionBase &Sec) {
411f75da0c8SAlexey Lapshin       return RemovePred(Sec) || Sec.ParentSegment == nullptr;
412f75da0c8SAlexey Lapshin     };
413f75da0c8SAlexey Lapshin   }
414f75da0c8SAlexey Lapshin 
415f75da0c8SAlexey Lapshin   if (Config.StripDebug || Config.StripUnneeded) {
416f75da0c8SAlexey Lapshin     RemovePred = [RemovePred](const SectionBase &Sec) {
417f75da0c8SAlexey Lapshin       return RemovePred(Sec) || isDebugSection(Sec);
418f75da0c8SAlexey Lapshin     };
419f75da0c8SAlexey Lapshin   }
420f75da0c8SAlexey Lapshin 
421f75da0c8SAlexey Lapshin   if (Config.StripNonAlloc)
422f75da0c8SAlexey Lapshin     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
423f75da0c8SAlexey Lapshin       if (RemovePred(Sec))
424f75da0c8SAlexey Lapshin         return true;
425f75da0c8SAlexey Lapshin       if (&Sec == Obj.SectionNames)
426f75da0c8SAlexey Lapshin         return false;
427f75da0c8SAlexey Lapshin       return (Sec.Flags & SHF_ALLOC) == 0 && Sec.ParentSegment == nullptr;
428f75da0c8SAlexey Lapshin     };
429f75da0c8SAlexey Lapshin 
430f75da0c8SAlexey Lapshin   if (Config.StripAll)
431f75da0c8SAlexey Lapshin     RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
432f75da0c8SAlexey Lapshin       if (RemovePred(Sec))
433f75da0c8SAlexey Lapshin         return true;
434f75da0c8SAlexey Lapshin       if (&Sec == Obj.SectionNames)
435f75da0c8SAlexey Lapshin         return false;
436f75da0c8SAlexey Lapshin       if (StringRef(Sec.Name).startswith(".gnu.warning"))
437f75da0c8SAlexey Lapshin         return false;
438f75da0c8SAlexey Lapshin       // We keep the .ARM.attribute section to maintain compatibility
439f75da0c8SAlexey Lapshin       // with Debian derived distributions. This is a bug in their
440f75da0c8SAlexey Lapshin       // patchset as documented here:
441f75da0c8SAlexey Lapshin       // https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=943798
442f75da0c8SAlexey Lapshin       if (Sec.Type == SHT_ARM_ATTRIBUTES)
443f75da0c8SAlexey Lapshin         return false;
444f75da0c8SAlexey Lapshin       if (Sec.ParentSegment != nullptr)
445f75da0c8SAlexey Lapshin         return false;
446f75da0c8SAlexey Lapshin       return (Sec.Flags & SHF_ALLOC) == 0;
447f75da0c8SAlexey Lapshin     };
448f75da0c8SAlexey Lapshin 
449f75da0c8SAlexey Lapshin   if (Config.ExtractPartition || Config.ExtractMainPartition) {
450f75da0c8SAlexey Lapshin     RemovePred = [RemovePred](const SectionBase &Sec) {
451f75da0c8SAlexey Lapshin       if (RemovePred(Sec))
452f75da0c8SAlexey Lapshin         return true;
453f75da0c8SAlexey Lapshin       if (Sec.Type == SHT_LLVM_PART_EHDR || Sec.Type == SHT_LLVM_PART_PHDR)
454f75da0c8SAlexey Lapshin         return true;
455f75da0c8SAlexey Lapshin       return (Sec.Flags & SHF_ALLOC) != 0 && !Sec.ParentSegment;
456f75da0c8SAlexey Lapshin     };
457f75da0c8SAlexey Lapshin   }
458f75da0c8SAlexey Lapshin 
459f75da0c8SAlexey Lapshin   // Explicit copies:
460f75da0c8SAlexey Lapshin   if (!Config.OnlySection.empty()) {
461f75da0c8SAlexey Lapshin     RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
462f75da0c8SAlexey Lapshin       // Explicitly keep these sections regardless of previous removes.
463f75da0c8SAlexey Lapshin       if (Config.OnlySection.matches(Sec.Name))
464f75da0c8SAlexey Lapshin         return false;
465f75da0c8SAlexey Lapshin 
466f75da0c8SAlexey Lapshin       // Allow all implicit removes.
467f75da0c8SAlexey Lapshin       if (RemovePred(Sec))
468f75da0c8SAlexey Lapshin         return true;
469f75da0c8SAlexey Lapshin 
470f75da0c8SAlexey Lapshin       // Keep special sections.
471f75da0c8SAlexey Lapshin       if (Obj.SectionNames == &Sec)
472f75da0c8SAlexey Lapshin         return false;
473f75da0c8SAlexey Lapshin       if (Obj.SymbolTable == &Sec ||
474f75da0c8SAlexey Lapshin           (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
475f75da0c8SAlexey Lapshin         return false;
476f75da0c8SAlexey Lapshin 
477f75da0c8SAlexey Lapshin       // Remove everything else.
478f75da0c8SAlexey Lapshin       return true;
479f75da0c8SAlexey Lapshin     };
480f75da0c8SAlexey Lapshin   }
481f75da0c8SAlexey Lapshin 
482f75da0c8SAlexey Lapshin   if (!Config.KeepSection.empty()) {
483f75da0c8SAlexey Lapshin     RemovePred = [&Config, RemovePred](const SectionBase &Sec) {
484f75da0c8SAlexey Lapshin       // Explicitly keep these sections regardless of previous removes.
485f75da0c8SAlexey Lapshin       if (Config.KeepSection.matches(Sec.Name))
486f75da0c8SAlexey Lapshin         return false;
487f75da0c8SAlexey Lapshin       // Otherwise defer to RemovePred.
488f75da0c8SAlexey Lapshin       return RemovePred(Sec);
489f75da0c8SAlexey Lapshin     };
490f75da0c8SAlexey Lapshin   }
491f75da0c8SAlexey Lapshin 
492f75da0c8SAlexey Lapshin   // This has to be the last predicate assignment.
493f75da0c8SAlexey Lapshin   // If the option --keep-symbol has been specified
494f75da0c8SAlexey Lapshin   // and at least one of those symbols is present
495f75da0c8SAlexey Lapshin   // (equivalently, the updated symbol table is not empty)
496f75da0c8SAlexey Lapshin   // the symbol table and the string table should not be removed.
497f75da0c8SAlexey Lapshin   if ((!Config.SymbolsToKeep.empty() || ELFConfig.KeepFileSymbols) &&
498f75da0c8SAlexey Lapshin       Obj.SymbolTable && !Obj.SymbolTable->empty()) {
499f75da0c8SAlexey Lapshin     RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
500f75da0c8SAlexey Lapshin       if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
501f75da0c8SAlexey Lapshin         return false;
502f75da0c8SAlexey Lapshin       return RemovePred(Sec);
503f75da0c8SAlexey Lapshin     };
504f75da0c8SAlexey Lapshin   }
505f75da0c8SAlexey Lapshin 
506f75da0c8SAlexey Lapshin   if (Error E = Obj.removeSections(ELFConfig.AllowBrokenLinks, RemovePred))
507f75da0c8SAlexey Lapshin     return E;
508f75da0c8SAlexey Lapshin 
509f75da0c8SAlexey Lapshin   if (Config.CompressionType != DebugCompressionType::None) {
510f75da0c8SAlexey Lapshin     if (Error Err = replaceDebugSections(
511f75da0c8SAlexey Lapshin             Obj, isCompressable,
512f75da0c8SAlexey Lapshin             [&Config, &Obj](const SectionBase *S) -> Expected<SectionBase *> {
513cce35210SFangrui Song               return &Obj.addSection<CompressedSection>(
514cce35210SFangrui Song                   CompressedSection(*S, Config.CompressionType));
515f75da0c8SAlexey Lapshin             }))
516f75da0c8SAlexey Lapshin       return Err;
517f75da0c8SAlexey Lapshin   } else if (Config.DecompressDebugSections) {
518f75da0c8SAlexey Lapshin     if (Error Err = replaceDebugSections(
519f75da0c8SAlexey Lapshin             Obj,
520f75da0c8SAlexey Lapshin             [](const SectionBase &S) { return isa<CompressedSection>(&S); },
521f75da0c8SAlexey Lapshin             [&Obj](const SectionBase *S) {
522f75da0c8SAlexey Lapshin               const CompressedSection *CS = cast<CompressedSection>(S);
523f75da0c8SAlexey Lapshin               return &Obj.addSection<DecompressedSection>(*CS);
524f75da0c8SAlexey Lapshin             }))
525f75da0c8SAlexey Lapshin       return Err;
526f75da0c8SAlexey Lapshin   }
527f75da0c8SAlexey Lapshin 
528f75da0c8SAlexey Lapshin   return Error::success();
529f75da0c8SAlexey Lapshin }
530f75da0c8SAlexey Lapshin 
531f75da0c8SAlexey Lapshin // Add symbol to the Object symbol table with the specified properties.
532f75da0c8SAlexey Lapshin static void addSymbol(Object &Obj, const NewSymbolInfo &SymInfo,
533f75da0c8SAlexey Lapshin                       uint8_t DefaultVisibility) {
534f75da0c8SAlexey Lapshin   SectionBase *Sec = Obj.findSection(SymInfo.SectionName);
535f75da0c8SAlexey Lapshin   uint64_t Value = Sec ? Sec->Addr + SymInfo.Value : SymInfo.Value;
536f75da0c8SAlexey Lapshin 
537f75da0c8SAlexey Lapshin   uint8_t Bind = ELF::STB_GLOBAL;
538f75da0c8SAlexey Lapshin   uint8_t Type = ELF::STT_NOTYPE;
539f75da0c8SAlexey Lapshin   uint8_t Visibility = DefaultVisibility;
540f75da0c8SAlexey Lapshin 
541f75da0c8SAlexey Lapshin   for (SymbolFlag FlagValue : SymInfo.Flags)
542f75da0c8SAlexey Lapshin     switch (FlagValue) {
543f75da0c8SAlexey Lapshin     case SymbolFlag::Global:
544f75da0c8SAlexey Lapshin       Bind = ELF::STB_GLOBAL;
545f75da0c8SAlexey Lapshin       break;
546f75da0c8SAlexey Lapshin     case SymbolFlag::Local:
547f75da0c8SAlexey Lapshin       Bind = ELF::STB_LOCAL;
548f75da0c8SAlexey Lapshin       break;
549f75da0c8SAlexey Lapshin     case SymbolFlag::Weak:
550f75da0c8SAlexey Lapshin       Bind = ELF::STB_WEAK;
551f75da0c8SAlexey Lapshin       break;
552f75da0c8SAlexey Lapshin     case SymbolFlag::Default:
553f75da0c8SAlexey Lapshin       Visibility = ELF::STV_DEFAULT;
554f75da0c8SAlexey Lapshin       break;
555f75da0c8SAlexey Lapshin     case SymbolFlag::Hidden:
556f75da0c8SAlexey Lapshin       Visibility = ELF::STV_HIDDEN;
557f75da0c8SAlexey Lapshin       break;
558f75da0c8SAlexey Lapshin     case SymbolFlag::Protected:
559f75da0c8SAlexey Lapshin       Visibility = ELF::STV_PROTECTED;
560f75da0c8SAlexey Lapshin       break;
561f75da0c8SAlexey Lapshin     case SymbolFlag::File:
562f75da0c8SAlexey Lapshin       Type = ELF::STT_FILE;
563f75da0c8SAlexey Lapshin       break;
564f75da0c8SAlexey Lapshin     case SymbolFlag::Section:
565f75da0c8SAlexey Lapshin       Type = ELF::STT_SECTION;
566f75da0c8SAlexey Lapshin       break;
567f75da0c8SAlexey Lapshin     case SymbolFlag::Object:
568f75da0c8SAlexey Lapshin       Type = ELF::STT_OBJECT;
569f75da0c8SAlexey Lapshin       break;
570f75da0c8SAlexey Lapshin     case SymbolFlag::Function:
571f75da0c8SAlexey Lapshin       Type = ELF::STT_FUNC;
572f75da0c8SAlexey Lapshin       break;
573f75da0c8SAlexey Lapshin     case SymbolFlag::IndirectFunction:
574f75da0c8SAlexey Lapshin       Type = ELF::STT_GNU_IFUNC;
575f75da0c8SAlexey Lapshin       break;
576f75da0c8SAlexey Lapshin     default: /* Other flag values are ignored for ELF. */
577f75da0c8SAlexey Lapshin       break;
578f75da0c8SAlexey Lapshin     };
579f75da0c8SAlexey Lapshin 
580f75da0c8SAlexey Lapshin   Obj.SymbolTable->addSymbol(
581f75da0c8SAlexey Lapshin       SymInfo.SymbolName, Bind, Type, Sec, Value, Visibility,
582f75da0c8SAlexey Lapshin       Sec ? (uint16_t)SYMBOL_SIMPLE_INDEX : (uint16_t)SHN_ABS, 0);
583f75da0c8SAlexey Lapshin }
584f75da0c8SAlexey Lapshin 
585f75da0c8SAlexey Lapshin static Error
586a6f3fedcSAlexey Lapshin handleUserSection(const NewSectionInfo &NewSection,
587f75da0c8SAlexey Lapshin                   function_ref<Error(StringRef, ArrayRef<uint8_t>)> F) {
588a6f3fedcSAlexey Lapshin   ArrayRef<uint8_t> Data(reinterpret_cast<const uint8_t *>(
589a6f3fedcSAlexey Lapshin                              NewSection.SectionData->getBufferStart()),
590a6f3fedcSAlexey Lapshin                          NewSection.SectionData->getBufferSize());
591a6f3fedcSAlexey Lapshin   return F(NewSection.SectionName, Data);
592f75da0c8SAlexey Lapshin }
593f75da0c8SAlexey Lapshin 
594f75da0c8SAlexey Lapshin // This function handles the high level operations of GNU objcopy including
595f75da0c8SAlexey Lapshin // handling command line options. It's important to outline certain properties
596f75da0c8SAlexey Lapshin // we expect to hold of the command line operations. Any operation that "keeps"
597f75da0c8SAlexey Lapshin // should keep regardless of a remove. Additionally any removal should respect
598f75da0c8SAlexey Lapshin // any previous removals. Lastly whether or not something is removed shouldn't
599f75da0c8SAlexey Lapshin // depend a) on the order the options occur in or b) on some opaque priority
600f75da0c8SAlexey Lapshin // system. The only priority is that keeps/copies overrule removes.
601f75da0c8SAlexey Lapshin static Error handleArgs(const CommonConfig &Config, const ELFConfig &ELFConfig,
602f75da0c8SAlexey Lapshin                         Object &Obj) {
603f75da0c8SAlexey Lapshin   if (Config.OutputArch) {
6043b7c3a65SKazu Hirata     Obj.Machine = Config.OutputArch.getValue().EMachine;
6053b7c3a65SKazu Hirata     Obj.OSABI = Config.OutputArch.getValue().OSABI;
606f75da0c8SAlexey Lapshin   }
607f75da0c8SAlexey Lapshin 
608f75da0c8SAlexey Lapshin   if (!Config.SplitDWO.empty() && Config.ExtractDWO) {
609f75da0c8SAlexey Lapshin     return Obj.removeSections(
610f75da0c8SAlexey Lapshin         ELFConfig.AllowBrokenLinks,
611f75da0c8SAlexey Lapshin         [&Obj](const SectionBase &Sec) { return onlyKeepDWOPred(Obj, Sec); });
612f75da0c8SAlexey Lapshin   }
613f75da0c8SAlexey Lapshin 
614f75da0c8SAlexey Lapshin   // Dump sections before add/remove for compatibility with GNU objcopy.
615f75da0c8SAlexey Lapshin   for (StringRef Flag : Config.DumpSection) {
616f75da0c8SAlexey Lapshin     StringRef SectionName;
617f75da0c8SAlexey Lapshin     StringRef FileName;
618f75da0c8SAlexey Lapshin     std::tie(SectionName, FileName) = Flag.split('=');
619f75da0c8SAlexey Lapshin     if (Error E = dumpSectionToFile(SectionName, FileName, Obj))
620f75da0c8SAlexey Lapshin       return E;
621f75da0c8SAlexey Lapshin   }
622f75da0c8SAlexey Lapshin 
623f75da0c8SAlexey Lapshin   // It is important to remove the sections first. For example, we want to
624f75da0c8SAlexey Lapshin   // remove the relocation sections before removing the symbols. That allows
625f75da0c8SAlexey Lapshin   // us to avoid reporting the inappropriate errors about removing symbols
626f75da0c8SAlexey Lapshin   // named in relocations.
627f75da0c8SAlexey Lapshin   if (Error E = replaceAndRemoveSections(Config, ELFConfig, Obj))
628f75da0c8SAlexey Lapshin     return E;
629f75da0c8SAlexey Lapshin 
630f75da0c8SAlexey Lapshin   if (Error E = updateAndRemoveSymbols(Config, ELFConfig, Obj))
631f75da0c8SAlexey Lapshin     return E;
632f75da0c8SAlexey Lapshin 
633f75da0c8SAlexey Lapshin   if (!Config.SectionsToRename.empty()) {
634f75da0c8SAlexey Lapshin     std::vector<RelocationSectionBase *> RelocSections;
635f75da0c8SAlexey Lapshin     DenseSet<SectionBase *> RenamedSections;
636f75da0c8SAlexey Lapshin     for (SectionBase &Sec : Obj.sections()) {
637f75da0c8SAlexey Lapshin       auto *RelocSec = dyn_cast<RelocationSectionBase>(&Sec);
638f75da0c8SAlexey Lapshin       const auto Iter = Config.SectionsToRename.find(Sec.Name);
639f75da0c8SAlexey Lapshin       if (Iter != Config.SectionsToRename.end()) {
640f75da0c8SAlexey Lapshin         const SectionRename &SR = Iter->second;
641f75da0c8SAlexey Lapshin         Sec.Name = std::string(SR.NewName);
642*a7938c74SKazu Hirata         if (SR.NewFlags)
6433b7c3a65SKazu Hirata           setSectionFlagsAndType(Sec, SR.NewFlags.getValue());
644f75da0c8SAlexey Lapshin         RenamedSections.insert(&Sec);
645f75da0c8SAlexey Lapshin       } else if (RelocSec && !(Sec.Flags & SHF_ALLOC))
646f75da0c8SAlexey Lapshin         // Postpone processing relocation sections which are not specified in
647f75da0c8SAlexey Lapshin         // their explicit '--rename-section' commands until after their target
648f75da0c8SAlexey Lapshin         // sections are renamed.
649f75da0c8SAlexey Lapshin         // Dynamic relocation sections (i.e. ones with SHF_ALLOC) should be
650f75da0c8SAlexey Lapshin         // renamed only explicitly. Otherwise, renaming, for example, '.got.plt'
651f75da0c8SAlexey Lapshin         // would affect '.rela.plt', which is not desirable.
652f75da0c8SAlexey Lapshin         RelocSections.push_back(RelocSec);
653f75da0c8SAlexey Lapshin     }
654f75da0c8SAlexey Lapshin 
655f75da0c8SAlexey Lapshin     // Rename relocation sections according to their target sections.
656f75da0c8SAlexey Lapshin     for (RelocationSectionBase *RelocSec : RelocSections) {
657f75da0c8SAlexey Lapshin       auto Iter = RenamedSections.find(RelocSec->getSection());
658f75da0c8SAlexey Lapshin       if (Iter != RenamedSections.end())
659f75da0c8SAlexey Lapshin         RelocSec->Name = (RelocSec->getNamePrefix() + (*Iter)->Name).str();
660f75da0c8SAlexey Lapshin     }
661f75da0c8SAlexey Lapshin   }
662f75da0c8SAlexey Lapshin 
663f75da0c8SAlexey Lapshin   // Add a prefix to allocated sections and their relocation sections. This
664f75da0c8SAlexey Lapshin   // should be done after renaming the section by Config.SectionToRename to
665f75da0c8SAlexey Lapshin   // imitate the GNU objcopy behavior.
666f75da0c8SAlexey Lapshin   if (!Config.AllocSectionsPrefix.empty()) {
667f75da0c8SAlexey Lapshin     DenseSet<SectionBase *> PrefixedSections;
668f75da0c8SAlexey Lapshin     for (SectionBase &Sec : Obj.sections()) {
669f75da0c8SAlexey Lapshin       if (Sec.Flags & SHF_ALLOC) {
670f75da0c8SAlexey Lapshin         Sec.Name = (Config.AllocSectionsPrefix + Sec.Name).str();
671f75da0c8SAlexey Lapshin         PrefixedSections.insert(&Sec);
672f75da0c8SAlexey Lapshin       } else if (auto *RelocSec = dyn_cast<RelocationSectionBase>(&Sec)) {
673f75da0c8SAlexey Lapshin         // Rename relocation sections associated to the allocated sections.
674f75da0c8SAlexey Lapshin         // For example, if we rename .text to .prefix.text, we also rename
675f75da0c8SAlexey Lapshin         // .rel.text to .rel.prefix.text.
676f75da0c8SAlexey Lapshin         //
677f75da0c8SAlexey Lapshin         // Dynamic relocation sections (SHT_REL[A] with SHF_ALLOC) are handled
678f75da0c8SAlexey Lapshin         // above, e.g., .rela.plt is renamed to .prefix.rela.plt, not
679f75da0c8SAlexey Lapshin         // .rela.prefix.plt since GNU objcopy does so.
680f75da0c8SAlexey Lapshin         const SectionBase *TargetSec = RelocSec->getSection();
681f75da0c8SAlexey Lapshin         if (TargetSec && (TargetSec->Flags & SHF_ALLOC)) {
682f75da0c8SAlexey Lapshin           // If the relocation section comes *after* the target section, we
683f75da0c8SAlexey Lapshin           // don't add Config.AllocSectionsPrefix because we've already added
684f75da0c8SAlexey Lapshin           // the prefix to TargetSec->Name. Otherwise, if the relocation
685f75da0c8SAlexey Lapshin           // section comes *before* the target section, we add the prefix.
686f75da0c8SAlexey Lapshin           if (PrefixedSections.count(TargetSec))
687f75da0c8SAlexey Lapshin             Sec.Name = (RelocSec->getNamePrefix() + TargetSec->Name).str();
688f75da0c8SAlexey Lapshin           else
689f75da0c8SAlexey Lapshin             Sec.Name = (RelocSec->getNamePrefix() + Config.AllocSectionsPrefix +
690f75da0c8SAlexey Lapshin                         TargetSec->Name)
691f75da0c8SAlexey Lapshin                            .str();
692f75da0c8SAlexey Lapshin         }
693f75da0c8SAlexey Lapshin       }
694f75da0c8SAlexey Lapshin     }
695f75da0c8SAlexey Lapshin   }
696f75da0c8SAlexey Lapshin 
697f75da0c8SAlexey Lapshin   if (!Config.SetSectionAlignment.empty()) {
698f75da0c8SAlexey Lapshin     for (SectionBase &Sec : Obj.sections()) {
699f75da0c8SAlexey Lapshin       auto I = Config.SetSectionAlignment.find(Sec.Name);
700f75da0c8SAlexey Lapshin       if (I != Config.SetSectionAlignment.end())
701f75da0c8SAlexey Lapshin         Sec.Align = I->second;
702f75da0c8SAlexey Lapshin     }
703f75da0c8SAlexey Lapshin   }
704f75da0c8SAlexey Lapshin 
705f75da0c8SAlexey Lapshin   if (Config.OnlyKeepDebug)
706f75da0c8SAlexey Lapshin     for (auto &Sec : Obj.sections())
707f75da0c8SAlexey Lapshin       if (Sec.Flags & SHF_ALLOC && Sec.Type != SHT_NOTE)
708f75da0c8SAlexey Lapshin         Sec.Type = SHT_NOBITS;
709f75da0c8SAlexey Lapshin 
710a6f3fedcSAlexey Lapshin   for (const NewSectionInfo &AddedSection : Config.AddSection) {
711f75da0c8SAlexey Lapshin     auto AddSection = [&](StringRef Name, ArrayRef<uint8_t> Data) {
712f75da0c8SAlexey Lapshin       OwnedDataSection &NewSection =
713f75da0c8SAlexey Lapshin           Obj.addSection<OwnedDataSection>(Name, Data);
714f75da0c8SAlexey Lapshin       if (Name.startswith(".note") && Name != ".note.GNU-stack")
715f75da0c8SAlexey Lapshin         NewSection.Type = SHT_NOTE;
716f75da0c8SAlexey Lapshin       return Error::success();
717f75da0c8SAlexey Lapshin     };
718a6f3fedcSAlexey Lapshin     if (Error E = handleUserSection(AddedSection, AddSection))
719f75da0c8SAlexey Lapshin       return E;
720f75da0c8SAlexey Lapshin   }
721f75da0c8SAlexey Lapshin 
722a6f3fedcSAlexey Lapshin   for (const NewSectionInfo &NewSection : Config.UpdateSection) {
723f75da0c8SAlexey Lapshin     auto UpdateSection = [&](StringRef Name, ArrayRef<uint8_t> Data) {
724f75da0c8SAlexey Lapshin       return Obj.updateSection(Name, Data);
725f75da0c8SAlexey Lapshin     };
726a6f3fedcSAlexey Lapshin     if (Error E = handleUserSection(NewSection, UpdateSection))
727f75da0c8SAlexey Lapshin       return E;
728f75da0c8SAlexey Lapshin   }
729f75da0c8SAlexey Lapshin 
730f75da0c8SAlexey Lapshin   if (!Config.AddGnuDebugLink.empty())
731f75da0c8SAlexey Lapshin     Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink,
732f75da0c8SAlexey Lapshin                                         Config.GnuDebugLinkCRC32);
733f75da0c8SAlexey Lapshin 
734f75da0c8SAlexey Lapshin   // If the symbol table was previously removed, we need to create a new one
735f75da0c8SAlexey Lapshin   // before adding new symbols.
736f75da0c8SAlexey Lapshin   if (!Obj.SymbolTable && !Config.SymbolsToAdd.empty())
737f75da0c8SAlexey Lapshin     if (Error E = Obj.addNewSymbolTable())
738f75da0c8SAlexey Lapshin       return E;
739f75da0c8SAlexey Lapshin 
740f75da0c8SAlexey Lapshin   for (const NewSymbolInfo &SI : Config.SymbolsToAdd)
741f75da0c8SAlexey Lapshin     addSymbol(Obj, SI, ELFConfig.NewSymbolVisibility);
742f75da0c8SAlexey Lapshin 
743f75da0c8SAlexey Lapshin   // --set-section-flags works with sections added by --add-section.
744f75da0c8SAlexey Lapshin   if (!Config.SetSectionFlags.empty()) {
745f75da0c8SAlexey Lapshin     for (auto &Sec : Obj.sections()) {
746f75da0c8SAlexey Lapshin       const auto Iter = Config.SetSectionFlags.find(Sec.Name);
747f75da0c8SAlexey Lapshin       if (Iter != Config.SetSectionFlags.end()) {
748f75da0c8SAlexey Lapshin         const SectionFlagsUpdate &SFU = Iter->second;
749f75da0c8SAlexey Lapshin         setSectionFlagsAndType(Sec, SFU.NewFlags);
750f75da0c8SAlexey Lapshin       }
751f75da0c8SAlexey Lapshin     }
752f75da0c8SAlexey Lapshin   }
753f75da0c8SAlexey Lapshin 
754f75da0c8SAlexey Lapshin   if (ELFConfig.EntryExpr)
755f75da0c8SAlexey Lapshin     Obj.Entry = ELFConfig.EntryExpr(Obj.Entry);
756f75da0c8SAlexey Lapshin   return Error::success();
757f75da0c8SAlexey Lapshin }
758f75da0c8SAlexey Lapshin 
759f75da0c8SAlexey Lapshin static Error writeOutput(const CommonConfig &Config, Object &Obj,
760f75da0c8SAlexey Lapshin                          raw_ostream &Out, ElfType OutputElfType) {
761f75da0c8SAlexey Lapshin   std::unique_ptr<Writer> Writer =
762f75da0c8SAlexey Lapshin       createWriter(Config, Obj, Out, OutputElfType);
763f75da0c8SAlexey Lapshin   if (Error E = Writer->finalize())
764f75da0c8SAlexey Lapshin     return E;
765f75da0c8SAlexey Lapshin   return Writer->write();
766f75da0c8SAlexey Lapshin }
767f75da0c8SAlexey Lapshin 
768f75da0c8SAlexey Lapshin Error objcopy::elf::executeObjcopyOnIHex(const CommonConfig &Config,
769f75da0c8SAlexey Lapshin                                          const ELFConfig &ELFConfig,
770f75da0c8SAlexey Lapshin                                          MemoryBuffer &In, raw_ostream &Out) {
771f75da0c8SAlexey Lapshin   IHexReader Reader(&In);
772f75da0c8SAlexey Lapshin   Expected<std::unique_ptr<Object>> Obj = Reader.create(true);
773f75da0c8SAlexey Lapshin   if (!Obj)
774f75da0c8SAlexey Lapshin     return Obj.takeError();
775f75da0c8SAlexey Lapshin 
776f75da0c8SAlexey Lapshin   const ElfType OutputElfType =
777129b531cSKazu Hirata       getOutputElfType(Config.OutputArch.value_or(MachineInfo()));
778f75da0c8SAlexey Lapshin   if (Error E = handleArgs(Config, ELFConfig, **Obj))
779f75da0c8SAlexey Lapshin     return E;
780f75da0c8SAlexey Lapshin   return writeOutput(Config, **Obj, Out, OutputElfType);
781f75da0c8SAlexey Lapshin }
782f75da0c8SAlexey Lapshin 
783f75da0c8SAlexey Lapshin Error objcopy::elf::executeObjcopyOnRawBinary(const CommonConfig &Config,
784f75da0c8SAlexey Lapshin                                               const ELFConfig &ELFConfig,
785f75da0c8SAlexey Lapshin                                               MemoryBuffer &In,
786f75da0c8SAlexey Lapshin                                               raw_ostream &Out) {
787f75da0c8SAlexey Lapshin   BinaryReader Reader(&In, ELFConfig.NewSymbolVisibility);
788f75da0c8SAlexey Lapshin   Expected<std::unique_ptr<Object>> Obj = Reader.create(true);
789f75da0c8SAlexey Lapshin   if (!Obj)
790f75da0c8SAlexey Lapshin     return Obj.takeError();
791f75da0c8SAlexey Lapshin 
792f75da0c8SAlexey Lapshin   // Prefer OutputArch (-O<format>) if set, otherwise fallback to BinaryArch
793f75da0c8SAlexey Lapshin   // (-B<arch>).
794f75da0c8SAlexey Lapshin   const ElfType OutputElfType =
795129b531cSKazu Hirata       getOutputElfType(Config.OutputArch.value_or(MachineInfo()));
796f75da0c8SAlexey Lapshin   if (Error E = handleArgs(Config, ELFConfig, **Obj))
797f75da0c8SAlexey Lapshin     return E;
798f75da0c8SAlexey Lapshin   return writeOutput(Config, **Obj, Out, OutputElfType);
799f75da0c8SAlexey Lapshin }
800f75da0c8SAlexey Lapshin 
801f75da0c8SAlexey Lapshin Error objcopy::elf::executeObjcopyOnBinary(const CommonConfig &Config,
802f75da0c8SAlexey Lapshin                                            const ELFConfig &ELFConfig,
803f75da0c8SAlexey Lapshin                                            object::ELFObjectFileBase &In,
804f75da0c8SAlexey Lapshin                                            raw_ostream &Out) {
805f75da0c8SAlexey Lapshin   ELFReader Reader(&In, Config.ExtractPartition);
806f75da0c8SAlexey Lapshin   Expected<std::unique_ptr<Object>> Obj =
807f75da0c8SAlexey Lapshin       Reader.create(!Config.SymbolsToAdd.empty());
808f75da0c8SAlexey Lapshin   if (!Obj)
809f75da0c8SAlexey Lapshin     return Obj.takeError();
810f75da0c8SAlexey Lapshin   // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
8113b7c3a65SKazu Hirata   const ElfType OutputElfType =
8123b7c3a65SKazu Hirata       Config.OutputArch ? getOutputElfType(Config.OutputArch.getValue())
813f75da0c8SAlexey Lapshin                         : getOutputElfType(In);
814f75da0c8SAlexey Lapshin 
815f75da0c8SAlexey Lapshin   if (Error E = handleArgs(Config, ELFConfig, **Obj))
816f75da0c8SAlexey Lapshin     return createFileError(Config.InputFilename, std::move(E));
817f75da0c8SAlexey Lapshin 
818f75da0c8SAlexey Lapshin   if (Error E = writeOutput(Config, **Obj, Out, OutputElfType))
819f75da0c8SAlexey Lapshin     return createFileError(Config.InputFilename, std::move(E));
820f75da0c8SAlexey Lapshin 
821f75da0c8SAlexey Lapshin   return Error::success();
822f75da0c8SAlexey Lapshin }
823