blob: fc1ac38ec872ebf311febdd3e032d3402369992b [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
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000301// This function handles the high level operations of GNU objcopy including
302// handling command line options. It's important to outline certain properties
303// we expect to hold of the command line operations. Any operation that "keeps"
304// should keep regardless of a remove. Additionally any removal should respect
305// any previous removals. Lastly whether or not something is removed shouldn't
306// depend a) on the order the options occur in or b) on some opaque priority
307// system. The only priority is that keeps/copies overrule removes.
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000308static Error handleArgs(const CopyConfig &Config, Object &Obj,
309 const Reader &Reader, ElfType OutputElfType) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000310
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000311 if (!Config.SplitDWO.empty())
312 if (Error E =
313 splitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType))
314 return E;
315
James Hendersonc040d5d2019-03-22 10:21:09 +0000316 if (Config.OutputArch) {
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000317 Obj.Machine = Config.OutputArch.getValue().EMachine;
James Hendersonc040d5d2019-03-22 10:21:09 +0000318 Obj.OSABI = Config.OutputArch.getValue().OSABI;
319 }
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000320
321 // TODO: update or remove symbols only if there is an option that affects
322 // them.
323 if (Obj.SymbolTable) {
324 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
Jordan Rupprechtbd7735f2019-01-31 16:45:16 +0000325 // Common and undefined symbols don't make sense as local symbols, and can
326 // even cause crashes if we localize those, so skip them.
327 if (!Sym.isCommon() && Sym.getShndx() != SHN_UNDEF &&
Jordan Rupprechtb47475c2018-11-01 17:26:36 +0000328 ((Config.LocalizeHidden &&
329 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
Fangrui Songe4ee0662018-11-29 17:32:51 +0000330 is_contained(Config.SymbolsToLocalize, Sym.Name)))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000331 Sym.Binding = STB_LOCAL;
332
333 // Note: these two globalize flags have very similar names but different
334 // meanings:
335 //
336 // --globalize-symbol: promote a symbol to global
337 // --keep-global-symbol: all symbols except for these should be made local
338 //
339 // If --globalize-symbol is specified for a given symbol, it will be
340 // global in the output file even if it is not included via
341 // --keep-global-symbol. Because of that, make sure to check
342 // --globalize-symbol second.
343 if (!Config.SymbolsToKeepGlobal.empty() &&
Jordan Rupprecht634820d2018-10-30 16:23:38 +0000344 !is_contained(Config.SymbolsToKeepGlobal, Sym.Name) &&
345 Sym.getShndx() != SHN_UNDEF)
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000346 Sym.Binding = STB_LOCAL;
347
Fangrui Songe4ee0662018-11-29 17:32:51 +0000348 if (is_contained(Config.SymbolsToGlobalize, Sym.Name) &&
Jordan Rupprecht634820d2018-10-30 16:23:38 +0000349 Sym.getShndx() != SHN_UNDEF)
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000350 Sym.Binding = STB_GLOBAL;
351
Fangrui Songe4ee0662018-11-29 17:32:51 +0000352 if (is_contained(Config.SymbolsToWeaken, Sym.Name) &&
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000353 Sym.Binding == STB_GLOBAL)
354 Sym.Binding = STB_WEAK;
355
356 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
357 Sym.getShndx() != SHN_UNDEF)
358 Sym.Binding = STB_WEAK;
359
360 const auto I = Config.SymbolsToRename.find(Sym.Name);
361 if (I != Config.SymbolsToRename.end())
362 Sym.Name = I->getValue();
363
364 if (!Config.SymbolsPrefix.empty() && Sym.Type != STT_SECTION)
365 Sym.Name = (Config.SymbolsPrefix + Sym.Name).str();
366 });
367
368 // The purpose of this loop is to mark symbols referenced by sections
369 // (like GroupSection or RelocationSection). This way, we know which
370 // symbols are still 'needed' and which are not.
Eugene Leviant2db10622019-02-13 07:34:54 +0000371 if (Config.StripUnneeded || !Config.UnneededSymbolsToRemove.empty()) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000372 for (auto &Section : Obj.sections())
373 Section.markSymbols();
374 }
375
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000376 auto RemoveSymbolsPred = [&](const Symbol &Sym) {
Fangrui Songe4ee0662018-11-29 17:32:51 +0000377 if (is_contained(Config.SymbolsToKeep, Sym.Name) ||
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000378 (Config.KeepFileSymbols && Sym.Type == STT_FILE))
379 return false;
380
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000381 if ((Config.DiscardMode == DiscardType::All ||
382 (Config.DiscardMode == DiscardType::Locals &&
383 StringRef(Sym.Name).startswith(".L"))) &&
384 Sym.Binding == STB_LOCAL && Sym.getShndx() != SHN_UNDEF &&
385 Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000386 return true;
387
388 if (Config.StripAll || Config.StripAllGNU)
389 return true;
390
Fangrui Songe4ee0662018-11-29 17:32:51 +0000391 if (is_contained(Config.SymbolsToRemove, Sym.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000392 return true;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000393
Eugene Leviant2db10622019-02-13 07:34:54 +0000394 if ((Config.StripUnneeded ||
395 is_contained(Config.UnneededSymbolsToRemove, Sym.Name)) &&
396 isUnneededSymbol(Sym))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000397 return true;
398
399 return false;
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000400 };
401 if (Error E = Obj.removeSymbols(RemoveSymbolsPred))
402 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000403 }
404
405 SectionPred RemovePred = [](const SectionBase &) { return false; };
406
407 // Removes:
408 if (!Config.ToRemove.empty()) {
409 RemovePred = [&Config](const SectionBase &Sec) {
410 return is_contained(Config.ToRemove, Sec.Name);
411 };
412 }
413
414 if (Config.StripDWO || !Config.SplitDWO.empty())
415 RemovePred = [RemovePred](const SectionBase &Sec) {
416 return isDWOSection(Sec) || RemovePred(Sec);
417 };
418
419 if (Config.ExtractDWO)
420 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
421 return onlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
422 };
423
424 if (Config.StripAllGNU)
425 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
426 if (RemovePred(Sec))
427 return true;
428 if ((Sec.Flags & SHF_ALLOC) != 0)
429 return false;
430 if (&Sec == Obj.SectionNames)
431 return false;
432 switch (Sec.Type) {
433 case SHT_SYMTAB:
434 case SHT_REL:
435 case SHT_RELA:
436 case SHT_STRTAB:
437 return true;
438 }
439 return isDebugSection(Sec);
440 };
441
442 if (Config.StripSections) {
443 RemovePred = [RemovePred](const SectionBase &Sec) {
James Hendersonb5de5e22019-03-14 11:47:41 +0000444 return RemovePred(Sec) || Sec.ParentSegment == nullptr;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000445 };
446 }
447
448 if (Config.StripDebug) {
449 RemovePred = [RemovePred](const SectionBase &Sec) {
450 return RemovePred(Sec) || isDebugSection(Sec);
451 };
452 }
453
454 if (Config.StripNonAlloc)
455 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
456 if (RemovePred(Sec))
457 return true;
458 if (&Sec == Obj.SectionNames)
459 return false;
James Hendersonb5de5e22019-03-14 11:47:41 +0000460 return (Sec.Flags & SHF_ALLOC) == 0 && Sec.ParentSegment == nullptr;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000461 };
462
463 if (Config.StripAll)
464 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
465 if (RemovePred(Sec))
466 return true;
467 if (&Sec == Obj.SectionNames)
468 return false;
469 if (StringRef(Sec.Name).startswith(".gnu.warning"))
470 return false;
James Hendersonb5de5e22019-03-14 11:47:41 +0000471 if (Sec.ParentSegment != nullptr)
472 return false;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000473 return (Sec.Flags & SHF_ALLOC) == 0;
474 };
475
476 // Explicit copies:
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000477 if (!Config.OnlySection.empty()) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000478 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
479 // Explicitly keep these sections regardless of previous removes.
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000480 if (is_contained(Config.OnlySection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000481 return false;
482
483 // Allow all implicit removes.
484 if (RemovePred(Sec))
485 return true;
486
487 // Keep special sections.
488 if (Obj.SectionNames == &Sec)
489 return false;
490 if (Obj.SymbolTable == &Sec ||
491 (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
492 return false;
493
494 // Remove everything else.
495 return true;
496 };
497 }
498
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000499 if (!Config.KeepSection.empty()) {
Fangrui Songe9f34b02018-11-12 23:46:22 +0000500 RemovePred = [&Config, RemovePred](const SectionBase &Sec) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000501 // Explicitly keep these sections regardless of previous removes.
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000502 if (is_contained(Config.KeepSection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000503 return false;
504 // Otherwise defer to RemovePred.
505 return RemovePred(Sec);
506 };
507 }
508
509 // This has to be the last predicate assignment.
510 // If the option --keep-symbol has been specified
511 // and at least one of those symbols is present
512 // (equivalently, the updated symbol table is not empty)
513 // the symbol table and the string table should not be removed.
514 if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) &&
515 Obj.SymbolTable && !Obj.SymbolTable->empty()) {
516 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
517 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
518 return false;
519 return RemovePred(Sec);
520 };
521 }
522
523 if (Config.CompressionType != DebugCompressionType::None)
Fangrui Song3dfc3fb2019-03-15 10:27:28 +0000524 replaceDebugSections(Obj, RemovePred, isCompressable,
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000525 [&Config, &Obj](const SectionBase *S) {
526 return &Obj.addSection<CompressedSection>(
527 *S, Config.CompressionType);
528 });
529 else if (Config.DecompressDebugSections)
530 replaceDebugSections(
Fangrui Song3dfc3fb2019-03-15 10:27:28 +0000531 Obj, RemovePred,
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000532 [](const SectionBase &S) { return isa<CompressedSection>(&S); },
533 [&Obj](const SectionBase *S) {
534 auto CS = cast<CompressedSection>(S);
535 return &Obj.addSection<DecompressedSection>(*CS);
536 });
537
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000538 if (Error E = Obj.removeSections(RemovePred))
539 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000540
541 if (!Config.SectionsToRename.empty()) {
542 for (auto &Sec : Obj.sections()) {
543 const auto Iter = Config.SectionsToRename.find(Sec.Name);
544 if (Iter != Config.SectionsToRename.end()) {
545 const SectionRename &SR = Iter->second;
546 Sec.Name = SR.NewName;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000547 if (SR.NewFlags.hasValue())
548 Sec.Flags =
549 setSectionFlagsPreserveMask(Sec.Flags, SR.NewFlags.getValue());
550 }
551 }
552 }
553
554 if (!Config.SetSectionFlags.empty()) {
555 for (auto &Sec : Obj.sections()) {
556 const auto Iter = Config.SetSectionFlags.find(Sec.Name);
557 if (Iter != Config.SetSectionFlags.end()) {
558 const SectionFlagsUpdate &SFU = Iter->second;
559 Sec.Flags = setSectionFlagsPreserveMask(Sec.Flags, SFU.NewFlags);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000560 }
561 }
562 }
Eugene Leviantc76671b2019-03-12 12:41:06 +0000563
564 for (const auto &Flag : Config.AddSection) {
565 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
566 StringRef SecName = SecPair.first;
567 StringRef File = SecPair.second;
568 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
569 MemoryBuffer::getFile(File);
570 if (!BufOrErr)
571 return createFileError(File, errorCodeToError(BufOrErr.getError()));
572 std::unique_ptr<MemoryBuffer> Buf = std::move(*BufOrErr);
573 ArrayRef<uint8_t> Data(
574 reinterpret_cast<const uint8_t *>(Buf->getBufferStart()),
575 Buf->getBufferSize());
576 OwnedDataSection &NewSection =
577 Obj.addSection<OwnedDataSection>(SecName, Data);
578 if (SecName.startswith(".note") && SecName != ".note.GNU-stack")
579 NewSection.Type = SHT_NOTE;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000580 }
581
Eugene Leviantc76671b2019-03-12 12:41:06 +0000582 for (const auto &Flag : Config.DumpSection) {
583 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
584 StringRef SecName = SecPair.first;
585 StringRef File = SecPair.second;
586 if (Error E = dumpSectionToFile(SecName, File, Obj))
587 return createFileError(Config.InputFilename, std::move(E));
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000588 }
589
590 if (!Config.AddGnuDebugLink.empty())
591 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000592
Eugene Leviant51c1f642019-02-25 14:12:41 +0000593 for (const NewSymbolInfo &SI : Config.SymbolsToAdd) {
594 SectionBase *Sec = Obj.findSection(SI.SectionName);
595 uint64_t Value = Sec ? Sec->Addr + SI.Value : SI.Value;
Simon Pilgrim65706cf2019-02-27 10:19:53 +0000596 Obj.SymbolTable->addSymbol(
597 SI.SymbolName, SI.Bind, SI.Type, Sec, Value, SI.Visibility,
598 Sec ? (uint16_t)SYMBOL_SIMPLE_INDEX : (uint16_t)SHN_ABS, 0);
Eugene Leviant51c1f642019-02-25 14:12:41 +0000599 }
600
Eugene Leviant53350d02019-02-26 09:24:22 +0000601 if (Config.EntryExpr)
602 Obj.Entry = Config.EntryExpr(Obj.Entry);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000603 return Error::success();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000604}
605
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000606Error executeObjcopyOnRawBinary(const CopyConfig &Config, MemoryBuffer &In,
607 Buffer &Out) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000608 BinaryReader Reader(Config.BinaryArch, &In);
609 std::unique_ptr<Object> Obj = Reader.create();
610
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000611 // Prefer OutputArch (-O<format>) if set, otherwise fallback to BinaryArch
612 // (-B<arch>).
613 const ElfType OutputElfType = getOutputElfType(
614 Config.OutputArch ? Config.OutputArch.getValue() : Config.BinaryArch);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000615 if (Error E = handleArgs(Config, *Obj, Reader, OutputElfType))
616 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000617 std::unique_ptr<Writer> Writer =
618 createWriter(Config, *Obj, Out, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000619 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000620 return E;
621 return Writer->write();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000622}
623
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000624Error executeObjcopyOnBinary(const CopyConfig &Config,
625 object::ELFObjectFileBase &In, Buffer &Out) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000626 ELFReader Reader(&In);
627 std::unique_ptr<Object> Obj = Reader.create();
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000628 // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
629 const ElfType OutputElfType =
630 Config.OutputArch ? getOutputElfType(Config.OutputArch.getValue())
631 : getOutputElfType(In);
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000632 ArrayRef<uint8_t> BuildIdBytes;
633
634 if (!Config.BuildIdLinkDir.empty()) {
635 BuildIdBytes = unwrapOrError(findBuildID(In));
636 if (BuildIdBytes.size() < 2)
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000637 return createFileError(
638 Config.InputFilename,
639 createStringError(object_error::parse_failed,
640 "build ID is smaller than two bytes."));
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000641 }
642
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000643 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkInput)
644 if (Error E =
645 linkToBuildIdDir(Config, Config.InputFilename,
646 Config.BuildIdLinkInput.getValue(), BuildIdBytes))
647 return E;
648
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000649 if (Error E = handleArgs(Config, *Obj, Reader, OutputElfType))
650 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000651 std::unique_ptr<Writer> Writer =
652 createWriter(Config, *Obj, Out, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000653 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000654 return E;
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000655 if (Error E = Writer->write())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000656 return E;
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000657 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkOutput)
658 if (Error E =
659 linkToBuildIdDir(Config, Config.OutputFilename,
660 Config.BuildIdLinkOutput.getValue(), BuildIdBytes))
661 return E;
662
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000663 return Error::success();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000664}
665
666} // end namespace elf
667} // end namespace objcopy
668} // end namespace llvm