blob: 1ae802ff14b3bd1a331e68728124b1fdaec6046a [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 Rupprechtc8927412019-01-29 15:05:38 +000073static uint64_t setSectionFlagsPreserveMask(uint64_t OldFlags,
74 uint64_t NewFlags) {
75 // Preserve some flags which should not be dropped when setting flags.
76 // Also, preserve anything OS/processor dependant.
77 const uint64_t PreserveMask = ELF::SHF_COMPRESSED | ELF::SHF_EXCLUDE |
78 ELF::SHF_GROUP | ELF::SHF_LINK_ORDER |
79 ELF::SHF_MASKOS | ELF::SHF_MASKPROC |
80 ELF::SHF_TLS | ELF::SHF_INFO_LINK;
81 return (OldFlags & PreserveMask) | (NewFlags & ~PreserveMask);
82}
83
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +000084static ElfType getOutputElfType(const Binary &Bin) {
85 // Infer output ELF type from the input ELF object
86 if (isa<ELFObjectFile<ELF32LE>>(Bin))
87 return ELFT_ELF32LE;
88 if (isa<ELFObjectFile<ELF64LE>>(Bin))
89 return ELFT_ELF64LE;
90 if (isa<ELFObjectFile<ELF32BE>>(Bin))
91 return ELFT_ELF32BE;
92 if (isa<ELFObjectFile<ELF64BE>>(Bin))
93 return ELFT_ELF64BE;
94 llvm_unreachable("Invalid ELFType");
95}
96
97static ElfType getOutputElfType(const MachineInfo &MI) {
98 // Infer output ELF type from the binary arch specified
99 if (MI.Is64Bit)
100 return MI.IsLittleEndian ? ELFT_ELF64LE : ELFT_ELF64BE;
101 else
102 return MI.IsLittleEndian ? ELFT_ELF32LE : ELFT_ELF32BE;
103}
104
105static std::unique_ptr<Writer> createWriter(const CopyConfig &Config,
106 Object &Obj, Buffer &Buf,
107 ElfType OutputElfType) {
108 if (Config.OutputFormat == "binary") {
109 return llvm::make_unique<BinaryWriter>(Obj, Buf);
110 }
111 // Depending on the initial ELFT and OutputFormat we need a different Writer.
112 switch (OutputElfType) {
113 case ELFT_ELF32LE:
114 return llvm::make_unique<ELFWriter<ELF32LE>>(Obj, Buf,
115 !Config.StripSections);
116 case ELFT_ELF64LE:
117 return llvm::make_unique<ELFWriter<ELF64LE>>(Obj, Buf,
118 !Config.StripSections);
119 case ELFT_ELF32BE:
120 return llvm::make_unique<ELFWriter<ELF32BE>>(Obj, Buf,
121 !Config.StripSections);
122 case ELFT_ELF64BE:
123 return llvm::make_unique<ELFWriter<ELF64BE>>(Obj, Buf,
124 !Config.StripSections);
125 }
126 llvm_unreachable("Invalid output format");
127}
128
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000129template <class ELFT>
130static Expected<ArrayRef<uint8_t>>
131findBuildID(const object::ELFFile<ELFT> &In) {
132 for (const auto &Phdr : unwrapOrError(In.program_headers())) {
133 if (Phdr.p_type != PT_NOTE)
134 continue;
135 Error Err = Error::success();
David Blaikieba005aa2018-12-11 00:09:06 +0000136 for (const auto &Note : In.notes(Phdr, Err))
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000137 if (Note.getType() == NT_GNU_BUILD_ID && Note.getName() == ELF_NOTE_GNU)
138 return Note.getDesc();
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000139 if (Err)
140 return std::move(Err);
141 }
142 return createStringError(llvm::errc::invalid_argument,
143 "Could not find build ID.");
144}
145
146static Expected<ArrayRef<uint8_t>>
147findBuildID(const object::ELFObjectFileBase &In) {
148 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(&In))
149 return findBuildID(*O->getELFFile());
150 else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(&In))
151 return findBuildID(*O->getELFFile());
152 else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(&In))
153 return findBuildID(*O->getELFFile());
154 else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(&In))
155 return findBuildID(*O->getELFFile());
156
157 llvm_unreachable("Bad file format");
158}
159
Jake Ehrlich5049c342019-03-18 20:35:18 +0000160template <class... Ts>
161static Error makeStringError(std::error_code EC, const Twine &Msg, Ts&&... Args) {
162 std::string FullMsg = (EC.message() + ": " + Msg).str();
163 return createStringError(EC, FullMsg.c_str(), std::forward<Ts>(Args)...);
164}
165
166#define MODEL_8 "%%%%%%%%"
167#define MODEL_16 MODEL_8 MODEL_8
168#define MODEL_32 (MODEL_16 MODEL_16)
169
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000170static Error linkToBuildIdDir(const CopyConfig &Config, StringRef ToLink,
171 StringRef Suffix,
172 ArrayRef<uint8_t> BuildIdBytes) {
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000173 SmallString<128> Path = Config.BuildIdLinkDir;
174 sys::path::append(Path, llvm::toHex(BuildIdBytes[0], /*LowerCase*/ true));
175 if (auto EC = sys::fs::create_directories(Path))
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000176 return createFileError(
177 Path.str(),
Jake Ehrlich5049c342019-03-18 20:35:18 +0000178 makeStringError(EC, "cannot create build ID link directory"));
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000179
180 sys::path::append(Path,
181 llvm::toHex(BuildIdBytes.slice(1), /*LowerCase*/ true));
182 Path += Suffix;
Jake Ehrlich5049c342019-03-18 20:35:18 +0000183 SmallString<128> TmpPath;
184 // create_hard_link races so we need to link to a temporary path but
185 // we want to make sure that we choose a filename that does not exist.
186 // By using 32 model characters we get 128-bits of entropy. It is
187 // unlikely that this string has ever existed before much less exists
188 // on this disk or in the current working directory.
189 // Additionally we prepend the original Path for debugging but also
190 // because it ensures that we're linking within a directory on the same
191 // partition on the same device which is critical. It has the added
192 // win of yet further decreasing the odds of a conflict.
193 sys::fs::createUniquePath(Twine(Path) + "-" + MODEL_32 + ".tmp", TmpPath,
194 /*MakeAbsolute*/ false);
195 if (auto EC = sys::fs::create_hard_link(ToLink, TmpPath)) {
196 Path.push_back('\0');
197 return makeStringError(EC, "cannot link %s to %s", ToLink.data(),
198 Path.data());
199 }
200 // We then atomically rename the link into place which will just move the
201 // link. If rename fails something is more seriously wrong so just return
202 // an error.
203 if (auto EC = sys::fs::rename(TmpPath, Path)) {
204 Path.push_back('\0');
205 return makeStringError(EC, "cannot link %s to %s", ToLink.data(),
206 Path.data());
207 }
208 // If `Path` was already a hard-link to the same underlying file then the
209 // temp file will be left so we need to remove it. Remove will not cause
210 // an error by default if the file is already gone so just blindly remove
211 // it rather than checking.
212 if (auto EC = sys::fs::remove(TmpPath)) {
213 TmpPath.push_back('\0');
214 return makeStringError(EC, "could not remove %s", TmpPath.data());
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000215 }
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000216 return Error::success();
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000217}
218
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000219static Error splitDWOToFile(const CopyConfig &Config, const Reader &Reader,
220 StringRef File, ElfType OutputElfType) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000221 auto DWOFile = Reader.create();
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000222 auto OnlyKeepDWOPred = [&DWOFile](const SectionBase &Sec) {
223 return onlyKeepDWOPred(*DWOFile, Sec);
224 };
225 if (Error E = DWOFile->removeSections(OnlyKeepDWOPred))
226 return E;
James Hendersonc040d5d2019-03-22 10:21:09 +0000227 if (Config.OutputArch) {
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000228 DWOFile->Machine = Config.OutputArch.getValue().EMachine;
James Hendersonc040d5d2019-03-22 10:21:09 +0000229 DWOFile->OSABI = Config.OutputArch.getValue().OSABI;
230 }
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000231 FileBuffer FB(File);
232 auto Writer = createWriter(Config, *DWOFile, FB, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000233 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000234 return E;
235 return Writer->write();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000236}
237
238static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
239 Object &Obj) {
240 for (auto &Sec : Obj.sections()) {
241 if (Sec.Name == SecName) {
Jordan Rupprecht16a0de22018-12-20 00:57:06 +0000242 if (Sec.OriginalData.empty())
Martin Storsjo8010c6be2019-01-22 10:57:59 +0000243 return createStringError(
244 object_error::parse_failed,
245 "Can't dump section \"%s\": it has no contents",
246 SecName.str().c_str());
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000247 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
248 FileOutputBuffer::create(Filename, Sec.OriginalData.size());
249 if (!BufferOrErr)
250 return BufferOrErr.takeError();
251 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
252 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(),
253 Buf->getBufferStart());
254 if (Error E = Buf->commit())
255 return E;
256 return Error::success();
257 }
258 }
Martin Storsjo8010c6be2019-01-22 10:57:59 +0000259 return createStringError(object_error::parse_failed, "Section not found");
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000260}
261
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000262static bool isCompressable(const SectionBase &Section) {
George Rimarade3c702019-03-05 13:07:43 +0000263 return !(Section.Flags & ELF::SHF_COMPRESSED) &&
264 StringRef(Section.Name).startswith(".debug");
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000265}
266
267static void replaceDebugSections(
Fangrui Song3dfc3fb2019-03-15 10:27:28 +0000268 Object &Obj, SectionPred &RemovePred,
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000269 function_ref<bool(const SectionBase &)> shouldReplace,
270 function_ref<SectionBase *(const SectionBase *)> addSection) {
George Rimard8a5c6c2019-03-11 11:01:24 +0000271 // Build a list of the debug sections we are going to replace.
272 // We can't call `addSection` while iterating over sections,
273 // because it would mutate the sections array.
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000274 SmallVector<SectionBase *, 13> ToReplace;
George Rimard8a5c6c2019-03-11 11:01:24 +0000275 for (auto &Sec : Obj.sections())
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000276 if (shouldReplace(Sec))
277 ToReplace.push_back(&Sec);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000278
George Rimard8a5c6c2019-03-11 11:01:24 +0000279 // Build a mapping from original section to a new one.
280 DenseMap<SectionBase *, SectionBase *> FromTo;
281 for (SectionBase *S : ToReplace)
282 FromTo[S] = addSection(S);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000283
George Rimard8a5c6c2019-03-11 11:01:24 +0000284 // Now we want to update the target sections of relocation
285 // sections. Also we will update the relocations themselves
286 // to update the symbol references.
287 for (auto &Sec : Obj.sections())
288 Sec.replaceSectionReferences(FromTo);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000289
290 RemovePred = [shouldReplace, RemovePred](const SectionBase &Sec) {
291 return shouldReplace(Sec) || RemovePred(Sec);
292 };
293}
294
Eugene Leviant2db10622019-02-13 07:34:54 +0000295static bool isUnneededSymbol(const Symbol &Sym) {
296 return !Sym.Referenced &&
297 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
298 Sym.Type != STT_FILE && Sym.Type != STT_SECTION;
299}
300
George Rimare6963be2019-03-25 12:34:25 +0000301static Error updateAndRemoveSymbols(const CopyConfig &Config, Object &Obj) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000302 // TODO: update or remove symbols only if there is an option that affects
303 // them.
George Rimare6963be2019-03-25 12:34:25 +0000304 if (!Obj.SymbolTable)
305 return Error::success();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000306
George Rimare6963be2019-03-25 12:34:25 +0000307 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
308 // Common and undefined symbols don't make sense as local symbols, and can
309 // even cause crashes if we localize those, so skip them.
310 if (!Sym.isCommon() && Sym.getShndx() != SHN_UNDEF &&
311 ((Config.LocalizeHidden &&
312 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
313 is_contained(Config.SymbolsToLocalize, Sym.Name)))
314 Sym.Binding = STB_LOCAL;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000315
George Rimare6963be2019-03-25 12:34:25 +0000316 // Note: these two globalize flags have very similar names but different
317 // meanings:
318 //
319 // --globalize-symbol: promote a symbol to global
320 // --keep-global-symbol: all symbols except for these should be made local
321 //
322 // If --globalize-symbol is specified for a given symbol, it will be
323 // global in the output file even if it is not included via
324 // --keep-global-symbol. Because of that, make sure to check
325 // --globalize-symbol second.
326 if (!Config.SymbolsToKeepGlobal.empty() &&
327 !is_contained(Config.SymbolsToKeepGlobal, Sym.Name) &&
328 Sym.getShndx() != SHN_UNDEF)
329 Sym.Binding = STB_LOCAL;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000330
George Rimare6963be2019-03-25 12:34:25 +0000331 if (is_contained(Config.SymbolsToGlobalize, Sym.Name) &&
332 Sym.getShndx() != SHN_UNDEF)
333 Sym.Binding = STB_GLOBAL;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000334
George Rimare6963be2019-03-25 12:34:25 +0000335 if (is_contained(Config.SymbolsToWeaken, Sym.Name) &&
336 Sym.Binding == STB_GLOBAL)
337 Sym.Binding = STB_WEAK;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000338
George Rimare6963be2019-03-25 12:34:25 +0000339 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
340 Sym.getShndx() != SHN_UNDEF)
341 Sym.Binding = STB_WEAK;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000342
George Rimare6963be2019-03-25 12:34:25 +0000343 const auto I = Config.SymbolsToRename.find(Sym.Name);
344 if (I != Config.SymbolsToRename.end())
345 Sym.Name = I->getValue();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000346
George Rimare6963be2019-03-25 12:34:25 +0000347 if (!Config.SymbolsPrefix.empty() && Sym.Type != STT_SECTION)
348 Sym.Name = (Config.SymbolsPrefix + Sym.Name).str();
349 });
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000350
George Rimare6963be2019-03-25 12:34:25 +0000351 // The purpose of this loop is to mark symbols referenced by sections
352 // (like GroupSection or RelocationSection). This way, we know which
353 // symbols are still 'needed' and which are not.
354 if (Config.StripUnneeded || !Config.UnneededSymbolsToRemove.empty()) {
355 for (auto &Section : Obj.sections())
356 Section.markSymbols();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000357 }
358
George Rimare6963be2019-03-25 12:34:25 +0000359 auto RemoveSymbolsPred = [&](const Symbol &Sym) {
360 if (is_contained(Config.SymbolsToKeep, Sym.Name) ||
361 (Config.KeepFileSymbols && Sym.Type == STT_FILE))
362 return false;
363
364 if ((Config.DiscardMode == DiscardType::All ||
365 (Config.DiscardMode == DiscardType::Locals &&
366 StringRef(Sym.Name).startswith(".L"))) &&
367 Sym.Binding == STB_LOCAL && Sym.getShndx() != SHN_UNDEF &&
368 Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
369 return true;
370
371 if (Config.StripAll || Config.StripAllGNU)
372 return true;
373
374 if (is_contained(Config.SymbolsToRemove, Sym.Name))
375 return true;
376
377 if ((Config.StripUnneeded ||
378 is_contained(Config.UnneededSymbolsToRemove, Sym.Name)) &&
379 isUnneededSymbol(Sym))
380 return true;
381
382 return false;
383 };
384
385 return Obj.removeSymbols(RemoveSymbolsPred);
386}
387
388static Error replaceAndRemoveSections(const CopyConfig &Config, Object &Obj) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000389 SectionPred RemovePred = [](const SectionBase &) { return false; };
390
391 // Removes:
392 if (!Config.ToRemove.empty()) {
393 RemovePred = [&Config](const SectionBase &Sec) {
394 return is_contained(Config.ToRemove, Sec.Name);
395 };
396 }
397
398 if (Config.StripDWO || !Config.SplitDWO.empty())
399 RemovePred = [RemovePred](const SectionBase &Sec) {
400 return isDWOSection(Sec) || RemovePred(Sec);
401 };
402
403 if (Config.ExtractDWO)
404 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
405 return onlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
406 };
407
408 if (Config.StripAllGNU)
409 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
410 if (RemovePred(Sec))
411 return true;
412 if ((Sec.Flags & SHF_ALLOC) != 0)
413 return false;
414 if (&Sec == Obj.SectionNames)
415 return false;
416 switch (Sec.Type) {
417 case SHT_SYMTAB:
418 case SHT_REL:
419 case SHT_RELA:
420 case SHT_STRTAB:
421 return true;
422 }
423 return isDebugSection(Sec);
424 };
425
426 if (Config.StripSections) {
427 RemovePred = [RemovePred](const SectionBase &Sec) {
James Hendersonb5de5e22019-03-14 11:47:41 +0000428 return RemovePred(Sec) || Sec.ParentSegment == nullptr;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000429 };
430 }
431
432 if (Config.StripDebug) {
433 RemovePred = [RemovePred](const SectionBase &Sec) {
434 return RemovePred(Sec) || isDebugSection(Sec);
435 };
436 }
437
438 if (Config.StripNonAlloc)
439 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
440 if (RemovePred(Sec))
441 return true;
442 if (&Sec == Obj.SectionNames)
443 return false;
James Hendersonb5de5e22019-03-14 11:47:41 +0000444 return (Sec.Flags & SHF_ALLOC) == 0 && Sec.ParentSegment == nullptr;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000445 };
446
447 if (Config.StripAll)
448 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
449 if (RemovePred(Sec))
450 return true;
451 if (&Sec == Obj.SectionNames)
452 return false;
453 if (StringRef(Sec.Name).startswith(".gnu.warning"))
454 return false;
James Hendersonb5de5e22019-03-14 11:47:41 +0000455 if (Sec.ParentSegment != nullptr)
456 return false;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000457 return (Sec.Flags & SHF_ALLOC) == 0;
458 };
459
460 // Explicit copies:
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000461 if (!Config.OnlySection.empty()) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000462 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
463 // Explicitly keep these sections regardless of previous removes.
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000464 if (is_contained(Config.OnlySection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000465 return false;
466
467 // Allow all implicit removes.
468 if (RemovePred(Sec))
469 return true;
470
471 // Keep special sections.
472 if (Obj.SectionNames == &Sec)
473 return false;
474 if (Obj.SymbolTable == &Sec ||
475 (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
476 return false;
477
478 // Remove everything else.
479 return true;
480 };
481 }
482
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000483 if (!Config.KeepSection.empty()) {
Fangrui Songe9f34b02018-11-12 23:46:22 +0000484 RemovePred = [&Config, RemovePred](const SectionBase &Sec) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000485 // Explicitly keep these sections regardless of previous removes.
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000486 if (is_contained(Config.KeepSection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000487 return false;
488 // Otherwise defer to RemovePred.
489 return RemovePred(Sec);
490 };
491 }
492
493 // This has to be the last predicate assignment.
494 // If the option --keep-symbol has been specified
495 // and at least one of those symbols is present
496 // (equivalently, the updated symbol table is not empty)
497 // the symbol table and the string table should not be removed.
498 if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) &&
499 Obj.SymbolTable && !Obj.SymbolTable->empty()) {
500 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
501 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
502 return false;
503 return RemovePred(Sec);
504 };
505 }
506
507 if (Config.CompressionType != DebugCompressionType::None)
Fangrui Song3dfc3fb2019-03-15 10:27:28 +0000508 replaceDebugSections(Obj, RemovePred, isCompressable,
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000509 [&Config, &Obj](const SectionBase *S) {
510 return &Obj.addSection<CompressedSection>(
511 *S, Config.CompressionType);
512 });
513 else if (Config.DecompressDebugSections)
514 replaceDebugSections(
Fangrui Song3dfc3fb2019-03-15 10:27:28 +0000515 Obj, RemovePred,
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000516 [](const SectionBase &S) { return isa<CompressedSection>(&S); },
517 [&Obj](const SectionBase *S) {
518 auto CS = cast<CompressedSection>(S);
519 return &Obj.addSection<DecompressedSection>(*CS);
520 });
521
George Rimare6963be2019-03-25 12:34:25 +0000522 return Obj.removeSections(RemovePred);
523}
524
525// This function handles the high level operations of GNU objcopy including
526// handling command line options. It's important to outline certain properties
527// we expect to hold of the command line operations. Any operation that "keeps"
528// should keep regardless of a remove. Additionally any removal should respect
529// any previous removals. Lastly whether or not something is removed shouldn't
530// depend a) on the order the options occur in or b) on some opaque priority
531// system. The only priority is that keeps/copies overrule removes.
532static Error handleArgs(const CopyConfig &Config, Object &Obj,
533 const Reader &Reader, ElfType OutputElfType) {
534
535 if (!Config.SplitDWO.empty())
536 if (Error E =
537 splitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType))
538 return E;
539
540 if (Config.OutputArch) {
541 Obj.Machine = Config.OutputArch.getValue().EMachine;
542 Obj.OSABI = Config.OutputArch.getValue().OSABI;
543 }
544
545 if (Error E = updateAndRemoveSymbols(Config, Obj))
546 return E;
547
548 if (Error E = replaceAndRemoveSections(Config, Obj))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000549 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000550
551 if (!Config.SectionsToRename.empty()) {
552 for (auto &Sec : Obj.sections()) {
553 const auto Iter = Config.SectionsToRename.find(Sec.Name);
554 if (Iter != Config.SectionsToRename.end()) {
555 const SectionRename &SR = Iter->second;
556 Sec.Name = SR.NewName;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000557 if (SR.NewFlags.hasValue())
558 Sec.Flags =
559 setSectionFlagsPreserveMask(Sec.Flags, SR.NewFlags.getValue());
560 }
561 }
562 }
563
564 if (!Config.SetSectionFlags.empty()) {
565 for (auto &Sec : Obj.sections()) {
566 const auto Iter = Config.SetSectionFlags.find(Sec.Name);
567 if (Iter != Config.SetSectionFlags.end()) {
568 const SectionFlagsUpdate &SFU = Iter->second;
569 Sec.Flags = setSectionFlagsPreserveMask(Sec.Flags, SFU.NewFlags);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000570 }
571 }
572 }
Eugene Leviantc76671b2019-03-12 12:41:06 +0000573
574 for (const auto &Flag : Config.AddSection) {
575 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
576 StringRef SecName = SecPair.first;
577 StringRef File = SecPair.second;
578 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
579 MemoryBuffer::getFile(File);
580 if (!BufOrErr)
581 return createFileError(File, errorCodeToError(BufOrErr.getError()));
582 std::unique_ptr<MemoryBuffer> Buf = std::move(*BufOrErr);
583 ArrayRef<uint8_t> Data(
584 reinterpret_cast<const uint8_t *>(Buf->getBufferStart()),
585 Buf->getBufferSize());
586 OwnedDataSection &NewSection =
587 Obj.addSection<OwnedDataSection>(SecName, Data);
588 if (SecName.startswith(".note") && SecName != ".note.GNU-stack")
589 NewSection.Type = SHT_NOTE;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000590 }
591
Eugene Leviantc76671b2019-03-12 12:41:06 +0000592 for (const auto &Flag : Config.DumpSection) {
593 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
594 StringRef SecName = SecPair.first;
595 StringRef File = SecPair.second;
596 if (Error E = dumpSectionToFile(SecName, File, Obj))
597 return createFileError(Config.InputFilename, std::move(E));
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000598 }
599
600 if (!Config.AddGnuDebugLink.empty())
601 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000602
Eugene Leviant51c1f642019-02-25 14:12:41 +0000603 for (const NewSymbolInfo &SI : Config.SymbolsToAdd) {
604 SectionBase *Sec = Obj.findSection(SI.SectionName);
605 uint64_t Value = Sec ? Sec->Addr + SI.Value : SI.Value;
Simon Pilgrim65706cf2019-02-27 10:19:53 +0000606 Obj.SymbolTable->addSymbol(
607 SI.SymbolName, SI.Bind, SI.Type, Sec, Value, SI.Visibility,
608 Sec ? (uint16_t)SYMBOL_SIMPLE_INDEX : (uint16_t)SHN_ABS, 0);
Eugene Leviant51c1f642019-02-25 14:12:41 +0000609 }
610
Eugene Leviant53350d02019-02-26 09:24:22 +0000611 if (Config.EntryExpr)
612 Obj.Entry = Config.EntryExpr(Obj.Entry);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000613 return Error::success();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000614}
615
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000616Error executeObjcopyOnRawBinary(const CopyConfig &Config, MemoryBuffer &In,
617 Buffer &Out) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000618 BinaryReader Reader(Config.BinaryArch, &In);
619 std::unique_ptr<Object> Obj = Reader.create();
620
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000621 // Prefer OutputArch (-O<format>) if set, otherwise fallback to BinaryArch
622 // (-B<arch>).
623 const ElfType OutputElfType = getOutputElfType(
624 Config.OutputArch ? Config.OutputArch.getValue() : Config.BinaryArch);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000625 if (Error E = handleArgs(Config, *Obj, Reader, OutputElfType))
626 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000627 std::unique_ptr<Writer> Writer =
628 createWriter(Config, *Obj, Out, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000629 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000630 return E;
631 return Writer->write();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000632}
633
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000634Error executeObjcopyOnBinary(const CopyConfig &Config,
635 object::ELFObjectFileBase &In, Buffer &Out) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000636 ELFReader Reader(&In);
637 std::unique_ptr<Object> Obj = Reader.create();
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000638 // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
639 const ElfType OutputElfType =
640 Config.OutputArch ? getOutputElfType(Config.OutputArch.getValue())
641 : getOutputElfType(In);
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000642 ArrayRef<uint8_t> BuildIdBytes;
643
644 if (!Config.BuildIdLinkDir.empty()) {
645 BuildIdBytes = unwrapOrError(findBuildID(In));
646 if (BuildIdBytes.size() < 2)
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000647 return createFileError(
648 Config.InputFilename,
649 createStringError(object_error::parse_failed,
650 "build ID is smaller than two bytes."));
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000651 }
652
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000653 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkInput)
654 if (Error E =
655 linkToBuildIdDir(Config, Config.InputFilename,
656 Config.BuildIdLinkInput.getValue(), BuildIdBytes))
657 return E;
658
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000659 if (Error E = handleArgs(Config, *Obj, Reader, OutputElfType))
660 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000661 std::unique_ptr<Writer> Writer =
662 createWriter(Config, *Obj, Out, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000663 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000664 return E;
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000665 if (Error E = Writer->write())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000666 return E;
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000667 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkOutput)
668 if (Error E =
669 linkToBuildIdDir(Config, Config.OutputFilename,
670 Config.BuildIdLinkOutput.getValue(), BuildIdBytes))
671 return E;
672
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000673 return Error::success();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000674}
675
676} // end namespace elf
677} // end namespace objcopy
678} // end namespace llvm