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