blob: 26f6987d80835ede83ba756973bf4e4fc7b86325 [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 Rupprechtc8927412019-01-29 15:05:38 +000088static uint64_t setSectionFlagsPreserveMask(uint64_t OldFlags,
89 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
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +000099static ElfType getOutputElfType(const Binary &Bin) {
100 // Infer output ELF type from the input ELF object
101 if (isa<ELFObjectFile<ELF32LE>>(Bin))
102 return ELFT_ELF32LE;
103 if (isa<ELFObjectFile<ELF64LE>>(Bin))
104 return ELFT_ELF64LE;
105 if (isa<ELFObjectFile<ELF32BE>>(Bin))
106 return ELFT_ELF32BE;
107 if (isa<ELFObjectFile<ELF64BE>>(Bin))
108 return ELFT_ELF64BE;
109 llvm_unreachable("Invalid ELFType");
110}
111
112static ElfType getOutputElfType(const MachineInfo &MI) {
113 // Infer output ELF type from the binary arch specified
114 if (MI.Is64Bit)
115 return MI.IsLittleEndian ? ELFT_ELF64LE : ELFT_ELF64BE;
116 else
117 return MI.IsLittleEndian ? ELFT_ELF32LE : ELFT_ELF32BE;
118}
119
120static std::unique_ptr<Writer> createWriter(const CopyConfig &Config,
121 Object &Obj, Buffer &Buf,
122 ElfType OutputElfType) {
123 if (Config.OutputFormat == "binary") {
124 return llvm::make_unique<BinaryWriter>(Obj, Buf);
125 }
126 // Depending on the initial ELFT and OutputFormat we need a different Writer.
127 switch (OutputElfType) {
128 case ELFT_ELF32LE:
129 return llvm::make_unique<ELFWriter<ELF32LE>>(Obj, Buf,
130 !Config.StripSections);
131 case ELFT_ELF64LE:
132 return llvm::make_unique<ELFWriter<ELF64LE>>(Obj, Buf,
133 !Config.StripSections);
134 case ELFT_ELF32BE:
135 return llvm::make_unique<ELFWriter<ELF32BE>>(Obj, Buf,
136 !Config.StripSections);
137 case ELFT_ELF64BE:
138 return llvm::make_unique<ELFWriter<ELF64BE>>(Obj, Buf,
139 !Config.StripSections);
140 }
141 llvm_unreachable("Invalid output format");
142}
143
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000144template <class ELFT>
145static Expected<ArrayRef<uint8_t>>
146findBuildID(const object::ELFFile<ELFT> &In) {
147 for (const auto &Phdr : unwrapOrError(In.program_headers())) {
148 if (Phdr.p_type != PT_NOTE)
149 continue;
150 Error Err = Error::success();
David Blaikieba005aa2018-12-11 00:09:06 +0000151 for (const auto &Note : In.notes(Phdr, Err))
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000152 if (Note.getType() == NT_GNU_BUILD_ID && Note.getName() == ELF_NOTE_GNU)
153 return Note.getDesc();
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000154 if (Err)
155 return std::move(Err);
156 }
157 return createStringError(llvm::errc::invalid_argument,
158 "Could not find build ID.");
159}
160
161static Expected<ArrayRef<uint8_t>>
162findBuildID(const object::ELFObjectFileBase &In) {
163 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(&In))
164 return findBuildID(*O->getELFFile());
165 else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(&In))
166 return findBuildID(*O->getELFFile());
167 else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(&In))
168 return findBuildID(*O->getELFFile());
169 else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(&In))
170 return findBuildID(*O->getELFFile());
171
172 llvm_unreachable("Bad file format");
173}
174
Jake Ehrlich5049c342019-03-18 20:35:18 +0000175template <class... Ts>
176static Error makeStringError(std::error_code EC, const Twine &Msg, Ts&&... Args) {
177 std::string FullMsg = (EC.message() + ": " + Msg).str();
178 return createStringError(EC, FullMsg.c_str(), std::forward<Ts>(Args)...);
179}
180
181#define MODEL_8 "%%%%%%%%"
182#define MODEL_16 MODEL_8 MODEL_8
183#define MODEL_32 (MODEL_16 MODEL_16)
184
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000185static Error linkToBuildIdDir(const CopyConfig &Config, StringRef ToLink,
186 StringRef Suffix,
187 ArrayRef<uint8_t> BuildIdBytes) {
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000188 SmallString<128> Path = Config.BuildIdLinkDir;
189 sys::path::append(Path, llvm::toHex(BuildIdBytes[0], /*LowerCase*/ true));
190 if (auto EC = sys::fs::create_directories(Path))
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000191 return createFileError(
192 Path.str(),
Jake Ehrlich5049c342019-03-18 20:35:18 +0000193 makeStringError(EC, "cannot create build ID link directory"));
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000194
195 sys::path::append(Path,
196 llvm::toHex(BuildIdBytes.slice(1), /*LowerCase*/ true));
197 Path += Suffix;
Jake Ehrlich5049c342019-03-18 20:35:18 +0000198 SmallString<128> TmpPath;
199 // create_hard_link races so we need to link to a temporary path but
200 // we want to make sure that we choose a filename that does not exist.
201 // By using 32 model characters we get 128-bits of entropy. It is
202 // unlikely that this string has ever existed before much less exists
203 // on this disk or in the current working directory.
204 // Additionally we prepend the original Path for debugging but also
205 // because it ensures that we're linking within a directory on the same
206 // partition on the same device which is critical. It has the added
207 // win of yet further decreasing the odds of a conflict.
208 sys::fs::createUniquePath(Twine(Path) + "-" + MODEL_32 + ".tmp", TmpPath,
209 /*MakeAbsolute*/ false);
210 if (auto EC = sys::fs::create_hard_link(ToLink, TmpPath)) {
211 Path.push_back('\0');
212 return makeStringError(EC, "cannot link %s to %s", ToLink.data(),
213 Path.data());
214 }
215 // We then atomically rename the link into place which will just move the
216 // link. If rename fails something is more seriously wrong so just return
217 // an error.
218 if (auto EC = sys::fs::rename(TmpPath, Path)) {
219 Path.push_back('\0');
220 return makeStringError(EC, "cannot link %s to %s", ToLink.data(),
221 Path.data());
222 }
223 // If `Path` was already a hard-link to the same underlying file then the
224 // temp file will be left so we need to remove it. Remove will not cause
225 // an error by default if the file is already gone so just blindly remove
226 // it rather than checking.
227 if (auto EC = sys::fs::remove(TmpPath)) {
228 TmpPath.push_back('\0');
229 return makeStringError(EC, "could not remove %s", TmpPath.data());
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000230 }
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000231 return Error::success();
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000232}
233
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000234static Error splitDWOToFile(const CopyConfig &Config, const Reader &Reader,
235 StringRef File, ElfType OutputElfType) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000236 auto DWOFile = Reader.create();
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000237 auto OnlyKeepDWOPred = [&DWOFile](const SectionBase &Sec) {
238 return onlyKeepDWOPred(*DWOFile, Sec);
239 };
240 if (Error E = DWOFile->removeSections(OnlyKeepDWOPred))
241 return E;
James Hendersonc040d5d2019-03-22 10:21:09 +0000242 if (Config.OutputArch) {
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000243 DWOFile->Machine = Config.OutputArch.getValue().EMachine;
James Hendersonc040d5d2019-03-22 10:21:09 +0000244 DWOFile->OSABI = Config.OutputArch.getValue().OSABI;
245 }
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000246 FileBuffer FB(File);
247 auto Writer = createWriter(Config, *DWOFile, FB, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000248 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000249 return E;
250 return Writer->write();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000251}
252
253static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
254 Object &Obj) {
255 for (auto &Sec : Obj.sections()) {
256 if (Sec.Name == SecName) {
Jordan Rupprecht16a0de22018-12-20 00:57:06 +0000257 if (Sec.OriginalData.empty())
Martin Storsjo8010c6be2019-01-22 10:57:59 +0000258 return createStringError(
259 object_error::parse_failed,
260 "Can't dump section \"%s\": it has no contents",
261 SecName.str().c_str());
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000262 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
263 FileOutputBuffer::create(Filename, Sec.OriginalData.size());
264 if (!BufferOrErr)
265 return BufferOrErr.takeError();
266 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
267 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(),
268 Buf->getBufferStart());
269 if (Error E = Buf->commit())
270 return E;
271 return Error::success();
272 }
273 }
Martin Storsjo8010c6be2019-01-22 10:57:59 +0000274 return createStringError(object_error::parse_failed, "Section not found");
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000275}
276
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000277static bool isCompressable(const SectionBase &Section) {
George Rimarade3c702019-03-05 13:07:43 +0000278 return !(Section.Flags & ELF::SHF_COMPRESSED) &&
279 StringRef(Section.Name).startswith(".debug");
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000280}
281
282static void replaceDebugSections(
Fangrui Song3dfc3fb2019-03-15 10:27:28 +0000283 Object &Obj, SectionPred &RemovePred,
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000284 function_ref<bool(const SectionBase &)> shouldReplace,
285 function_ref<SectionBase *(const SectionBase *)> addSection) {
George Rimard8a5c6c2019-03-11 11:01:24 +0000286 // Build a list of the debug sections we are going to replace.
287 // We can't call `addSection` while iterating over sections,
288 // because it would mutate the sections array.
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000289 SmallVector<SectionBase *, 13> ToReplace;
George Rimard8a5c6c2019-03-11 11:01:24 +0000290 for (auto &Sec : Obj.sections())
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000291 if (shouldReplace(Sec))
292 ToReplace.push_back(&Sec);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000293
George Rimard8a5c6c2019-03-11 11:01:24 +0000294 // Build a mapping from original section to a new one.
295 DenseMap<SectionBase *, SectionBase *> FromTo;
296 for (SectionBase *S : ToReplace)
297 FromTo[S] = addSection(S);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000298
George Rimard8a5c6c2019-03-11 11:01:24 +0000299 // Now we want to update the target sections of relocation
300 // sections. Also we will update the relocations themselves
301 // to update the symbol references.
302 for (auto &Sec : Obj.sections())
303 Sec.replaceSectionReferences(FromTo);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000304
305 RemovePred = [shouldReplace, RemovePred](const SectionBase &Sec) {
306 return shouldReplace(Sec) || RemovePred(Sec);
307 };
308}
309
Eugene Leviant2db10622019-02-13 07:34:54 +0000310static bool isUnneededSymbol(const Symbol &Sym) {
311 return !Sym.Referenced &&
312 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
313 Sym.Type != STT_FILE && Sym.Type != STT_SECTION;
314}
315
George Rimare6963be2019-03-25 12:34:25 +0000316static Error updateAndRemoveSymbols(const CopyConfig &Config, Object &Obj) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000317 // TODO: update or remove symbols only if there is an option that affects
318 // them.
George Rimare6963be2019-03-25 12:34:25 +0000319 if (!Obj.SymbolTable)
320 return Error::success();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000321
George Rimare6963be2019-03-25 12:34:25 +0000322 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
323 // Common and undefined symbols don't make sense as local symbols, and can
324 // even cause crashes if we localize those, so skip them.
325 if (!Sym.isCommon() && Sym.getShndx() != SHN_UNDEF &&
326 ((Config.LocalizeHidden &&
327 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
328 is_contained(Config.SymbolsToLocalize, Sym.Name)))
329 Sym.Binding = STB_LOCAL;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000330
George Rimare6963be2019-03-25 12:34:25 +0000331 // Note: these two globalize flags have very similar names but different
332 // meanings:
333 //
334 // --globalize-symbol: promote a symbol to global
335 // --keep-global-symbol: all symbols except for these should be made local
336 //
337 // If --globalize-symbol is specified for a given symbol, it will be
338 // global in the output file even if it is not included via
339 // --keep-global-symbol. Because of that, make sure to check
340 // --globalize-symbol second.
341 if (!Config.SymbolsToKeepGlobal.empty() &&
342 !is_contained(Config.SymbolsToKeepGlobal, Sym.Name) &&
343 Sym.getShndx() != SHN_UNDEF)
344 Sym.Binding = STB_LOCAL;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000345
George Rimare6963be2019-03-25 12:34:25 +0000346 if (is_contained(Config.SymbolsToGlobalize, Sym.Name) &&
347 Sym.getShndx() != SHN_UNDEF)
348 Sym.Binding = STB_GLOBAL;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000349
George Rimare6963be2019-03-25 12:34:25 +0000350 if (is_contained(Config.SymbolsToWeaken, Sym.Name) &&
351 Sym.Binding == STB_GLOBAL)
352 Sym.Binding = STB_WEAK;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000353
George Rimare6963be2019-03-25 12:34:25 +0000354 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
355 Sym.getShndx() != SHN_UNDEF)
356 Sym.Binding = STB_WEAK;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000357
George Rimare6963be2019-03-25 12:34:25 +0000358 const auto I = Config.SymbolsToRename.find(Sym.Name);
359 if (I != Config.SymbolsToRename.end())
360 Sym.Name = I->getValue();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000361
George Rimare6963be2019-03-25 12:34:25 +0000362 if (!Config.SymbolsPrefix.empty() && Sym.Type != STT_SECTION)
363 Sym.Name = (Config.SymbolsPrefix + Sym.Name).str();
364 });
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000365
George Rimare6963be2019-03-25 12:34:25 +0000366 // The purpose of this loop is to mark symbols referenced by sections
367 // (like GroupSection or RelocationSection). This way, we know which
368 // symbols are still 'needed' and which are not.
369 if (Config.StripUnneeded || !Config.UnneededSymbolsToRemove.empty()) {
370 for (auto &Section : Obj.sections())
371 Section.markSymbols();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000372 }
373
George Rimare6963be2019-03-25 12:34:25 +0000374 auto RemoveSymbolsPred = [&](const Symbol &Sym) {
375 if (is_contained(Config.SymbolsToKeep, Sym.Name) ||
376 (Config.KeepFileSymbols && Sym.Type == STT_FILE))
377 return false;
378
379 if ((Config.DiscardMode == DiscardType::All ||
380 (Config.DiscardMode == DiscardType::Locals &&
381 StringRef(Sym.Name).startswith(".L"))) &&
382 Sym.Binding == STB_LOCAL && Sym.getShndx() != SHN_UNDEF &&
383 Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
384 return true;
385
386 if (Config.StripAll || Config.StripAllGNU)
387 return true;
388
389 if (is_contained(Config.SymbolsToRemove, Sym.Name))
390 return true;
391
392 if ((Config.StripUnneeded ||
393 is_contained(Config.UnneededSymbolsToRemove, Sym.Name)) &&
394 isUnneededSymbol(Sym))
395 return true;
396
397 return false;
398 };
399
400 return Obj.removeSymbols(RemoveSymbolsPred);
401}
402
403static Error replaceAndRemoveSections(const CopyConfig &Config, Object &Obj) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000404 SectionPred RemovePred = [](const SectionBase &) { return false; };
405
406 // Removes:
407 if (!Config.ToRemove.empty()) {
408 RemovePred = [&Config](const SectionBase &Sec) {
409 return is_contained(Config.ToRemove, Sec.Name);
410 };
411 }
412
413 if (Config.StripDWO || !Config.SplitDWO.empty())
414 RemovePred = [RemovePred](const SectionBase &Sec) {
415 return isDWOSection(Sec) || RemovePred(Sec);
416 };
417
418 if (Config.ExtractDWO)
419 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
420 return onlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
421 };
422
423 if (Config.StripAllGNU)
424 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
425 if (RemovePred(Sec))
426 return true;
427 if ((Sec.Flags & SHF_ALLOC) != 0)
428 return false;
429 if (&Sec == Obj.SectionNames)
430 return false;
431 switch (Sec.Type) {
432 case SHT_SYMTAB:
433 case SHT_REL:
434 case SHT_RELA:
435 case SHT_STRTAB:
436 return true;
437 }
438 return isDebugSection(Sec);
439 };
440
441 if (Config.StripSections) {
442 RemovePred = [RemovePred](const SectionBase &Sec) {
James Hendersonb5de5e22019-03-14 11:47:41 +0000443 return RemovePred(Sec) || Sec.ParentSegment == nullptr;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000444 };
445 }
446
447 if (Config.StripDebug) {
448 RemovePred = [RemovePred](const SectionBase &Sec) {
449 return RemovePred(Sec) || isDebugSection(Sec);
450 };
451 }
452
453 if (Config.StripNonAlloc)
454 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
455 if (RemovePred(Sec))
456 return true;
457 if (&Sec == Obj.SectionNames)
458 return false;
James Hendersonb5de5e22019-03-14 11:47:41 +0000459 return (Sec.Flags & SHF_ALLOC) == 0 && Sec.ParentSegment == nullptr;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000460 };
461
462 if (Config.StripAll)
463 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
464 if (RemovePred(Sec))
465 return true;
466 if (&Sec == Obj.SectionNames)
467 return false;
468 if (StringRef(Sec.Name).startswith(".gnu.warning"))
469 return false;
James Hendersonb5de5e22019-03-14 11:47:41 +0000470 if (Sec.ParentSegment != nullptr)
471 return false;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000472 return (Sec.Flags & SHF_ALLOC) == 0;
473 };
474
475 // Explicit copies:
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000476 if (!Config.OnlySection.empty()) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000477 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
478 // Explicitly keep these sections regardless of previous removes.
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000479 if (is_contained(Config.OnlySection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000480 return false;
481
482 // Allow all implicit removes.
483 if (RemovePred(Sec))
484 return true;
485
486 // Keep special sections.
487 if (Obj.SectionNames == &Sec)
488 return false;
489 if (Obj.SymbolTable == &Sec ||
490 (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
491 return false;
492
493 // Remove everything else.
494 return true;
495 };
496 }
497
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000498 if (!Config.KeepSection.empty()) {
Fangrui Songe9f34b02018-11-12 23:46:22 +0000499 RemovePred = [&Config, RemovePred](const SectionBase &Sec) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000500 // Explicitly keep these sections regardless of previous removes.
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000501 if (is_contained(Config.KeepSection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000502 return false;
503 // Otherwise defer to RemovePred.
504 return RemovePred(Sec);
505 };
506 }
507
508 // This has to be the last predicate assignment.
509 // If the option --keep-symbol has been specified
510 // and at least one of those symbols is present
511 // (equivalently, the updated symbol table is not empty)
512 // the symbol table and the string table should not be removed.
513 if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) &&
514 Obj.SymbolTable && !Obj.SymbolTable->empty()) {
515 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
516 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
517 return false;
518 return RemovePred(Sec);
519 };
520 }
521
522 if (Config.CompressionType != DebugCompressionType::None)
Fangrui Song3dfc3fb2019-03-15 10:27:28 +0000523 replaceDebugSections(Obj, RemovePred, isCompressable,
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000524 [&Config, &Obj](const SectionBase *S) {
525 return &Obj.addSection<CompressedSection>(
526 *S, Config.CompressionType);
527 });
528 else if (Config.DecompressDebugSections)
529 replaceDebugSections(
Fangrui Song3dfc3fb2019-03-15 10:27:28 +0000530 Obj, RemovePred,
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000531 [](const SectionBase &S) { return isa<CompressedSection>(&S); },
532 [&Obj](const SectionBase *S) {
533 auto CS = cast<CompressedSection>(S);
534 return &Obj.addSection<DecompressedSection>(*CS);
535 });
536
George Rimare6963be2019-03-25 12:34:25 +0000537 return Obj.removeSections(RemovePred);
538}
539
540// This function handles the high level operations of GNU objcopy including
541// handling command line options. It's important to outline certain properties
542// we expect to hold of the command line operations. Any operation that "keeps"
543// should keep regardless of a remove. Additionally any removal should respect
544// any previous removals. Lastly whether or not something is removed shouldn't
545// depend a) on the order the options occur in or b) on some opaque priority
546// system. The only priority is that keeps/copies overrule removes.
547static Error handleArgs(const CopyConfig &Config, Object &Obj,
548 const Reader &Reader, ElfType OutputElfType) {
549
550 if (!Config.SplitDWO.empty())
551 if (Error E =
552 splitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType))
553 return E;
554
555 if (Config.OutputArch) {
556 Obj.Machine = Config.OutputArch.getValue().EMachine;
557 Obj.OSABI = Config.OutputArch.getValue().OSABI;
558 }
559
George Rimar279898b2019-03-26 18:42:15 +0000560 // It is important to remove the sections first. For example, we want to
561 // remove the relocation sections before removing the symbols. That allows
562 // us to avoid reporting the inappropriate errors about removing symbols
563 // named in relocations.
564 if (Error E = replaceAndRemoveSections(Config, Obj))
George Rimare6963be2019-03-25 12:34:25 +0000565 return E;
566
George Rimar279898b2019-03-26 18:42:15 +0000567 if (Error E = updateAndRemoveSymbols(Config, Obj))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000568 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000569
570 if (!Config.SectionsToRename.empty()) {
571 for (auto &Sec : Obj.sections()) {
572 const auto Iter = Config.SectionsToRename.find(Sec.Name);
573 if (Iter != Config.SectionsToRename.end()) {
574 const SectionRename &SR = Iter->second;
575 Sec.Name = SR.NewName;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000576 if (SR.NewFlags.hasValue())
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000577 Sec.Flags = setSectionFlagsPreserveMask(
578 Sec.Flags, getNewShfFlags(SR.NewFlags.getValue()));
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000579 }
580 }
581 }
582
583 if (!Config.SetSectionFlags.empty()) {
584 for (auto &Sec : Obj.sections()) {
585 const auto Iter = Config.SetSectionFlags.find(Sec.Name);
586 if (Iter != Config.SetSectionFlags.end()) {
587 const SectionFlagsUpdate &SFU = Iter->second;
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000588 Sec.Flags = setSectionFlagsPreserveMask(Sec.Flags,
589 getNewShfFlags(SFU.NewFlags));
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000590 }
591 }
592 }
Jordan Rupprechtbd95a9f2019-03-28 18:27:00 +0000593
Eugene Leviantc76671b2019-03-12 12:41:06 +0000594 for (const auto &Flag : Config.AddSection) {
595 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
596 StringRef SecName = SecPair.first;
597 StringRef File = SecPair.second;
598 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
599 MemoryBuffer::getFile(File);
600 if (!BufOrErr)
601 return createFileError(File, errorCodeToError(BufOrErr.getError()));
602 std::unique_ptr<MemoryBuffer> Buf = std::move(*BufOrErr);
603 ArrayRef<uint8_t> Data(
604 reinterpret_cast<const uint8_t *>(Buf->getBufferStart()),
605 Buf->getBufferSize());
606 OwnedDataSection &NewSection =
607 Obj.addSection<OwnedDataSection>(SecName, Data);
608 if (SecName.startswith(".note") && SecName != ".note.GNU-stack")
609 NewSection.Type = SHT_NOTE;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000610 }
611
Eugene Leviantc76671b2019-03-12 12:41:06 +0000612 for (const auto &Flag : Config.DumpSection) {
613 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
614 StringRef SecName = SecPair.first;
615 StringRef File = SecPair.second;
616 if (Error E = dumpSectionToFile(SecName, File, Obj))
617 return createFileError(Config.InputFilename, std::move(E));
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000618 }
619
620 if (!Config.AddGnuDebugLink.empty())
621 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000622
Eugene Leviant51c1f642019-02-25 14:12:41 +0000623 for (const NewSymbolInfo &SI : Config.SymbolsToAdd) {
624 SectionBase *Sec = Obj.findSection(SI.SectionName);
625 uint64_t Value = Sec ? Sec->Addr + SI.Value : SI.Value;
Simon Pilgrim65706cf2019-02-27 10:19:53 +0000626 Obj.SymbolTable->addSymbol(
627 SI.SymbolName, SI.Bind, SI.Type, Sec, Value, SI.Visibility,
628 Sec ? (uint16_t)SYMBOL_SIMPLE_INDEX : (uint16_t)SHN_ABS, 0);
Eugene Leviant51c1f642019-02-25 14:12:41 +0000629 }
630
Eugene Leviant53350d02019-02-26 09:24:22 +0000631 if (Config.EntryExpr)
632 Obj.Entry = Config.EntryExpr(Obj.Entry);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000633 return Error::success();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000634}
635
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000636Error executeObjcopyOnRawBinary(const CopyConfig &Config, MemoryBuffer &In,
637 Buffer &Out) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000638 BinaryReader Reader(Config.BinaryArch, &In);
639 std::unique_ptr<Object> Obj = Reader.create();
640
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000641 // Prefer OutputArch (-O<format>) if set, otherwise fallback to BinaryArch
642 // (-B<arch>).
643 const ElfType OutputElfType = getOutputElfType(
644 Config.OutputArch ? Config.OutputArch.getValue() : Config.BinaryArch);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000645 if (Error E = handleArgs(Config, *Obj, Reader, OutputElfType))
646 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000647 std::unique_ptr<Writer> Writer =
648 createWriter(Config, *Obj, Out, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000649 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000650 return E;
651 return Writer->write();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000652}
653
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000654Error executeObjcopyOnBinary(const CopyConfig &Config,
655 object::ELFObjectFileBase &In, Buffer &Out) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000656 ELFReader Reader(&In);
657 std::unique_ptr<Object> Obj = Reader.create();
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000658 // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
659 const ElfType OutputElfType =
660 Config.OutputArch ? getOutputElfType(Config.OutputArch.getValue())
661 : getOutputElfType(In);
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000662 ArrayRef<uint8_t> BuildIdBytes;
663
664 if (!Config.BuildIdLinkDir.empty()) {
665 BuildIdBytes = unwrapOrError(findBuildID(In));
666 if (BuildIdBytes.size() < 2)
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000667 return createFileError(
668 Config.InputFilename,
669 createStringError(object_error::parse_failed,
670 "build ID is smaller than two bytes."));
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000671 }
672
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000673 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkInput)
674 if (Error E =
675 linkToBuildIdDir(Config, Config.InputFilename,
676 Config.BuildIdLinkInput.getValue(), BuildIdBytes))
677 return E;
678
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000679 if (Error E = handleArgs(Config, *Obj, Reader, OutputElfType))
680 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000681 std::unique_ptr<Writer> Writer =
682 createWriter(Config, *Obj, Out, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000683 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000684 return E;
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000685 if (Error E = Writer->write())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000686 return E;
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000687 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkOutput)
688 if (Error E =
689 linkToBuildIdDir(Config, Config.OutputFilename,
690 Config.BuildIdLinkOutput.getValue(), BuildIdBytes))
691 return E;
692
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000693 return Error::success();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000694}
695
696} // end namespace elf
697} // end namespace objcopy
698} // end namespace llvm