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