blob: 7e991169124dd4fb36d1c99e4392483f02173a11 [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
102 // Certain flags also promote SHT_NOBITS to SHT_PROGBITS. Don't change other
103 // section types (RELA, SYMTAB, etc.).
104 const SectionFlag NoBitsToProgBitsMask =
105 SectionFlag::SecContents | SectionFlag::SecLoad | SectionFlag::SecNoload |
106 SectionFlag::SecCode | SectionFlag::SecData | SectionFlag::SecRom |
107 SectionFlag::SecDebug;
108 if (Sec.Type == SHT_NOBITS && (Flags & NoBitsToProgBitsMask))
109 Sec.Type = SHT_PROGBITS;
110}
111
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000112static ElfType getOutputElfType(const Binary &Bin) {
113 // Infer output ELF type from the input ELF object
114 if (isa<ELFObjectFile<ELF32LE>>(Bin))
115 return ELFT_ELF32LE;
116 if (isa<ELFObjectFile<ELF64LE>>(Bin))
117 return ELFT_ELF64LE;
118 if (isa<ELFObjectFile<ELF32BE>>(Bin))
119 return ELFT_ELF32BE;
120 if (isa<ELFObjectFile<ELF64BE>>(Bin))
121 return ELFT_ELF64BE;
122 llvm_unreachable("Invalid ELFType");
123}
124
125static ElfType getOutputElfType(const MachineInfo &MI) {
126 // Infer output ELF type from the binary arch specified
127 if (MI.Is64Bit)
128 return MI.IsLittleEndian ? ELFT_ELF64LE : ELFT_ELF64BE;
129 else
130 return MI.IsLittleEndian ? ELFT_ELF32LE : ELFT_ELF32BE;
131}
132
133static std::unique_ptr<Writer> createWriter(const CopyConfig &Config,
134 Object &Obj, Buffer &Buf,
135 ElfType OutputElfType) {
136 if (Config.OutputFormat == "binary") {
137 return llvm::make_unique<BinaryWriter>(Obj, Buf);
138 }
139 // Depending on the initial ELFT and OutputFormat we need a different Writer.
140 switch (OutputElfType) {
141 case ELFT_ELF32LE:
142 return llvm::make_unique<ELFWriter<ELF32LE>>(Obj, Buf,
143 !Config.StripSections);
144 case ELFT_ELF64LE:
145 return llvm::make_unique<ELFWriter<ELF64LE>>(Obj, Buf,
146 !Config.StripSections);
147 case ELFT_ELF32BE:
148 return llvm::make_unique<ELFWriter<ELF32BE>>(Obj, Buf,
149 !Config.StripSections);
150 case ELFT_ELF64BE:
151 return llvm::make_unique<ELFWriter<ELF64BE>>(Obj, Buf,
152 !Config.StripSections);
153 }
154 llvm_unreachable("Invalid output format");
155}
156
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000157template <class ELFT>
158static Expected<ArrayRef<uint8_t>>
159findBuildID(const object::ELFFile<ELFT> &In) {
160 for (const auto &Phdr : unwrapOrError(In.program_headers())) {
161 if (Phdr.p_type != PT_NOTE)
162 continue;
163 Error Err = Error::success();
David Blaikieba005aa2018-12-11 00:09:06 +0000164 for (const auto &Note : In.notes(Phdr, Err))
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000165 if (Note.getType() == NT_GNU_BUILD_ID && Note.getName() == ELF_NOTE_GNU)
166 return Note.getDesc();
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000167 if (Err)
168 return std::move(Err);
169 }
170 return createStringError(llvm::errc::invalid_argument,
171 "Could not find build ID.");
172}
173
174static Expected<ArrayRef<uint8_t>>
175findBuildID(const object::ELFObjectFileBase &In) {
176 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(&In))
177 return findBuildID(*O->getELFFile());
178 else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(&In))
179 return findBuildID(*O->getELFFile());
180 else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(&In))
181 return findBuildID(*O->getELFFile());
182 else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(&In))
183 return findBuildID(*O->getELFFile());
184
185 llvm_unreachable("Bad file format");
186}
187
Jake Ehrlich5049c342019-03-18 20:35:18 +0000188template <class... Ts>
189static Error makeStringError(std::error_code EC, const Twine &Msg, Ts&&... Args) {
190 std::string FullMsg = (EC.message() + ": " + Msg).str();
191 return createStringError(EC, FullMsg.c_str(), std::forward<Ts>(Args)...);
192}
193
194#define MODEL_8 "%%%%%%%%"
195#define MODEL_16 MODEL_8 MODEL_8
196#define MODEL_32 (MODEL_16 MODEL_16)
197
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000198static Error linkToBuildIdDir(const CopyConfig &Config, StringRef ToLink,
199 StringRef Suffix,
200 ArrayRef<uint8_t> BuildIdBytes) {
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000201 SmallString<128> Path = Config.BuildIdLinkDir;
202 sys::path::append(Path, llvm::toHex(BuildIdBytes[0], /*LowerCase*/ true));
203 if (auto EC = sys::fs::create_directories(Path))
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000204 return createFileError(
205 Path.str(),
Jake Ehrlich5049c342019-03-18 20:35:18 +0000206 makeStringError(EC, "cannot create build ID link directory"));
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000207
208 sys::path::append(Path,
209 llvm::toHex(BuildIdBytes.slice(1), /*LowerCase*/ true));
210 Path += Suffix;
Jake Ehrlich5049c342019-03-18 20:35:18 +0000211 SmallString<128> TmpPath;
212 // create_hard_link races so we need to link to a temporary path but
213 // we want to make sure that we choose a filename that does not exist.
214 // By using 32 model characters we get 128-bits of entropy. It is
215 // unlikely that this string has ever existed before much less exists
216 // on this disk or in the current working directory.
217 // Additionally we prepend the original Path for debugging but also
218 // because it ensures that we're linking within a directory on the same
219 // partition on the same device which is critical. It has the added
220 // win of yet further decreasing the odds of a conflict.
221 sys::fs::createUniquePath(Twine(Path) + "-" + MODEL_32 + ".tmp", TmpPath,
222 /*MakeAbsolute*/ false);
223 if (auto EC = sys::fs::create_hard_link(ToLink, TmpPath)) {
224 Path.push_back('\0');
225 return makeStringError(EC, "cannot link %s to %s", ToLink.data(),
226 Path.data());
227 }
228 // We then atomically rename the link into place which will just move the
229 // link. If rename fails something is more seriously wrong so just return
230 // an error.
231 if (auto EC = sys::fs::rename(TmpPath, Path)) {
232 Path.push_back('\0');
233 return makeStringError(EC, "cannot link %s to %s", ToLink.data(),
234 Path.data());
235 }
236 // If `Path` was already a hard-link to the same underlying file then the
237 // temp file will be left so we need to remove it. Remove will not cause
238 // an error by default if the file is already gone so just blindly remove
239 // it rather than checking.
240 if (auto EC = sys::fs::remove(TmpPath)) {
241 TmpPath.push_back('\0');
242 return makeStringError(EC, "could not remove %s", TmpPath.data());
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000243 }
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000244 return Error::success();
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000245}
246
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000247static Error splitDWOToFile(const CopyConfig &Config, const Reader &Reader,
248 StringRef File, ElfType OutputElfType) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000249 auto DWOFile = Reader.create();
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000250 auto OnlyKeepDWOPred = [&DWOFile](const SectionBase &Sec) {
251 return onlyKeepDWOPred(*DWOFile, Sec);
252 };
James Henderson66a9d0f2019-04-18 09:13:30 +0000253 if (Error E = DWOFile->removeSections(Config.AllowBrokenLinks,
254 OnlyKeepDWOPred))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000255 return E;
James Hendersonc040d5d2019-03-22 10:21:09 +0000256 if (Config.OutputArch) {
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000257 DWOFile->Machine = Config.OutputArch.getValue().EMachine;
James Hendersonc040d5d2019-03-22 10:21:09 +0000258 DWOFile->OSABI = Config.OutputArch.getValue().OSABI;
259 }
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000260 FileBuffer FB(File);
261 auto Writer = createWriter(Config, *DWOFile, FB, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000262 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000263 return E;
264 return Writer->write();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000265}
266
267static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
268 Object &Obj) {
269 for (auto &Sec : Obj.sections()) {
270 if (Sec.Name == SecName) {
Jordan Rupprecht16a0de22018-12-20 00:57:06 +0000271 if (Sec.OriginalData.empty())
Martin Storsjo8010c6be2019-01-22 10:57:59 +0000272 return createStringError(
273 object_error::parse_failed,
274 "Can't dump section \"%s\": it has no contents",
275 SecName.str().c_str());
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000276 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
277 FileOutputBuffer::create(Filename, Sec.OriginalData.size());
278 if (!BufferOrErr)
279 return BufferOrErr.takeError();
280 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
281 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(),
282 Buf->getBufferStart());
283 if (Error E = Buf->commit())
284 return E;
285 return Error::success();
286 }
287 }
Martin Storsjo8010c6be2019-01-22 10:57:59 +0000288 return createStringError(object_error::parse_failed, "Section not found");
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000289}
290
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000291static bool isCompressable(const SectionBase &Section) {
George Rimarade3c702019-03-05 13:07:43 +0000292 return !(Section.Flags & ELF::SHF_COMPRESSED) &&
293 StringRef(Section.Name).startswith(".debug");
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000294}
295
296static void replaceDebugSections(
Fangrui Song3dfc3fb2019-03-15 10:27:28 +0000297 Object &Obj, SectionPred &RemovePred,
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000298 function_ref<bool(const SectionBase &)> shouldReplace,
299 function_ref<SectionBase *(const SectionBase *)> addSection) {
George Rimard8a5c6c2019-03-11 11:01:24 +0000300 // Build a list of the debug sections we are going to replace.
301 // We can't call `addSection` while iterating over sections,
302 // because it would mutate the sections array.
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000303 SmallVector<SectionBase *, 13> ToReplace;
George Rimard8a5c6c2019-03-11 11:01:24 +0000304 for (auto &Sec : Obj.sections())
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000305 if (shouldReplace(Sec))
306 ToReplace.push_back(&Sec);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000307
George Rimard8a5c6c2019-03-11 11:01:24 +0000308 // Build a mapping from original section to a new one.
309 DenseMap<SectionBase *, SectionBase *> FromTo;
310 for (SectionBase *S : ToReplace)
311 FromTo[S] = addSection(S);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000312
George Rimard8a5c6c2019-03-11 11:01:24 +0000313 // Now we want to update the target sections of relocation
314 // sections. Also we will update the relocations themselves
315 // to update the symbol references.
316 for (auto &Sec : Obj.sections())
317 Sec.replaceSectionReferences(FromTo);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000318
319 RemovePred = [shouldReplace, RemovePred](const SectionBase &Sec) {
320 return shouldReplace(Sec) || RemovePred(Sec);
321 };
322}
323
Eugene Leviant2db10622019-02-13 07:34:54 +0000324static bool isUnneededSymbol(const Symbol &Sym) {
325 return !Sym.Referenced &&
326 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
327 Sym.Type != STT_FILE && Sym.Type != STT_SECTION;
328}
329
George Rimare6963be2019-03-25 12:34:25 +0000330static Error updateAndRemoveSymbols(const CopyConfig &Config, Object &Obj) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000331 // TODO: update or remove symbols only if there is an option that affects
332 // them.
George Rimare6963be2019-03-25 12:34:25 +0000333 if (!Obj.SymbolTable)
334 return Error::success();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000335
George Rimare6963be2019-03-25 12:34:25 +0000336 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
337 // Common and undefined symbols don't make sense as local symbols, and can
338 // even cause crashes if we localize those, so skip them.
339 if (!Sym.isCommon() && Sym.getShndx() != SHN_UNDEF &&
340 ((Config.LocalizeHidden &&
341 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
342 is_contained(Config.SymbolsToLocalize, Sym.Name)))
343 Sym.Binding = STB_LOCAL;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000344
George Rimare6963be2019-03-25 12:34:25 +0000345 // Note: these two globalize flags have very similar names but different
346 // meanings:
347 //
348 // --globalize-symbol: promote a symbol to global
349 // --keep-global-symbol: all symbols except for these should be made local
350 //
351 // If --globalize-symbol is specified for a given symbol, it will be
352 // global in the output file even if it is not included via
353 // --keep-global-symbol. Because of that, make sure to check
354 // --globalize-symbol second.
355 if (!Config.SymbolsToKeepGlobal.empty() &&
356 !is_contained(Config.SymbolsToKeepGlobal, Sym.Name) &&
357 Sym.getShndx() != SHN_UNDEF)
358 Sym.Binding = STB_LOCAL;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000359
George Rimare6963be2019-03-25 12:34:25 +0000360 if (is_contained(Config.SymbolsToGlobalize, Sym.Name) &&
361 Sym.getShndx() != SHN_UNDEF)
362 Sym.Binding = STB_GLOBAL;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000363
George Rimare6963be2019-03-25 12:34:25 +0000364 if (is_contained(Config.SymbolsToWeaken, Sym.Name) &&
365 Sym.Binding == STB_GLOBAL)
366 Sym.Binding = STB_WEAK;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000367
George Rimare6963be2019-03-25 12:34:25 +0000368 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
369 Sym.getShndx() != SHN_UNDEF)
370 Sym.Binding = STB_WEAK;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000371
George Rimare6963be2019-03-25 12:34:25 +0000372 const auto I = Config.SymbolsToRename.find(Sym.Name);
373 if (I != Config.SymbolsToRename.end())
374 Sym.Name = I->getValue();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000375
George Rimare6963be2019-03-25 12:34:25 +0000376 if (!Config.SymbolsPrefix.empty() && Sym.Type != STT_SECTION)
377 Sym.Name = (Config.SymbolsPrefix + Sym.Name).str();
378 });
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000379
George Rimare6963be2019-03-25 12:34:25 +0000380 // The purpose of this loop is to mark symbols referenced by sections
381 // (like GroupSection or RelocationSection). This way, we know which
382 // symbols are still 'needed' and which are not.
383 if (Config.StripUnneeded || !Config.UnneededSymbolsToRemove.empty()) {
384 for (auto &Section : Obj.sections())
385 Section.markSymbols();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000386 }
387
George Rimare6963be2019-03-25 12:34:25 +0000388 auto RemoveSymbolsPred = [&](const Symbol &Sym) {
389 if (is_contained(Config.SymbolsToKeep, Sym.Name) ||
390 (Config.KeepFileSymbols && Sym.Type == STT_FILE))
391 return false;
392
393 if ((Config.DiscardMode == DiscardType::All ||
394 (Config.DiscardMode == DiscardType::Locals &&
395 StringRef(Sym.Name).startswith(".L"))) &&
396 Sym.Binding == STB_LOCAL && Sym.getShndx() != SHN_UNDEF &&
397 Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
398 return true;
399
400 if (Config.StripAll || Config.StripAllGNU)
401 return true;
402
403 if (is_contained(Config.SymbolsToRemove, Sym.Name))
404 return true;
405
406 if ((Config.StripUnneeded ||
407 is_contained(Config.UnneededSymbolsToRemove, Sym.Name)) &&
408 isUnneededSymbol(Sym))
409 return true;
410
411 return false;
412 };
413
414 return Obj.removeSymbols(RemoveSymbolsPred);
415}
416
417static Error replaceAndRemoveSections(const CopyConfig &Config, Object &Obj) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000418 SectionPred RemovePred = [](const SectionBase &) { return false; };
419
420 // Removes:
421 if (!Config.ToRemove.empty()) {
422 RemovePred = [&Config](const SectionBase &Sec) {
423 return is_contained(Config.ToRemove, Sec.Name);
424 };
425 }
426
427 if (Config.StripDWO || !Config.SplitDWO.empty())
428 RemovePred = [RemovePred](const SectionBase &Sec) {
429 return isDWOSection(Sec) || RemovePred(Sec);
430 };
431
432 if (Config.ExtractDWO)
433 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
434 return onlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
435 };
436
437 if (Config.StripAllGNU)
438 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
439 if (RemovePred(Sec))
440 return true;
441 if ((Sec.Flags & SHF_ALLOC) != 0)
442 return false;
443 if (&Sec == Obj.SectionNames)
444 return false;
445 switch (Sec.Type) {
446 case SHT_SYMTAB:
447 case SHT_REL:
448 case SHT_RELA:
449 case SHT_STRTAB:
450 return true;
451 }
452 return isDebugSection(Sec);
453 };
454
455 if (Config.StripSections) {
456 RemovePred = [RemovePred](const SectionBase &Sec) {
James Hendersonb5de5e22019-03-14 11:47:41 +0000457 return RemovePred(Sec) || Sec.ParentSegment == nullptr;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000458 };
459 }
460
461 if (Config.StripDebug) {
462 RemovePred = [RemovePred](const SectionBase &Sec) {
463 return RemovePred(Sec) || isDebugSection(Sec);
464 };
465 }
466
467 if (Config.StripNonAlloc)
468 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
469 if (RemovePred(Sec))
470 return true;
471 if (&Sec == Obj.SectionNames)
472 return false;
James Hendersonb5de5e22019-03-14 11:47:41 +0000473 return (Sec.Flags & SHF_ALLOC) == 0 && Sec.ParentSegment == nullptr;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000474 };
475
476 if (Config.StripAll)
477 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
478 if (RemovePred(Sec))
479 return true;
480 if (&Sec == Obj.SectionNames)
481 return false;
482 if (StringRef(Sec.Name).startswith(".gnu.warning"))
483 return false;
James Hendersonb5de5e22019-03-14 11:47:41 +0000484 if (Sec.ParentSegment != nullptr)
485 return false;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000486 return (Sec.Flags & SHF_ALLOC) == 0;
487 };
488
489 // Explicit copies:
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000490 if (!Config.OnlySection.empty()) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000491 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
492 // Explicitly keep these sections regardless of previous removes.
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000493 if (is_contained(Config.OnlySection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000494 return false;
495
496 // Allow all implicit removes.
497 if (RemovePred(Sec))
498 return true;
499
500 // Keep special sections.
501 if (Obj.SectionNames == &Sec)
502 return false;
503 if (Obj.SymbolTable == &Sec ||
504 (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
505 return false;
506
507 // Remove everything else.
508 return true;
509 };
510 }
511
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000512 if (!Config.KeepSection.empty()) {
Fangrui Songe9f34b02018-11-12 23:46:22 +0000513 RemovePred = [&Config, RemovePred](const SectionBase &Sec) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000514 // Explicitly keep these sections regardless of previous removes.
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000515 if (is_contained(Config.KeepSection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000516 return false;
517 // Otherwise defer to RemovePred.
518 return RemovePred(Sec);
519 };
520 }
521
522 // This has to be the last predicate assignment.
523 // If the option --keep-symbol has been specified
524 // and at least one of those symbols is present
525 // (equivalently, the updated symbol table is not empty)
526 // the symbol table and the string table should not be removed.
527 if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) &&
528 Obj.SymbolTable && !Obj.SymbolTable->empty()) {
529 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
530 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
531 return false;
532 return RemovePred(Sec);
533 };
534 }
535
536 if (Config.CompressionType != DebugCompressionType::None)
Fangrui Song3dfc3fb2019-03-15 10:27:28 +0000537 replaceDebugSections(Obj, RemovePred, isCompressable,
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000538 [&Config, &Obj](const SectionBase *S) {
539 return &Obj.addSection<CompressedSection>(
540 *S, Config.CompressionType);
541 });
542 else if (Config.DecompressDebugSections)
543 replaceDebugSections(
Fangrui Song3dfc3fb2019-03-15 10:27:28 +0000544 Obj, RemovePred,
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000545 [](const SectionBase &S) { return isa<CompressedSection>(&S); },
546 [&Obj](const SectionBase *S) {
547 auto CS = cast<CompressedSection>(S);
548 return &Obj.addSection<DecompressedSection>(*CS);
549 });
550
James Henderson66a9d0f2019-04-18 09:13:30 +0000551 return Obj.removeSections(Config.AllowBrokenLinks, RemovePred);
George Rimare6963be2019-03-25 12:34:25 +0000552}
553
554// This function handles the high level operations of GNU objcopy including
555// handling command line options. It's important to outline certain properties
556// we expect to hold of the command line operations. Any operation that "keeps"
557// should keep regardless of a remove. Additionally any removal should respect
558// any previous removals. Lastly whether or not something is removed shouldn't
559// depend a) on the order the options occur in or b) on some opaque priority
560// system. The only priority is that keeps/copies overrule removes.
561static Error handleArgs(const CopyConfig &Config, Object &Obj,
562 const Reader &Reader, ElfType OutputElfType) {
563
564 if (!Config.SplitDWO.empty())
565 if (Error E =
566 splitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType))
567 return E;
568
569 if (Config.OutputArch) {
570 Obj.Machine = Config.OutputArch.getValue().EMachine;
571 Obj.OSABI = Config.OutputArch.getValue().OSABI;
572 }
573
George Rimar279898b2019-03-26 18:42:15 +0000574 // It is important to remove the sections first. For example, we want to
575 // remove the relocation sections before removing the symbols. That allows
576 // us to avoid reporting the inappropriate errors about removing symbols
577 // named in relocations.
578 if (Error E = replaceAndRemoveSections(Config, Obj))
George Rimare6963be2019-03-25 12:34:25 +0000579 return E;
580
George Rimar279898b2019-03-26 18:42:15 +0000581 if (Error E = updateAndRemoveSymbols(Config, Obj))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000582 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000583
584 if (!Config.SectionsToRename.empty()) {
585 for (auto &Sec : Obj.sections()) {
586 const auto Iter = Config.SectionsToRename.find(Sec.Name);
587 if (Iter != Config.SectionsToRename.end()) {
588 const SectionRename &SR = Iter->second;
589 Sec.Name = SR.NewName;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000590 if (SR.NewFlags.hasValue())
Jordan Rupprecht017deaf2019-04-02 16:49:56 +0000591 setSectionFlagsAndType(Sec, SR.NewFlags.getValue());
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000592 }
593 }
594 }
595
596 if (!Config.SetSectionFlags.empty()) {
597 for (auto &Sec : Obj.sections()) {
598 const auto Iter = Config.SetSectionFlags.find(Sec.Name);
599 if (Iter != Config.SetSectionFlags.end()) {
600 const SectionFlagsUpdate &SFU = Iter->second;
Jordan Rupprecht017deaf2019-04-02 16:49:56 +0000601 setSectionFlagsAndType(Sec, SFU.NewFlags);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000602 }
603 }
604 }
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000605
Eugene Leviantc76671b2019-03-12 12:41:06 +0000606 for (const auto &Flag : Config.AddSection) {
607 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
608 StringRef SecName = SecPair.first;
609 StringRef File = SecPair.second;
610 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
611 MemoryBuffer::getFile(File);
612 if (!BufOrErr)
613 return createFileError(File, errorCodeToError(BufOrErr.getError()));
614 std::unique_ptr<MemoryBuffer> Buf = std::move(*BufOrErr);
615 ArrayRef<uint8_t> Data(
616 reinterpret_cast<const uint8_t *>(Buf->getBufferStart()),
617 Buf->getBufferSize());
618 OwnedDataSection &NewSection =
619 Obj.addSection<OwnedDataSection>(SecName, Data);
620 if (SecName.startswith(".note") && SecName != ".note.GNU-stack")
621 NewSection.Type = SHT_NOTE;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000622 }
623
Eugene Leviantc76671b2019-03-12 12:41:06 +0000624 for (const auto &Flag : Config.DumpSection) {
625 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
626 StringRef SecName = SecPair.first;
627 StringRef File = SecPair.second;
628 if (Error E = dumpSectionToFile(SecName, File, Obj))
629 return createFileError(Config.InputFilename, std::move(E));
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000630 }
631
632 if (!Config.AddGnuDebugLink.empty())
633 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000634
Eugene Leviant51c1f642019-02-25 14:12:41 +0000635 for (const NewSymbolInfo &SI : Config.SymbolsToAdd) {
636 SectionBase *Sec = Obj.findSection(SI.SectionName);
637 uint64_t Value = Sec ? Sec->Addr + SI.Value : SI.Value;
Simon Pilgrim65706cf2019-02-27 10:19:53 +0000638 Obj.SymbolTable->addSymbol(
639 SI.SymbolName, SI.Bind, SI.Type, Sec, Value, SI.Visibility,
640 Sec ? (uint16_t)SYMBOL_SIMPLE_INDEX : (uint16_t)SHN_ABS, 0);
Eugene Leviant51c1f642019-02-25 14:12:41 +0000641 }
642
Eugene Leviant53350d02019-02-26 09:24:22 +0000643 if (Config.EntryExpr)
644 Obj.Entry = Config.EntryExpr(Obj.Entry);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000645 return Error::success();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000646}
647
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000648Error executeObjcopyOnRawBinary(const CopyConfig &Config, MemoryBuffer &In,
649 Buffer &Out) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000650 BinaryReader Reader(Config.BinaryArch, &In);
651 std::unique_ptr<Object> Obj = Reader.create();
652
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000653 // Prefer OutputArch (-O<format>) if set, otherwise fallback to BinaryArch
654 // (-B<arch>).
655 const ElfType OutputElfType = getOutputElfType(
656 Config.OutputArch ? Config.OutputArch.getValue() : Config.BinaryArch);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000657 if (Error E = handleArgs(Config, *Obj, Reader, OutputElfType))
658 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000659 std::unique_ptr<Writer> Writer =
660 createWriter(Config, *Obj, Out, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000661 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000662 return E;
663 return Writer->write();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000664}
665
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000666Error executeObjcopyOnBinary(const CopyConfig &Config,
667 object::ELFObjectFileBase &In, Buffer &Out) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000668 ELFReader Reader(&In);
669 std::unique_ptr<Object> Obj = Reader.create();
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000670 // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
671 const ElfType OutputElfType =
672 Config.OutputArch ? getOutputElfType(Config.OutputArch.getValue())
673 : getOutputElfType(In);
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000674 ArrayRef<uint8_t> BuildIdBytes;
675
676 if (!Config.BuildIdLinkDir.empty()) {
677 BuildIdBytes = unwrapOrError(findBuildID(In));
678 if (BuildIdBytes.size() < 2)
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000679 return createFileError(
680 Config.InputFilename,
681 createStringError(object_error::parse_failed,
682 "build ID is smaller than two bytes."));
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000683 }
684
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000685 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkInput)
686 if (Error E =
687 linkToBuildIdDir(Config, Config.InputFilename,
688 Config.BuildIdLinkInput.getValue(), BuildIdBytes))
689 return E;
690
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000691 if (Error E = handleArgs(Config, *Obj, Reader, OutputElfType))
692 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000693 std::unique_ptr<Writer> Writer =
694 createWriter(Config, *Obj, Out, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000695 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000696 return E;
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000697 if (Error E = Writer->write())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000698 return E;
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000699 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkOutput)
700 if (Error E =
701 linkToBuildIdDir(Config, Config.OutputFilename,
702 Config.BuildIdLinkOutput.getValue(), BuildIdBytes))
703 return E;
704
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000705 return Error::success();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000706}
707
708} // end namespace elf
709} // end namespace objcopy
710} // end namespace llvm