blob: 9b21190000e2070cb1ff9bcdce331f7295750956 [file] [log] [blame]
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +00001//===- ELFObjcopy.cpp -----------------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "ELFObjcopy.h"
10#include "Buffer.h"
11#include "CopyConfig.h"
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +000012#include "Object.h"
Jake Ehrlich8ad77792018-12-03 19:49:23 +000013#include "llvm-objcopy.h"
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +000014
15#include "llvm/ADT/BitmaskEnum.h"
16#include "llvm/ADT/Optional.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/ADT/Twine.h"
21#include "llvm/BinaryFormat/ELF.h"
22#include "llvm/MC/MCTargetOptions.h"
23#include "llvm/Object/Binary.h"
24#include "llvm/Object/ELFObjectFile.h"
25#include "llvm/Object/ELFTypes.h"
26#include "llvm/Object/Error.h"
27#include "llvm/Option/Option.h"
28#include "llvm/Support/Casting.h"
29#include "llvm/Support/Compression.h"
Jake Ehrlich8ad77792018-12-03 19:49:23 +000030#include "llvm/Support/Errc.h"
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +000031#include "llvm/Support/Error.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/ErrorOr.h"
34#include "llvm/Support/Memory.h"
35#include "llvm/Support/Path.h"
36#include "llvm/Support/raw_ostream.h"
37#include <algorithm>
38#include <cassert>
39#include <cstdlib>
40#include <functional>
41#include <iterator>
42#include <memory>
43#include <string>
44#include <system_error>
45#include <utility>
46
47namespace llvm {
48namespace objcopy {
49namespace elf {
50
51using namespace object;
52using namespace ELF;
53using SectionPred = std::function<bool(const SectionBase &Sec)>;
54
55static bool isDebugSection(const SectionBase &Sec) {
56 return StringRef(Sec.Name).startswith(".debug") ||
57 StringRef(Sec.Name).startswith(".zdebug") || Sec.Name == ".gdb_index";
58}
59
60static bool isDWOSection(const SectionBase &Sec) {
61 return StringRef(Sec.Name).endswith(".dwo");
62}
63
64static bool onlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
65 // We can't remove the section header string table.
66 if (&Sec == Obj.SectionNames)
67 return false;
68 // Short of keeping the string table we want to keep everything that is a DWO
69 // section and remove everything else.
70 return !isDWOSection(Sec);
71}
72
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +000073uint64_t getNewShfFlags(SectionFlag AllFlags) {
74 uint64_t NewFlags = 0;
75 if (AllFlags & SectionFlag::SecAlloc)
76 NewFlags |= ELF::SHF_ALLOC;
77 if (!(AllFlags & SectionFlag::SecReadonly))
78 NewFlags |= ELF::SHF_WRITE;
79 if (AllFlags & SectionFlag::SecCode)
80 NewFlags |= ELF::SHF_EXECINSTR;
81 if (AllFlags & SectionFlag::SecMerge)
82 NewFlags |= ELF::SHF_MERGE;
83 if (AllFlags & SectionFlag::SecStrings)
84 NewFlags |= ELF::SHF_STRINGS;
85 return NewFlags;
86}
87
Jordan Rupprecht017deaf2019-04-02 16:49:56 +000088static uint64_t getSectionFlagsPreserveMask(uint64_t OldFlags,
Jordan Rupprechtc8927412019-01-29 15:05:38 +000089 uint64_t NewFlags) {
90 // Preserve some flags which should not be dropped when setting flags.
91 // Also, preserve anything OS/processor dependant.
92 const uint64_t PreserveMask = ELF::SHF_COMPRESSED | ELF::SHF_EXCLUDE |
93 ELF::SHF_GROUP | ELF::SHF_LINK_ORDER |
94 ELF::SHF_MASKOS | ELF::SHF_MASKPROC |
95 ELF::SHF_TLS | ELF::SHF_INFO_LINK;
96 return (OldFlags & PreserveMask) | (NewFlags & ~PreserveMask);
97}
98
Jordan Rupprecht017deaf2019-04-02 16:49:56 +000099static void setSectionFlagsAndType(SectionBase &Sec, SectionFlag Flags) {
100 Sec.Flags = getSectionFlagsPreserveMask(Sec.Flags, getNewShfFlags(Flags));
101
Fangrui Songaa1f2c52019-05-01 00:39:31 +0000102 // In GNU objcopy, certain flags promote SHT_NOBITS to SHT_PROGBITS. This rule
103 // may promote more non-ALLOC sections than GNU objcopy, but it is fine as
104 // non-ALLOC SHT_NOBITS sections do not make much sense.
105 if (Sec.Type == SHT_NOBITS &&
106 (!(Sec.Flags & ELF::SHF_ALLOC) ||
107 Flags & (SectionFlag::SecContents | SectionFlag::SecLoad)))
Jordan Rupprecht017deaf2019-04-02 16:49:56 +0000108 Sec.Type = SHT_PROGBITS;
109}
110
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000111static ElfType getOutputElfType(const Binary &Bin) {
112 // Infer output ELF type from the input ELF object
113 if (isa<ELFObjectFile<ELF32LE>>(Bin))
114 return ELFT_ELF32LE;
115 if (isa<ELFObjectFile<ELF64LE>>(Bin))
116 return ELFT_ELF64LE;
117 if (isa<ELFObjectFile<ELF32BE>>(Bin))
118 return ELFT_ELF32BE;
119 if (isa<ELFObjectFile<ELF64BE>>(Bin))
120 return ELFT_ELF64BE;
121 llvm_unreachable("Invalid ELFType");
122}
123
124static ElfType getOutputElfType(const MachineInfo &MI) {
125 // Infer output ELF type from the binary arch specified
126 if (MI.Is64Bit)
127 return MI.IsLittleEndian ? ELFT_ELF64LE : ELFT_ELF64BE;
128 else
129 return MI.IsLittleEndian ? ELFT_ELF32LE : ELFT_ELF32BE;
130}
131
132static std::unique_ptr<Writer> createWriter(const CopyConfig &Config,
133 Object &Obj, Buffer &Buf,
134 ElfType OutputElfType) {
135 if (Config.OutputFormat == "binary") {
136 return llvm::make_unique<BinaryWriter>(Obj, Buf);
137 }
138 // Depending on the initial ELFT and OutputFormat we need a different Writer.
139 switch (OutputElfType) {
140 case ELFT_ELF32LE:
141 return llvm::make_unique<ELFWriter<ELF32LE>>(Obj, Buf,
142 !Config.StripSections);
143 case ELFT_ELF64LE:
144 return llvm::make_unique<ELFWriter<ELF64LE>>(Obj, Buf,
145 !Config.StripSections);
146 case ELFT_ELF32BE:
147 return llvm::make_unique<ELFWriter<ELF32BE>>(Obj, Buf,
148 !Config.StripSections);
149 case ELFT_ELF64BE:
150 return llvm::make_unique<ELFWriter<ELF64BE>>(Obj, Buf,
151 !Config.StripSections);
152 }
153 llvm_unreachable("Invalid output format");
154}
155
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000156template <class ELFT>
157static Expected<ArrayRef<uint8_t>>
158findBuildID(const object::ELFFile<ELFT> &In) {
159 for (const auto &Phdr : unwrapOrError(In.program_headers())) {
160 if (Phdr.p_type != PT_NOTE)
161 continue;
162 Error Err = Error::success();
David Blaikieba005aa2018-12-11 00:09:06 +0000163 for (const auto &Note : In.notes(Phdr, Err))
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000164 if (Note.getType() == NT_GNU_BUILD_ID && Note.getName() == ELF_NOTE_GNU)
165 return Note.getDesc();
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000166 if (Err)
167 return std::move(Err);
168 }
169 return createStringError(llvm::errc::invalid_argument,
170 "Could not find build ID.");
171}
172
173static Expected<ArrayRef<uint8_t>>
174findBuildID(const object::ELFObjectFileBase &In) {
175 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(&In))
176 return findBuildID(*O->getELFFile());
177 else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(&In))
178 return findBuildID(*O->getELFFile());
179 else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(&In))
180 return findBuildID(*O->getELFFile());
181 else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(&In))
182 return findBuildID(*O->getELFFile());
183
184 llvm_unreachable("Bad file format");
185}
186
Jake Ehrlich5049c342019-03-18 20:35:18 +0000187template <class... Ts>
188static Error makeStringError(std::error_code EC, const Twine &Msg, Ts&&... Args) {
189 std::string FullMsg = (EC.message() + ": " + Msg).str();
190 return createStringError(EC, FullMsg.c_str(), std::forward<Ts>(Args)...);
191}
192
193#define MODEL_8 "%%%%%%%%"
194#define MODEL_16 MODEL_8 MODEL_8
195#define MODEL_32 (MODEL_16 MODEL_16)
196
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000197static Error linkToBuildIdDir(const CopyConfig &Config, StringRef ToLink,
198 StringRef Suffix,
199 ArrayRef<uint8_t> BuildIdBytes) {
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000200 SmallString<128> Path = Config.BuildIdLinkDir;
201 sys::path::append(Path, llvm::toHex(BuildIdBytes[0], /*LowerCase*/ true));
202 if (auto EC = sys::fs::create_directories(Path))
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000203 return createFileError(
204 Path.str(),
Jake Ehrlich5049c342019-03-18 20:35:18 +0000205 makeStringError(EC, "cannot create build ID link directory"));
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000206
207 sys::path::append(Path,
208 llvm::toHex(BuildIdBytes.slice(1), /*LowerCase*/ true));
209 Path += Suffix;
Jake Ehrlich5049c342019-03-18 20:35:18 +0000210 SmallString<128> TmpPath;
211 // create_hard_link races so we need to link to a temporary path but
212 // we want to make sure that we choose a filename that does not exist.
213 // By using 32 model characters we get 128-bits of entropy. It is
214 // unlikely that this string has ever existed before much less exists
215 // on this disk or in the current working directory.
216 // Additionally we prepend the original Path for debugging but also
217 // because it ensures that we're linking within a directory on the same
218 // partition on the same device which is critical. It has the added
219 // win of yet further decreasing the odds of a conflict.
220 sys::fs::createUniquePath(Twine(Path) + "-" + MODEL_32 + ".tmp", TmpPath,
221 /*MakeAbsolute*/ false);
222 if (auto EC = sys::fs::create_hard_link(ToLink, TmpPath)) {
223 Path.push_back('\0');
224 return makeStringError(EC, "cannot link %s to %s", ToLink.data(),
225 Path.data());
226 }
227 // We then atomically rename the link into place which will just move the
228 // link. If rename fails something is more seriously wrong so just return
229 // an error.
230 if (auto EC = sys::fs::rename(TmpPath, Path)) {
231 Path.push_back('\0');
232 return makeStringError(EC, "cannot link %s to %s", ToLink.data(),
233 Path.data());
234 }
235 // If `Path` was already a hard-link to the same underlying file then the
236 // temp file will be left so we need to remove it. Remove will not cause
237 // an error by default if the file is already gone so just blindly remove
238 // it rather than checking.
239 if (auto EC = sys::fs::remove(TmpPath)) {
240 TmpPath.push_back('\0');
241 return makeStringError(EC, "could not remove %s", TmpPath.data());
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000242 }
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000243 return Error::success();
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000244}
245
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000246static Error splitDWOToFile(const CopyConfig &Config, const Reader &Reader,
247 StringRef File, ElfType OutputElfType) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000248 auto DWOFile = Reader.create();
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000249 auto OnlyKeepDWOPred = [&DWOFile](const SectionBase &Sec) {
250 return onlyKeepDWOPred(*DWOFile, Sec);
251 };
James Henderson66a9d0f2019-04-18 09:13:30 +0000252 if (Error E = DWOFile->removeSections(Config.AllowBrokenLinks,
253 OnlyKeepDWOPred))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000254 return E;
James Hendersonc040d5d2019-03-22 10:21:09 +0000255 if (Config.OutputArch) {
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000256 DWOFile->Machine = Config.OutputArch.getValue().EMachine;
James Hendersonc040d5d2019-03-22 10:21:09 +0000257 DWOFile->OSABI = Config.OutputArch.getValue().OSABI;
258 }
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000259 FileBuffer FB(File);
260 auto Writer = createWriter(Config, *DWOFile, FB, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000261 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000262 return E;
263 return Writer->write();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000264}
265
266static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
267 Object &Obj) {
268 for (auto &Sec : Obj.sections()) {
269 if (Sec.Name == SecName) {
Jordan Rupprecht16a0de22018-12-20 00:57:06 +0000270 if (Sec.OriginalData.empty())
Martin Storsjo8010c6be2019-01-22 10:57:59 +0000271 return createStringError(
272 object_error::parse_failed,
273 "Can't dump section \"%s\": it has no contents",
274 SecName.str().c_str());
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000275 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
276 FileOutputBuffer::create(Filename, Sec.OriginalData.size());
277 if (!BufferOrErr)
278 return BufferOrErr.takeError();
279 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
280 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(),
281 Buf->getBufferStart());
282 if (Error E = Buf->commit())
283 return E;
284 return Error::success();
285 }
286 }
Martin Storsjo8010c6be2019-01-22 10:57:59 +0000287 return createStringError(object_error::parse_failed, "Section not found");
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000288}
289
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000290static bool isCompressable(const SectionBase &Section) {
George Rimarade3c702019-03-05 13:07:43 +0000291 return !(Section.Flags & ELF::SHF_COMPRESSED) &&
292 StringRef(Section.Name).startswith(".debug");
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000293}
294
295static void replaceDebugSections(
Fangrui Song3dfc3fb2019-03-15 10:27:28 +0000296 Object &Obj, SectionPred &RemovePred,
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000297 function_ref<bool(const SectionBase &)> shouldReplace,
298 function_ref<SectionBase *(const SectionBase *)> addSection) {
George Rimard8a5c6c2019-03-11 11:01:24 +0000299 // Build a list of the debug sections we are going to replace.
300 // We can't call `addSection` while iterating over sections,
301 // because it would mutate the sections array.
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000302 SmallVector<SectionBase *, 13> ToReplace;
George Rimard8a5c6c2019-03-11 11:01:24 +0000303 for (auto &Sec : Obj.sections())
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000304 if (shouldReplace(Sec))
305 ToReplace.push_back(&Sec);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000306
George Rimard8a5c6c2019-03-11 11:01:24 +0000307 // Build a mapping from original section to a new one.
308 DenseMap<SectionBase *, SectionBase *> FromTo;
309 for (SectionBase *S : ToReplace)
310 FromTo[S] = addSection(S);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000311
George Rimard8a5c6c2019-03-11 11:01:24 +0000312 // Now we want to update the target sections of relocation
313 // sections. Also we will update the relocations themselves
314 // to update the symbol references.
315 for (auto &Sec : Obj.sections())
316 Sec.replaceSectionReferences(FromTo);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000317
318 RemovePred = [shouldReplace, RemovePred](const SectionBase &Sec) {
319 return shouldReplace(Sec) || RemovePred(Sec);
320 };
321}
322
Eugene Leviant2db10622019-02-13 07:34:54 +0000323static bool isUnneededSymbol(const Symbol &Sym) {
324 return !Sym.Referenced &&
325 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
326 Sym.Type != STT_FILE && Sym.Type != STT_SECTION;
327}
328
George Rimare6963be2019-03-25 12:34:25 +0000329static Error updateAndRemoveSymbols(const CopyConfig &Config, Object &Obj) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000330 // TODO: update or remove symbols only if there is an option that affects
331 // them.
George Rimare6963be2019-03-25 12:34:25 +0000332 if (!Obj.SymbolTable)
333 return Error::success();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000334
George Rimare6963be2019-03-25 12:34:25 +0000335 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
336 // Common and undefined symbols don't make sense as local symbols, and can
337 // even cause crashes if we localize those, so skip them.
338 if (!Sym.isCommon() && Sym.getShndx() != SHN_UNDEF &&
339 ((Config.LocalizeHidden &&
340 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
341 is_contained(Config.SymbolsToLocalize, Sym.Name)))
342 Sym.Binding = STB_LOCAL;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000343
George Rimare6963be2019-03-25 12:34:25 +0000344 // Note: these two globalize flags have very similar names but different
345 // meanings:
346 //
347 // --globalize-symbol: promote a symbol to global
348 // --keep-global-symbol: all symbols except for these should be made local
349 //
350 // If --globalize-symbol is specified for a given symbol, it will be
351 // global in the output file even if it is not included via
352 // --keep-global-symbol. Because of that, make sure to check
353 // --globalize-symbol second.
354 if (!Config.SymbolsToKeepGlobal.empty() &&
355 !is_contained(Config.SymbolsToKeepGlobal, Sym.Name) &&
356 Sym.getShndx() != SHN_UNDEF)
357 Sym.Binding = STB_LOCAL;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000358
George Rimare6963be2019-03-25 12:34:25 +0000359 if (is_contained(Config.SymbolsToGlobalize, Sym.Name) &&
360 Sym.getShndx() != SHN_UNDEF)
361 Sym.Binding = STB_GLOBAL;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000362
George Rimare6963be2019-03-25 12:34:25 +0000363 if (is_contained(Config.SymbolsToWeaken, Sym.Name) &&
364 Sym.Binding == STB_GLOBAL)
365 Sym.Binding = STB_WEAK;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000366
George Rimare6963be2019-03-25 12:34:25 +0000367 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
368 Sym.getShndx() != SHN_UNDEF)
369 Sym.Binding = STB_WEAK;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000370
George Rimare6963be2019-03-25 12:34:25 +0000371 const auto I = Config.SymbolsToRename.find(Sym.Name);
372 if (I != Config.SymbolsToRename.end())
373 Sym.Name = I->getValue();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000374
George Rimare6963be2019-03-25 12:34:25 +0000375 if (!Config.SymbolsPrefix.empty() && Sym.Type != STT_SECTION)
376 Sym.Name = (Config.SymbolsPrefix + Sym.Name).str();
377 });
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000378
George Rimare6963be2019-03-25 12:34:25 +0000379 // The purpose of this loop is to mark symbols referenced by sections
380 // (like GroupSection or RelocationSection). This way, we know which
381 // symbols are still 'needed' and which are not.
382 if (Config.StripUnneeded || !Config.UnneededSymbolsToRemove.empty()) {
383 for (auto &Section : Obj.sections())
384 Section.markSymbols();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000385 }
386
George Rimare6963be2019-03-25 12:34:25 +0000387 auto RemoveSymbolsPred = [&](const Symbol &Sym) {
388 if (is_contained(Config.SymbolsToKeep, Sym.Name) ||
389 (Config.KeepFileSymbols && Sym.Type == STT_FILE))
390 return false;
391
392 if ((Config.DiscardMode == DiscardType::All ||
393 (Config.DiscardMode == DiscardType::Locals &&
394 StringRef(Sym.Name).startswith(".L"))) &&
395 Sym.Binding == STB_LOCAL && Sym.getShndx() != SHN_UNDEF &&
396 Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
397 return true;
398
399 if (Config.StripAll || Config.StripAllGNU)
400 return true;
401
402 if (is_contained(Config.SymbolsToRemove, Sym.Name))
403 return true;
404
405 if ((Config.StripUnneeded ||
406 is_contained(Config.UnneededSymbolsToRemove, Sym.Name)) &&
407 isUnneededSymbol(Sym))
408 return true;
409
410 return false;
411 };
412
413 return Obj.removeSymbols(RemoveSymbolsPred);
414}
415
416static Error replaceAndRemoveSections(const CopyConfig &Config, Object &Obj) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000417 SectionPred RemovePred = [](const SectionBase &) { return false; };
418
419 // Removes:
420 if (!Config.ToRemove.empty()) {
421 RemovePred = [&Config](const SectionBase &Sec) {
422 return is_contained(Config.ToRemove, Sec.Name);
423 };
424 }
425
426 if (Config.StripDWO || !Config.SplitDWO.empty())
427 RemovePred = [RemovePred](const SectionBase &Sec) {
428 return isDWOSection(Sec) || RemovePred(Sec);
429 };
430
431 if (Config.ExtractDWO)
432 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
433 return onlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
434 };
435
436 if (Config.StripAllGNU)
437 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
438 if (RemovePred(Sec))
439 return true;
440 if ((Sec.Flags & SHF_ALLOC) != 0)
441 return false;
442 if (&Sec == Obj.SectionNames)
443 return false;
444 switch (Sec.Type) {
445 case SHT_SYMTAB:
446 case SHT_REL:
447 case SHT_RELA:
448 case SHT_STRTAB:
449 return true;
450 }
451 return isDebugSection(Sec);
452 };
453
454 if (Config.StripSections) {
455 RemovePred = [RemovePred](const SectionBase &Sec) {
James Hendersonb5de5e22019-03-14 11:47:41 +0000456 return RemovePred(Sec) || Sec.ParentSegment == nullptr;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000457 };
458 }
459
460 if (Config.StripDebug) {
461 RemovePred = [RemovePred](const SectionBase &Sec) {
462 return RemovePred(Sec) || isDebugSection(Sec);
463 };
464 }
465
466 if (Config.StripNonAlloc)
467 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
468 if (RemovePred(Sec))
469 return true;
470 if (&Sec == Obj.SectionNames)
471 return false;
James Hendersonb5de5e22019-03-14 11:47:41 +0000472 return (Sec.Flags & SHF_ALLOC) == 0 && Sec.ParentSegment == nullptr;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000473 };
474
475 if (Config.StripAll)
476 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
477 if (RemovePred(Sec))
478 return true;
479 if (&Sec == Obj.SectionNames)
480 return false;
481 if (StringRef(Sec.Name).startswith(".gnu.warning"))
482 return false;
James Hendersonb5de5e22019-03-14 11:47:41 +0000483 if (Sec.ParentSegment != nullptr)
484 return false;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000485 return (Sec.Flags & SHF_ALLOC) == 0;
486 };
487
488 // Explicit copies:
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000489 if (!Config.OnlySection.empty()) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000490 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
491 // Explicitly keep these sections regardless of previous removes.
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000492 if (is_contained(Config.OnlySection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000493 return false;
494
495 // Allow all implicit removes.
496 if (RemovePred(Sec))
497 return true;
498
499 // Keep special sections.
500 if (Obj.SectionNames == &Sec)
501 return false;
502 if (Obj.SymbolTable == &Sec ||
503 (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
504 return false;
505
506 // Remove everything else.
507 return true;
508 };
509 }
510
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000511 if (!Config.KeepSection.empty()) {
Fangrui Songe9f34b02018-11-12 23:46:22 +0000512 RemovePred = [&Config, RemovePred](const SectionBase &Sec) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000513 // Explicitly keep these sections regardless of previous removes.
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000514 if (is_contained(Config.KeepSection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000515 return false;
516 // Otherwise defer to RemovePred.
517 return RemovePred(Sec);
518 };
519 }
520
521 // This has to be the last predicate assignment.
522 // If the option --keep-symbol has been specified
523 // and at least one of those symbols is present
524 // (equivalently, the updated symbol table is not empty)
525 // the symbol table and the string table should not be removed.
526 if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) &&
527 Obj.SymbolTable && !Obj.SymbolTable->empty()) {
528 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
529 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
530 return false;
531 return RemovePred(Sec);
532 };
533 }
534
535 if (Config.CompressionType != DebugCompressionType::None)
Fangrui Song3dfc3fb2019-03-15 10:27:28 +0000536 replaceDebugSections(Obj, RemovePred, isCompressable,
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000537 [&Config, &Obj](const SectionBase *S) {
538 return &Obj.addSection<CompressedSection>(
539 *S, Config.CompressionType);
540 });
541 else if (Config.DecompressDebugSections)
542 replaceDebugSections(
Fangrui Song3dfc3fb2019-03-15 10:27:28 +0000543 Obj, RemovePred,
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000544 [](const SectionBase &S) { return isa<CompressedSection>(&S); },
545 [&Obj](const SectionBase *S) {
546 auto CS = cast<CompressedSection>(S);
547 return &Obj.addSection<DecompressedSection>(*CS);
548 });
549
James Henderson66a9d0f2019-04-18 09:13:30 +0000550 return Obj.removeSections(Config.AllowBrokenLinks, RemovePred);
George Rimare6963be2019-03-25 12:34:25 +0000551}
552
553// This function handles the high level operations of GNU objcopy including
554// handling command line options. It's important to outline certain properties
555// we expect to hold of the command line operations. Any operation that "keeps"
556// should keep regardless of a remove. Additionally any removal should respect
557// any previous removals. Lastly whether or not something is removed shouldn't
558// depend a) on the order the options occur in or b) on some opaque priority
559// system. The only priority is that keeps/copies overrule removes.
560static Error handleArgs(const CopyConfig &Config, Object &Obj,
561 const Reader &Reader, ElfType OutputElfType) {
562
563 if (!Config.SplitDWO.empty())
564 if (Error E =
565 splitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType))
566 return E;
567
568 if (Config.OutputArch) {
569 Obj.Machine = Config.OutputArch.getValue().EMachine;
570 Obj.OSABI = Config.OutputArch.getValue().OSABI;
571 }
572
George Rimar279898b2019-03-26 18:42:15 +0000573 // It is important to remove the sections first. For example, we want to
574 // remove the relocation sections before removing the symbols. That allows
575 // us to avoid reporting the inappropriate errors about removing symbols
576 // named in relocations.
577 if (Error E = replaceAndRemoveSections(Config, Obj))
George Rimare6963be2019-03-25 12:34:25 +0000578 return E;
579
George Rimar279898b2019-03-26 18:42:15 +0000580 if (Error E = updateAndRemoveSymbols(Config, Obj))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000581 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000582
583 if (!Config.SectionsToRename.empty()) {
584 for (auto &Sec : Obj.sections()) {
585 const auto Iter = Config.SectionsToRename.find(Sec.Name);
586 if (Iter != Config.SectionsToRename.end()) {
587 const SectionRename &SR = Iter->second;
588 Sec.Name = SR.NewName;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000589 if (SR.NewFlags.hasValue())
Jordan Rupprecht017deaf2019-04-02 16:49:56 +0000590 setSectionFlagsAndType(Sec, SR.NewFlags.getValue());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000591 }
592 }
593 }
594
595 if (!Config.SetSectionFlags.empty()) {
596 for (auto &Sec : Obj.sections()) {
597 const auto Iter = Config.SetSectionFlags.find(Sec.Name);
598 if (Iter != Config.SetSectionFlags.end()) {
599 const SectionFlagsUpdate &SFU = Iter->second;
Jordan Rupprecht017deaf2019-04-02 16:49:56 +0000600 setSectionFlagsAndType(Sec, SFU.NewFlags);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000601 }
602 }
603 }
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000604
Eugene Leviantc76671b2019-03-12 12:41:06 +0000605 for (const auto &Flag : Config.AddSection) {
606 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
607 StringRef SecName = SecPair.first;
608 StringRef File = SecPair.second;
609 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
610 MemoryBuffer::getFile(File);
611 if (!BufOrErr)
612 return createFileError(File, errorCodeToError(BufOrErr.getError()));
613 std::unique_ptr<MemoryBuffer> Buf = std::move(*BufOrErr);
614 ArrayRef<uint8_t> Data(
615 reinterpret_cast<const uint8_t *>(Buf->getBufferStart()),
616 Buf->getBufferSize());
617 OwnedDataSection &NewSection =
618 Obj.addSection<OwnedDataSection>(SecName, Data);
619 if (SecName.startswith(".note") && SecName != ".note.GNU-stack")
620 NewSection.Type = SHT_NOTE;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000621 }
622
Eugene Leviantc76671b2019-03-12 12:41:06 +0000623 for (const auto &Flag : Config.DumpSection) {
624 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
625 StringRef SecName = SecPair.first;
626 StringRef File = SecPair.second;
627 if (Error E = dumpSectionToFile(SecName, File, Obj))
628 return createFileError(Config.InputFilename, std::move(E));
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000629 }
630
631 if (!Config.AddGnuDebugLink.empty())
632 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000633
Eugene Leviant51c1f642019-02-25 14:12:41 +0000634 for (const NewSymbolInfo &SI : Config.SymbolsToAdd) {
635 SectionBase *Sec = Obj.findSection(SI.SectionName);
636 uint64_t Value = Sec ? Sec->Addr + SI.Value : SI.Value;
Simon Pilgrim65706cf2019-02-27 10:19:53 +0000637 Obj.SymbolTable->addSymbol(
638 SI.SymbolName, SI.Bind, SI.Type, Sec, Value, SI.Visibility,
639 Sec ? (uint16_t)SYMBOL_SIMPLE_INDEX : (uint16_t)SHN_ABS, 0);
Eugene Leviant51c1f642019-02-25 14:12:41 +0000640 }
641
Eugene Leviant53350d02019-02-26 09:24:22 +0000642 if (Config.EntryExpr)
643 Obj.Entry = Config.EntryExpr(Obj.Entry);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000644 return Error::success();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000645}
646
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000647Error executeObjcopyOnRawBinary(const CopyConfig &Config, MemoryBuffer &In,
648 Buffer &Out) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000649 BinaryReader Reader(Config.BinaryArch, &In);
650 std::unique_ptr<Object> Obj = Reader.create();
651
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000652 // Prefer OutputArch (-O<format>) if set, otherwise fallback to BinaryArch
653 // (-B<arch>).
654 const ElfType OutputElfType = getOutputElfType(
655 Config.OutputArch ? Config.OutputArch.getValue() : Config.BinaryArch);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000656 if (Error E = handleArgs(Config, *Obj, Reader, OutputElfType))
657 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000658 std::unique_ptr<Writer> Writer =
659 createWriter(Config, *Obj, Out, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000660 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000661 return E;
662 return Writer->write();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000663}
664
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000665Error executeObjcopyOnBinary(const CopyConfig &Config,
666 object::ELFObjectFileBase &In, Buffer &Out) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000667 ELFReader Reader(&In);
668 std::unique_ptr<Object> Obj = Reader.create();
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000669 // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
670 const ElfType OutputElfType =
671 Config.OutputArch ? getOutputElfType(Config.OutputArch.getValue())
672 : getOutputElfType(In);
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000673 ArrayRef<uint8_t> BuildIdBytes;
674
675 if (!Config.BuildIdLinkDir.empty()) {
676 BuildIdBytes = unwrapOrError(findBuildID(In));
677 if (BuildIdBytes.size() < 2)
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000678 return createFileError(
679 Config.InputFilename,
680 createStringError(object_error::parse_failed,
681 "build ID is smaller than two bytes."));
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000682 }
683
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000684 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkInput)
685 if (Error E =
686 linkToBuildIdDir(Config, Config.InputFilename,
687 Config.BuildIdLinkInput.getValue(), BuildIdBytes))
688 return E;
689
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000690 if (Error E = handleArgs(Config, *Obj, Reader, OutputElfType))
691 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000692 std::unique_ptr<Writer> Writer =
693 createWriter(Config, *Obj, Out, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000694 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000695 return E;
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000696 if (Error E = Writer->write())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000697 return E;
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000698 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkOutput)
699 if (Error E =
700 linkToBuildIdDir(Config, Config.OutputFilename,
701 Config.BuildIdLinkOutput.getValue(), BuildIdBytes))
702 return E;
703
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000704 return Error::success();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000705}
706
707} // end namespace elf
708} // end namespace objcopy
709} // end namespace llvm