blob: fc34387307571cafb60e85ca080cdc43b028cce8 [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
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000160static Error linkToBuildIdDir(const CopyConfig &Config, StringRef ToLink,
161 StringRef Suffix,
162 ArrayRef<uint8_t> BuildIdBytes) {
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000163 SmallString<128> Path = Config.BuildIdLinkDir;
164 sys::path::append(Path, llvm::toHex(BuildIdBytes[0], /*LowerCase*/ true));
165 if (auto EC = sys::fs::create_directories(Path))
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000166 return createFileError(
167 Path.str(),
168 createStringError(EC, "cannot create build ID link directory"));
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000169
170 sys::path::append(Path,
171 llvm::toHex(BuildIdBytes.slice(1), /*LowerCase*/ true));
172 Path += Suffix;
173 if (auto EC = sys::fs::create_hard_link(ToLink, Path)) {
174 // Hard linking failed, try to remove the file first if it exists.
175 if (sys::fs::exists(Path))
176 sys::fs::remove(Path);
177 EC = sys::fs::create_hard_link(ToLink, Path);
178 if (EC)
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000179 return createStringError(EC, "cannot link %s to %s", ToLink.data(),
180 Path.data());
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000181 }
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000182 return Error::success();
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000183}
184
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000185static Error splitDWOToFile(const CopyConfig &Config, const Reader &Reader,
186 StringRef File, ElfType OutputElfType) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000187 auto DWOFile = Reader.create();
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000188 auto OnlyKeepDWOPred = [&DWOFile](const SectionBase &Sec) {
189 return onlyKeepDWOPred(*DWOFile, Sec);
190 };
191 if (Error E = DWOFile->removeSections(OnlyKeepDWOPred))
192 return E;
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000193 if (Config.OutputArch)
194 DWOFile->Machine = Config.OutputArch.getValue().EMachine;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000195 FileBuffer FB(File);
196 auto Writer = createWriter(Config, *DWOFile, FB, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000197 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000198 return E;
199 return Writer->write();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000200}
201
202static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
203 Object &Obj) {
204 for (auto &Sec : Obj.sections()) {
205 if (Sec.Name == SecName) {
Jordan Rupprecht16a0de22018-12-20 00:57:06 +0000206 if (Sec.OriginalData.empty())
Martin Storsjo8010c6be2019-01-22 10:57:59 +0000207 return createStringError(
208 object_error::parse_failed,
209 "Can't dump section \"%s\": it has no contents",
210 SecName.str().c_str());
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000211 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
212 FileOutputBuffer::create(Filename, Sec.OriginalData.size());
213 if (!BufferOrErr)
214 return BufferOrErr.takeError();
215 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
216 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(),
217 Buf->getBufferStart());
218 if (Error E = Buf->commit())
219 return E;
220 return Error::success();
221 }
222 }
Martin Storsjo8010c6be2019-01-22 10:57:59 +0000223 return createStringError(object_error::parse_failed, "Section not found");
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000224}
225
226static bool isCompressed(const SectionBase &Section) {
227 const char *Magic = "ZLIB";
228 return StringRef(Section.Name).startswith(".zdebug") ||
229 (Section.OriginalData.size() > strlen(Magic) &&
230 !strncmp(reinterpret_cast<const char *>(Section.OriginalData.data()),
231 Magic, strlen(Magic))) ||
232 (Section.Flags & ELF::SHF_COMPRESSED);
233}
234
235static bool isCompressable(const SectionBase &Section) {
236 return !isCompressed(Section) && isDebugSection(Section) &&
237 Section.Name != ".gdb_index";
238}
239
240static void replaceDebugSections(
241 const CopyConfig &Config, Object &Obj, SectionPred &RemovePred,
242 function_ref<bool(const SectionBase &)> shouldReplace,
243 function_ref<SectionBase *(const SectionBase *)> addSection) {
244 SmallVector<SectionBase *, 13> ToReplace;
245 SmallVector<RelocationSection *, 13> RelocationSections;
246 for (auto &Sec : Obj.sections()) {
247 if (RelocationSection *R = dyn_cast<RelocationSection>(&Sec)) {
248 if (shouldReplace(*R->getSection()))
249 RelocationSections.push_back(R);
250 continue;
251 }
252
253 if (shouldReplace(Sec))
254 ToReplace.push_back(&Sec);
255 }
256
257 for (SectionBase *S : ToReplace) {
258 SectionBase *NewSection = addSection(S);
259
260 for (RelocationSection *RS : RelocationSections) {
261 if (RS->getSection() == S)
262 RS->setSection(NewSection);
263 }
264 }
265
266 RemovePred = [shouldReplace, RemovePred](const SectionBase &Sec) {
267 return shouldReplace(Sec) || RemovePred(Sec);
268 };
269}
270
271// This function handles the high level operations of GNU objcopy including
272// handling command line options. It's important to outline certain properties
273// we expect to hold of the command line operations. Any operation that "keeps"
274// should keep regardless of a remove. Additionally any removal should respect
275// any previous removals. Lastly whether or not something is removed shouldn't
276// depend a) on the order the options occur in or b) on some opaque priority
277// system. The only priority is that keeps/copies overrule removes.
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000278static Error handleArgs(const CopyConfig &Config, Object &Obj,
279 const Reader &Reader, ElfType OutputElfType) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000280
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000281 if (!Config.SplitDWO.empty())
282 if (Error E =
283 splitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType))
284 return E;
285
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000286 if (Config.OutputArch)
287 Obj.Machine = Config.OutputArch.getValue().EMachine;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000288
289 // TODO: update or remove symbols only if there is an option that affects
290 // them.
291 if (Obj.SymbolTable) {
292 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
Jordan Rupprechtbd7735f2019-01-31 16:45:16 +0000293 // Common and undefined symbols don't make sense as local symbols, and can
294 // even cause crashes if we localize those, so skip them.
295 if (!Sym.isCommon() && Sym.getShndx() != SHN_UNDEF &&
Jordan Rupprechtb47475c2018-11-01 17:26:36 +0000296 ((Config.LocalizeHidden &&
297 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
Fangrui Songe4ee0662018-11-29 17:32:51 +0000298 is_contained(Config.SymbolsToLocalize, Sym.Name)))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000299 Sym.Binding = STB_LOCAL;
300
301 // Note: these two globalize flags have very similar names but different
302 // meanings:
303 //
304 // --globalize-symbol: promote a symbol to global
305 // --keep-global-symbol: all symbols except for these should be made local
306 //
307 // If --globalize-symbol is specified for a given symbol, it will be
308 // global in the output file even if it is not included via
309 // --keep-global-symbol. Because of that, make sure to check
310 // --globalize-symbol second.
311 if (!Config.SymbolsToKeepGlobal.empty() &&
Jordan Rupprecht634820d2018-10-30 16:23:38 +0000312 !is_contained(Config.SymbolsToKeepGlobal, Sym.Name) &&
313 Sym.getShndx() != SHN_UNDEF)
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000314 Sym.Binding = STB_LOCAL;
315
Fangrui Songe4ee0662018-11-29 17:32:51 +0000316 if (is_contained(Config.SymbolsToGlobalize, Sym.Name) &&
Jordan Rupprecht634820d2018-10-30 16:23:38 +0000317 Sym.getShndx() != SHN_UNDEF)
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000318 Sym.Binding = STB_GLOBAL;
319
Fangrui Songe4ee0662018-11-29 17:32:51 +0000320 if (is_contained(Config.SymbolsToWeaken, Sym.Name) &&
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000321 Sym.Binding == STB_GLOBAL)
322 Sym.Binding = STB_WEAK;
323
324 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
325 Sym.getShndx() != SHN_UNDEF)
326 Sym.Binding = STB_WEAK;
327
328 const auto I = Config.SymbolsToRename.find(Sym.Name);
329 if (I != Config.SymbolsToRename.end())
330 Sym.Name = I->getValue();
331
332 if (!Config.SymbolsPrefix.empty() && Sym.Type != STT_SECTION)
333 Sym.Name = (Config.SymbolsPrefix + Sym.Name).str();
334 });
335
336 // The purpose of this loop is to mark symbols referenced by sections
337 // (like GroupSection or RelocationSection). This way, we know which
338 // symbols are still 'needed' and which are not.
339 if (Config.StripUnneeded) {
340 for (auto &Section : Obj.sections())
341 Section.markSymbols();
342 }
343
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000344 auto RemoveSymbolsPred = [&](const Symbol &Sym) {
Fangrui Songe4ee0662018-11-29 17:32:51 +0000345 if (is_contained(Config.SymbolsToKeep, Sym.Name) ||
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000346 (Config.KeepFileSymbols && Sym.Type == STT_FILE))
347 return false;
348
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000349 if ((Config.DiscardMode == DiscardType::All ||
350 (Config.DiscardMode == DiscardType::Locals &&
351 StringRef(Sym.Name).startswith(".L"))) &&
352 Sym.Binding == STB_LOCAL && Sym.getShndx() != SHN_UNDEF &&
353 Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000354 return true;
355
356 if (Config.StripAll || Config.StripAllGNU)
357 return true;
358
Fangrui Songe4ee0662018-11-29 17:32:51 +0000359 if (is_contained(Config.SymbolsToRemove, Sym.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000360 return true;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000361
362 if (Config.StripUnneeded && !Sym.Referenced &&
363 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
364 Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
365 return true;
366
367 return false;
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000368 };
369 if (Error E = Obj.removeSymbols(RemoveSymbolsPred))
370 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000371 }
372
373 SectionPred RemovePred = [](const SectionBase &) { return false; };
374
375 // Removes:
376 if (!Config.ToRemove.empty()) {
377 RemovePred = [&Config](const SectionBase &Sec) {
378 return is_contained(Config.ToRemove, Sec.Name);
379 };
380 }
381
382 if (Config.StripDWO || !Config.SplitDWO.empty())
383 RemovePred = [RemovePred](const SectionBase &Sec) {
384 return isDWOSection(Sec) || RemovePred(Sec);
385 };
386
387 if (Config.ExtractDWO)
388 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
389 return onlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
390 };
391
392 if (Config.StripAllGNU)
393 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
394 if (RemovePred(Sec))
395 return true;
396 if ((Sec.Flags & SHF_ALLOC) != 0)
397 return false;
398 if (&Sec == Obj.SectionNames)
399 return false;
400 switch (Sec.Type) {
401 case SHT_SYMTAB:
402 case SHT_REL:
403 case SHT_RELA:
404 case SHT_STRTAB:
405 return true;
406 }
407 return isDebugSection(Sec);
408 };
409
410 if (Config.StripSections) {
411 RemovePred = [RemovePred](const SectionBase &Sec) {
412 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
413 };
414 }
415
416 if (Config.StripDebug) {
417 RemovePred = [RemovePred](const SectionBase &Sec) {
418 return RemovePred(Sec) || isDebugSection(Sec);
419 };
420 }
421
422 if (Config.StripNonAlloc)
423 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
424 if (RemovePred(Sec))
425 return true;
426 if (&Sec == Obj.SectionNames)
427 return false;
428 return (Sec.Flags & SHF_ALLOC) == 0;
429 };
430
431 if (Config.StripAll)
432 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
433 if (RemovePred(Sec))
434 return true;
435 if (&Sec == Obj.SectionNames)
436 return false;
437 if (StringRef(Sec.Name).startswith(".gnu.warning"))
438 return false;
439 return (Sec.Flags & SHF_ALLOC) == 0;
440 };
441
442 // Explicit copies:
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000443 if (!Config.OnlySection.empty()) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000444 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
445 // Explicitly keep these sections regardless of previous removes.
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000446 if (is_contained(Config.OnlySection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000447 return false;
448
449 // Allow all implicit removes.
450 if (RemovePred(Sec))
451 return true;
452
453 // Keep special sections.
454 if (Obj.SectionNames == &Sec)
455 return false;
456 if (Obj.SymbolTable == &Sec ||
457 (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
458 return false;
459
460 // Remove everything else.
461 return true;
462 };
463 }
464
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000465 if (!Config.KeepSection.empty()) {
Fangrui Songe9f34b02018-11-12 23:46:22 +0000466 RemovePred = [&Config, RemovePred](const SectionBase &Sec) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000467 // Explicitly keep these sections regardless of previous removes.
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000468 if (is_contained(Config.KeepSection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000469 return false;
470 // Otherwise defer to RemovePred.
471 return RemovePred(Sec);
472 };
473 }
474
475 // This has to be the last predicate assignment.
476 // If the option --keep-symbol has been specified
477 // and at least one of those symbols is present
478 // (equivalently, the updated symbol table is not empty)
479 // the symbol table and the string table should not be removed.
480 if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) &&
481 Obj.SymbolTable && !Obj.SymbolTable->empty()) {
482 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
483 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
484 return false;
485 return RemovePred(Sec);
486 };
487 }
488
489 if (Config.CompressionType != DebugCompressionType::None)
490 replaceDebugSections(Config, Obj, RemovePred, isCompressable,
491 [&Config, &Obj](const SectionBase *S) {
492 return &Obj.addSection<CompressedSection>(
493 *S, Config.CompressionType);
494 });
495 else if (Config.DecompressDebugSections)
496 replaceDebugSections(
497 Config, Obj, RemovePred,
498 [](const SectionBase &S) { return isa<CompressedSection>(&S); },
499 [&Obj](const SectionBase *S) {
500 auto CS = cast<CompressedSection>(S);
501 return &Obj.addSection<DecompressedSection>(*CS);
502 });
503
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000504 if (Error E = Obj.removeSections(RemovePred))
505 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000506
507 if (!Config.SectionsToRename.empty()) {
508 for (auto &Sec : Obj.sections()) {
509 const auto Iter = Config.SectionsToRename.find(Sec.Name);
510 if (Iter != Config.SectionsToRename.end()) {
511 const SectionRename &SR = Iter->second;
512 Sec.Name = SR.NewName;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000513 if (SR.NewFlags.hasValue())
514 Sec.Flags =
515 setSectionFlagsPreserveMask(Sec.Flags, SR.NewFlags.getValue());
516 }
517 }
518 }
519
520 if (!Config.SetSectionFlags.empty()) {
521 for (auto &Sec : Obj.sections()) {
522 const auto Iter = Config.SetSectionFlags.find(Sec.Name);
523 if (Iter != Config.SetSectionFlags.end()) {
524 const SectionFlagsUpdate &SFU = Iter->second;
525 Sec.Flags = setSectionFlagsPreserveMask(Sec.Flags, SFU.NewFlags);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000526 }
527 }
528 }
529
530 if (!Config.AddSection.empty()) {
531 for (const auto &Flag : Config.AddSection) {
Jordan Rupprecht17dd4a22019-01-15 16:57:23 +0000532 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
533 StringRef SecName = SecPair.first;
534 StringRef File = SecPair.second;
535 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
536 MemoryBuffer::getFile(File);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000537 if (!BufOrErr)
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000538 return createFileError(File, errorCodeToError(BufOrErr.getError()));
Jordan Rupprecht17dd4a22019-01-15 16:57:23 +0000539 std::unique_ptr<MemoryBuffer> Buf = std::move(*BufOrErr);
540 ArrayRef<uint8_t> Data(
541 reinterpret_cast<const uint8_t *>(Buf->getBufferStart()),
542 Buf->getBufferSize());
543 OwnedDataSection &NewSection =
544 Obj.addSection<OwnedDataSection>(SecName, Data);
545 if (SecName.startswith(".note") && SecName != ".note.GNU-stack")
546 NewSection.Type = SHT_NOTE;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000547 }
548 }
549
550 if (!Config.DumpSection.empty()) {
551 for (const auto &Flag : Config.DumpSection) {
552 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
553 StringRef SecName = SecPair.first;
554 StringRef File = SecPair.second;
555 if (Error E = dumpSectionToFile(SecName, File, Obj))
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000556 return createFileError(Config.InputFilename, std::move(E));
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000557 }
558 }
559
560 if (!Config.AddGnuDebugLink.empty())
561 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000562
563 return Error::success();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000564}
565
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000566Error executeObjcopyOnRawBinary(const CopyConfig &Config, MemoryBuffer &In,
567 Buffer &Out) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000568 BinaryReader Reader(Config.BinaryArch, &In);
569 std::unique_ptr<Object> Obj = Reader.create();
570
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000571 // Prefer OutputArch (-O<format>) if set, otherwise fallback to BinaryArch
572 // (-B<arch>).
573 const ElfType OutputElfType = getOutputElfType(
574 Config.OutputArch ? Config.OutputArch.getValue() : Config.BinaryArch);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000575 if (Error E = handleArgs(Config, *Obj, Reader, OutputElfType))
576 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000577 std::unique_ptr<Writer> Writer =
578 createWriter(Config, *Obj, Out, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000579 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000580 return E;
581 return Writer->write();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000582}
583
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000584Error executeObjcopyOnBinary(const CopyConfig &Config,
585 object::ELFObjectFileBase &In, Buffer &Out) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000586 ELFReader Reader(&In);
587 std::unique_ptr<Object> Obj = Reader.create();
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000588 // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
589 const ElfType OutputElfType =
590 Config.OutputArch ? getOutputElfType(Config.OutputArch.getValue())
591 : getOutputElfType(In);
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000592 ArrayRef<uint8_t> BuildIdBytes;
593
594 if (!Config.BuildIdLinkDir.empty()) {
595 BuildIdBytes = unwrapOrError(findBuildID(In));
596 if (BuildIdBytes.size() < 2)
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000597 return createFileError(
598 Config.InputFilename,
599 createStringError(object_error::parse_failed,
600 "build ID is smaller than two bytes."));
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000601 }
602
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000603 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkInput)
604 if (Error E =
605 linkToBuildIdDir(Config, Config.InputFilename,
606 Config.BuildIdLinkInput.getValue(), BuildIdBytes))
607 return E;
608
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000609 if (Error E = handleArgs(Config, *Obj, Reader, OutputElfType))
610 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000611 std::unique_ptr<Writer> Writer =
612 createWriter(Config, *Obj, Out, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000613 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000614 return E;
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000615 if (Error E = Writer->write())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000616 return E;
Jordan Rupprechtfc832e92019-01-30 18:13:30 +0000617 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkOutput)
618 if (Error E =
619 linkToBuildIdDir(Config, Config.OutputFilename,
620 Config.BuildIdLinkOutput.getValue(), BuildIdBytes))
621 return E;
622
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000623 return Error::success();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000624}
625
626} // end namespace elf
627} // end namespace objcopy
628} // end namespace llvm