blob: 883ffa0aaf636c7b4e20b937426c3d7fe592f603 [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;
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000227 if (Config.OutputArch)
228 DWOFile->Machine = Config.OutputArch.getValue().EMachine;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000229 FileBuffer FB(File);
230 auto Writer = createWriter(Config, *DWOFile, FB, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000231 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000232 return E;
233 return Writer->write();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000234}
235
236static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
237 Object &Obj) {
238 for (auto &Sec : Obj.sections()) {
239 if (Sec.Name == SecName) {
Jordan Rupprecht16a0de22018-12-20 00:57:06 +0000240 if (Sec.OriginalData.empty())
Martin Storsjo8010c6be2019-01-22 10:57:59 +0000241 return createStringError(
242 object_error::parse_failed,
243 "Can't dump section \"%s\": it has no contents",
244 SecName.str().c_str());
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000245 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
246 FileOutputBuffer::create(Filename, Sec.OriginalData.size());
247 if (!BufferOrErr)
248 return BufferOrErr.takeError();
249 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
250 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(),
251 Buf->getBufferStart());
252 if (Error E = Buf->commit())
253 return E;
254 return Error::success();
255 }
256 }
Martin Storsjo8010c6be2019-01-22 10:57:59 +0000257 return createStringError(object_error::parse_failed, "Section not found");
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000258}
259
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000260static bool isCompressable(const SectionBase &Section) {
George Rimarade3c702019-03-05 13:07:43 +0000261 return !(Section.Flags & ELF::SHF_COMPRESSED) &&
262 StringRef(Section.Name).startswith(".debug");
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000263}
264
265static void replaceDebugSections(
Fangrui Song3dfc3fb2019-03-15 10:27:28 +0000266 Object &Obj, SectionPred &RemovePred,
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000267 function_ref<bool(const SectionBase &)> shouldReplace,
268 function_ref<SectionBase *(const SectionBase *)> addSection) {
George Rimard8a5c6c2019-03-11 11:01:24 +0000269 // Build a list of the debug sections we are going to replace.
270 // We can't call `addSection` while iterating over sections,
271 // because it would mutate the sections array.
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000272 SmallVector<SectionBase *, 13> ToReplace;
George Rimard8a5c6c2019-03-11 11:01:24 +0000273 for (auto &Sec : Obj.sections())
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000274 if (shouldReplace(Sec))
275 ToReplace.push_back(&Sec);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000276
George Rimard8a5c6c2019-03-11 11:01:24 +0000277 // Build a mapping from original section to a new one.
278 DenseMap<SectionBase *, SectionBase *> FromTo;
279 for (SectionBase *S : ToReplace)
280 FromTo[S] = addSection(S);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000281
George Rimard8a5c6c2019-03-11 11:01:24 +0000282 // Now we want to update the target sections of relocation
283 // sections. Also we will update the relocations themselves
284 // to update the symbol references.
285 for (auto &Sec : Obj.sections())
286 Sec.replaceSectionReferences(FromTo);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000287
288 RemovePred = [shouldReplace, RemovePred](const SectionBase &Sec) {
289 return shouldReplace(Sec) || RemovePred(Sec);
290 };
291}
292
Eugene Leviant2db10622019-02-13 07:34:54 +0000293static bool isUnneededSymbol(const Symbol &Sym) {
294 return !Sym.Referenced &&
295 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
296 Sym.Type != STT_FILE && Sym.Type != STT_SECTION;
297}
298
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000299// This function handles the high level operations of GNU objcopy including
300// handling command line options. It's important to outline certain properties
301// we expect to hold of the command line operations. Any operation that "keeps"
302// should keep regardless of a remove. Additionally any removal should respect
303// any previous removals. Lastly whether or not something is removed shouldn't
304// depend a) on the order the options occur in or b) on some opaque priority
305// system. The only priority is that keeps/copies overrule removes.
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000306static Error handleArgs(const CopyConfig &Config, Object &Obj,
307 const Reader &Reader, ElfType OutputElfType) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000308
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000309 if (!Config.SplitDWO.empty())
310 if (Error E =
311 splitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType))
312 return E;
313
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000314 if (Config.OutputArch)
315 Obj.Machine = Config.OutputArch.getValue().EMachine;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000316
317 // TODO: update or remove symbols only if there is an option that affects
318 // them.
319 if (Obj.SymbolTable) {
320 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
Jordan Rupprechtbd7735f2019-01-31 16:45:16 +0000321 // Common and undefined symbols don't make sense as local symbols, and can
322 // even cause crashes if we localize those, so skip them.
323 if (!Sym.isCommon() && Sym.getShndx() != SHN_UNDEF &&
Jordan Rupprechtb47475c2018-11-01 17:26:36 +0000324 ((Config.LocalizeHidden &&
325 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
Fangrui Songe4ee0662018-11-29 17:32:51 +0000326 is_contained(Config.SymbolsToLocalize, Sym.Name)))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000327 Sym.Binding = STB_LOCAL;
328
329 // Note: these two globalize flags have very similar names but different
330 // meanings:
331 //
332 // --globalize-symbol: promote a symbol to global
333 // --keep-global-symbol: all symbols except for these should be made local
334 //
335 // If --globalize-symbol is specified for a given symbol, it will be
336 // global in the output file even if it is not included via
337 // --keep-global-symbol. Because of that, make sure to check
338 // --globalize-symbol second.
339 if (!Config.SymbolsToKeepGlobal.empty() &&
Jordan Rupprecht634820d2018-10-30 16:23:38 +0000340 !is_contained(Config.SymbolsToKeepGlobal, Sym.Name) &&
341 Sym.getShndx() != SHN_UNDEF)
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000342 Sym.Binding = STB_LOCAL;
343
Fangrui Songe4ee0662018-11-29 17:32:51 +0000344 if (is_contained(Config.SymbolsToGlobalize, Sym.Name) &&
Jordan Rupprecht634820d2018-10-30 16:23:38 +0000345 Sym.getShndx() != SHN_UNDEF)
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000346 Sym.Binding = STB_GLOBAL;
347
Fangrui Songe4ee0662018-11-29 17:32:51 +0000348 if (is_contained(Config.SymbolsToWeaken, Sym.Name) &&
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000349 Sym.Binding == STB_GLOBAL)
350 Sym.Binding = STB_WEAK;
351
352 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
353 Sym.getShndx() != SHN_UNDEF)
354 Sym.Binding = STB_WEAK;
355
356 const auto I = Config.SymbolsToRename.find(Sym.Name);
357 if (I != Config.SymbolsToRename.end())
358 Sym.Name = I->getValue();
359
360 if (!Config.SymbolsPrefix.empty() && Sym.Type != STT_SECTION)
361 Sym.Name = (Config.SymbolsPrefix + Sym.Name).str();
362 });
363
364 // The purpose of this loop is to mark symbols referenced by sections
365 // (like GroupSection or RelocationSection). This way, we know which
366 // symbols are still 'needed' and which are not.
Eugene Leviant2db10622019-02-13 07:34:54 +0000367 if (Config.StripUnneeded || !Config.UnneededSymbolsToRemove.empty()) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000368 for (auto &Section : Obj.sections())
369 Section.markSymbols();
370 }
371
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000372 auto RemoveSymbolsPred = [&](const Symbol &Sym) {
Fangrui Songe4ee0662018-11-29 17:32:51 +0000373 if (is_contained(Config.SymbolsToKeep, Sym.Name) ||
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000374 (Config.KeepFileSymbols && Sym.Type == STT_FILE))
375 return false;
376
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000377 if ((Config.DiscardMode == DiscardType::All ||
378 (Config.DiscardMode == DiscardType::Locals &&
379 StringRef(Sym.Name).startswith(".L"))) &&
380 Sym.Binding == STB_LOCAL && Sym.getShndx() != SHN_UNDEF &&
381 Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000382 return true;
383
384 if (Config.StripAll || Config.StripAllGNU)
385 return true;
386
Fangrui Songe4ee0662018-11-29 17:32:51 +0000387 if (is_contained(Config.SymbolsToRemove, Sym.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000388 return true;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000389
Eugene Leviant2db10622019-02-13 07:34:54 +0000390 if ((Config.StripUnneeded ||
391 is_contained(Config.UnneededSymbolsToRemove, Sym.Name)) &&
392 isUnneededSymbol(Sym))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000393 return true;
394
395 return false;
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000396 };
397 if (Error E = Obj.removeSymbols(RemoveSymbolsPred))
398 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000399 }
400
401 SectionPred RemovePred = [](const SectionBase &) { return false; };
402
403 // Removes:
404 if (!Config.ToRemove.empty()) {
405 RemovePred = [&Config](const SectionBase &Sec) {
406 return is_contained(Config.ToRemove, Sec.Name);
407 };
408 }
409
410 if (Config.StripDWO || !Config.SplitDWO.empty())
411 RemovePred = [RemovePred](const SectionBase &Sec) {
412 return isDWOSection(Sec) || RemovePred(Sec);
413 };
414
415 if (Config.ExtractDWO)
416 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
417 return onlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
418 };
419
420 if (Config.StripAllGNU)
421 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
422 if (RemovePred(Sec))
423 return true;
424 if ((Sec.Flags & SHF_ALLOC) != 0)
425 return false;
426 if (&Sec == Obj.SectionNames)
427 return false;
428 switch (Sec.Type) {
429 case SHT_SYMTAB:
430 case SHT_REL:
431 case SHT_RELA:
432 case SHT_STRTAB:
433 return true;
434 }
435 return isDebugSection(Sec);
436 };
437
438 if (Config.StripSections) {
439 RemovePred = [RemovePred](const SectionBase &Sec) {
James Hendersonb5de5e22019-03-14 11:47:41 +0000440 return RemovePred(Sec) || Sec.ParentSegment == nullptr;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000441 };
442 }
443
444 if (Config.StripDebug) {
445 RemovePred = [RemovePred](const SectionBase &Sec) {
446 return RemovePred(Sec) || isDebugSection(Sec);
447 };
448 }
449
450 if (Config.StripNonAlloc)
451 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
452 if (RemovePred(Sec))
453 return true;
454 if (&Sec == Obj.SectionNames)
455 return false;
James Hendersonb5de5e22019-03-14 11:47:41 +0000456 return (Sec.Flags & SHF_ALLOC) == 0 && Sec.ParentSegment == nullptr;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000457 };
458
459 if (Config.StripAll)
460 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
461 if (RemovePred(Sec))
462 return true;
463 if (&Sec == Obj.SectionNames)
464 return false;
465 if (StringRef(Sec.Name).startswith(".gnu.warning"))
466 return false;
James Hendersonb5de5e22019-03-14 11:47:41 +0000467 if (Sec.ParentSegment != nullptr)
468 return false;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000469 return (Sec.Flags & SHF_ALLOC) == 0;
470 };
471
472 // Explicit copies:
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000473 if (!Config.OnlySection.empty()) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000474 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
475 // Explicitly keep these sections regardless of previous removes.
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000476 if (is_contained(Config.OnlySection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000477 return false;
478
479 // Allow all implicit removes.
480 if (RemovePred(Sec))
481 return true;
482
483 // Keep special sections.
484 if (Obj.SectionNames == &Sec)
485 return false;
486 if (Obj.SymbolTable == &Sec ||
487 (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
488 return false;
489
490 // Remove everything else.
491 return true;
492 };
493 }
494
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000495 if (!Config.KeepSection.empty()) {
Fangrui Songe9f34b02018-11-12 23:46:22 +0000496 RemovePred = [&Config, RemovePred](const SectionBase &Sec) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000497 // Explicitly keep these sections regardless of previous removes.
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000498 if (is_contained(Config.KeepSection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000499 return false;
500 // Otherwise defer to RemovePred.
501 return RemovePred(Sec);
502 };
503 }
504
505 // This has to be the last predicate assignment.
506 // If the option --keep-symbol has been specified
507 // and at least one of those symbols is present
508 // (equivalently, the updated symbol table is not empty)
509 // the symbol table and the string table should not be removed.
510 if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) &&
511 Obj.SymbolTable && !Obj.SymbolTable->empty()) {
512 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
513 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
514 return false;
515 return RemovePred(Sec);
516 };
517 }
518
519 if (Config.CompressionType != DebugCompressionType::None)
Fangrui Song3dfc3fb2019-03-15 10:27:28 +0000520 replaceDebugSections(Obj, RemovePred, isCompressable,
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000521 [&Config, &Obj](const SectionBase *S) {
522 return &Obj.addSection<CompressedSection>(
523 *S, Config.CompressionType);
524 });
525 else if (Config.DecompressDebugSections)
526 replaceDebugSections(
Fangrui Song3dfc3fb2019-03-15 10:27:28 +0000527 Obj, RemovePred,
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000528 [](const SectionBase &S) { return isa<CompressedSection>(&S); },
529 [&Obj](const SectionBase *S) {
530 auto CS = cast<CompressedSection>(S);
531 return &Obj.addSection<DecompressedSection>(*CS);
532 });
533
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000534 if (Error E = Obj.removeSections(RemovePred))
535 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000536
537 if (!Config.SectionsToRename.empty()) {
538 for (auto &Sec : Obj.sections()) {
539 const auto Iter = Config.SectionsToRename.find(Sec.Name);
540 if (Iter != Config.SectionsToRename.end()) {
541 const SectionRename &SR = Iter->second;
542 Sec.Name = SR.NewName;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000543 if (SR.NewFlags.hasValue())
544 Sec.Flags =
545 setSectionFlagsPreserveMask(Sec.Flags, SR.NewFlags.getValue());
546 }
547 }
548 }
549
550 if (!Config.SetSectionFlags.empty()) {
551 for (auto &Sec : Obj.sections()) {
552 const auto Iter = Config.SetSectionFlags.find(Sec.Name);
553 if (Iter != Config.SetSectionFlags.end()) {
554 const SectionFlagsUpdate &SFU = Iter->second;
555 Sec.Flags = setSectionFlagsPreserveMask(Sec.Flags, SFU.NewFlags);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000556 }
557 }
558 }
Eugene Leviantc76671b2019-03-12 12:41:06 +0000559
560 for (const auto &Flag : Config.AddSection) {
561 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
562 StringRef SecName = SecPair.first;
563 StringRef File = SecPair.second;
564 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
565 MemoryBuffer::getFile(File);
566 if (!BufOrErr)
567 return createFileError(File, errorCodeToError(BufOrErr.getError()));
568 std::unique_ptr<MemoryBuffer> Buf = std::move(*BufOrErr);
569 ArrayRef<uint8_t> Data(
570 reinterpret_cast<const uint8_t *>(Buf->getBufferStart()),
571 Buf->getBufferSize());
572 OwnedDataSection &NewSection =
573 Obj.addSection<OwnedDataSection>(SecName, Data);
574 if (SecName.startswith(".note") && SecName != ".note.GNU-stack")
575 NewSection.Type = SHT_NOTE;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000576 }
577
Eugene Leviantc76671b2019-03-12 12:41:06 +0000578 for (const auto &Flag : Config.DumpSection) {
579 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
580 StringRef SecName = SecPair.first;
581 StringRef File = SecPair.second;
582 if (Error E = dumpSectionToFile(SecName, File, Obj))
583 return createFileError(Config.InputFilename, std::move(E));
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000584 }
585
586 if (!Config.AddGnuDebugLink.empty())
587 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000588
Eugene Leviant51c1f642019-02-25 14:12:41 +0000589 for (const NewSymbolInfo &SI : Config.SymbolsToAdd) {
590 SectionBase *Sec = Obj.findSection(SI.SectionName);
591 uint64_t Value = Sec ? Sec->Addr + SI.Value : SI.Value;
Simon Pilgrim65706cf2019-02-27 10:19:53 +0000592 Obj.SymbolTable->addSymbol(
593 SI.SymbolName, SI.Bind, SI.Type, Sec, Value, SI.Visibility,
594 Sec ? (uint16_t)SYMBOL_SIMPLE_INDEX : (uint16_t)SHN_ABS, 0);
Eugene Leviant51c1f642019-02-25 14:12:41 +0000595 }
596
Eugene Leviant53350d02019-02-26 09:24:22 +0000597 if (Config.EntryExpr)
598 Obj.Entry = Config.EntryExpr(Obj.Entry);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000599 return Error::success();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000600}
601
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000602Error executeObjcopyOnRawBinary(const CopyConfig &Config, MemoryBuffer &In,
603 Buffer &Out) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000604 BinaryReader Reader(Config.BinaryArch, &In);
605 std::unique_ptr<Object> Obj = Reader.create();
606
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000607 // Prefer OutputArch (-O<format>) if set, otherwise fallback to BinaryArch
608 // (-B<arch>).
609 const ElfType OutputElfType = getOutputElfType(
610 Config.OutputArch ? Config.OutputArch.getValue() : Config.BinaryArch);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000611 if (Error E = handleArgs(Config, *Obj, Reader, OutputElfType))
612 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000613 std::unique_ptr<Writer> Writer =
614 createWriter(Config, *Obj, Out, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000615 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000616 return E;
617 return Writer->write();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000618}
619
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000620Error executeObjcopyOnBinary(const CopyConfig &Config,
621 object::ELFObjectFileBase &In, Buffer &Out) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000622 ELFReader Reader(&In);
623 std::unique_ptr<Object> Obj = Reader.create();
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000624 // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
625 const ElfType OutputElfType =
626 Config.OutputArch ? getOutputElfType(Config.OutputArch.getValue())
627 : getOutputElfType(In);
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000628 ArrayRef<uint8_t> BuildIdBytes;
629
630 if (!Config.BuildIdLinkDir.empty()) {
631 BuildIdBytes = unwrapOrError(findBuildID(In));
632 if (BuildIdBytes.size() < 2)
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000633 return createFileError(
634 Config.InputFilename,
635 createStringError(object_error::parse_failed,
636 "build ID is smaller than two bytes."));
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000637 }
638
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000639 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkInput)
640 if (Error E =
641 linkToBuildIdDir(Config, Config.InputFilename,
642 Config.BuildIdLinkInput.getValue(), BuildIdBytes))
643 return E;
644
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;
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000651 if (Error E = Writer->write())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000652 return E;
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000653 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkOutput)
654 if (Error E =
655 linkToBuildIdDir(Config, Config.OutputFilename,
656 Config.BuildIdLinkOutput.getValue(), BuildIdBytes))
657 return E;
658
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000659 return Error::success();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000660}
661
662} // end namespace elf
663} // end namespace objcopy
664} // end namespace llvm