blob: cbdad77cda78966fd06a15874090b974d7944722 [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
160static void linkToBuildIdDir(const CopyConfig &Config, StringRef ToLink,
161 StringRef Suffix, ArrayRef<uint8_t> BuildIdBytes) {
162 SmallString<128> Path = Config.BuildIdLinkDir;
163 sys::path::append(Path, llvm::toHex(BuildIdBytes[0], /*LowerCase*/ true));
164 if (auto EC = sys::fs::create_directories(Path))
165 error("cannot create build ID link directory " + Path + ": " +
166 EC.message());
167
168 sys::path::append(Path,
169 llvm::toHex(BuildIdBytes.slice(1), /*LowerCase*/ true));
170 Path += Suffix;
171 if (auto EC = sys::fs::create_hard_link(ToLink, Path)) {
172 // Hard linking failed, try to remove the file first if it exists.
173 if (sys::fs::exists(Path))
174 sys::fs::remove(Path);
175 EC = sys::fs::create_hard_link(ToLink, Path);
176 if (EC)
177 error("cannot link " + ToLink + " to " + Path + ": " + EC.message());
178 }
179}
180
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000181static Error splitDWOToFile(const CopyConfig &Config, const Reader &Reader,
182 StringRef File, ElfType OutputElfType) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000183 auto DWOFile = Reader.create();
184 DWOFile->removeSections(
185 [&](const SectionBase &Sec) { return onlyKeepDWOPred(*DWOFile, Sec); });
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000186 if (Config.OutputArch)
187 DWOFile->Machine = Config.OutputArch.getValue().EMachine;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000188 FileBuffer FB(File);
189 auto Writer = createWriter(Config, *DWOFile, FB, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000190 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000191 return E;
192 return Writer->write();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000193}
194
195static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
196 Object &Obj) {
197 for (auto &Sec : Obj.sections()) {
198 if (Sec.Name == SecName) {
Jordan Rupprecht16a0de22018-12-20 00:57:06 +0000199 if (Sec.OriginalData.empty())
Martin Storsjo8010c6be2019-01-22 10:57:59 +0000200 return createStringError(
201 object_error::parse_failed,
202 "Can't dump section \"%s\": it has no contents",
203 SecName.str().c_str());
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000204 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
205 FileOutputBuffer::create(Filename, Sec.OriginalData.size());
206 if (!BufferOrErr)
207 return BufferOrErr.takeError();
208 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
209 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(),
210 Buf->getBufferStart());
211 if (Error E = Buf->commit())
212 return E;
213 return Error::success();
214 }
215 }
Martin Storsjo8010c6be2019-01-22 10:57:59 +0000216 return createStringError(object_error::parse_failed, "Section not found");
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000217}
218
219static bool isCompressed(const SectionBase &Section) {
220 const char *Magic = "ZLIB";
221 return StringRef(Section.Name).startswith(".zdebug") ||
222 (Section.OriginalData.size() > strlen(Magic) &&
223 !strncmp(reinterpret_cast<const char *>(Section.OriginalData.data()),
224 Magic, strlen(Magic))) ||
225 (Section.Flags & ELF::SHF_COMPRESSED);
226}
227
228static bool isCompressable(const SectionBase &Section) {
229 return !isCompressed(Section) && isDebugSection(Section) &&
230 Section.Name != ".gdb_index";
231}
232
233static void replaceDebugSections(
234 const CopyConfig &Config, Object &Obj, SectionPred &RemovePred,
235 function_ref<bool(const SectionBase &)> shouldReplace,
236 function_ref<SectionBase *(const SectionBase *)> addSection) {
237 SmallVector<SectionBase *, 13> ToReplace;
238 SmallVector<RelocationSection *, 13> RelocationSections;
239 for (auto &Sec : Obj.sections()) {
240 if (RelocationSection *R = dyn_cast<RelocationSection>(&Sec)) {
241 if (shouldReplace(*R->getSection()))
242 RelocationSections.push_back(R);
243 continue;
244 }
245
246 if (shouldReplace(Sec))
247 ToReplace.push_back(&Sec);
248 }
249
250 for (SectionBase *S : ToReplace) {
251 SectionBase *NewSection = addSection(S);
252
253 for (RelocationSection *RS : RelocationSections) {
254 if (RS->getSection() == S)
255 RS->setSection(NewSection);
256 }
257 }
258
259 RemovePred = [shouldReplace, RemovePred](const SectionBase &Sec) {
260 return shouldReplace(Sec) || RemovePred(Sec);
261 };
262}
263
264// This function handles the high level operations of GNU objcopy including
265// handling command line options. It's important to outline certain properties
266// we expect to hold of the command line operations. Any operation that "keeps"
267// should keep regardless of a remove. Additionally any removal should respect
268// any previous removals. Lastly whether or not something is removed shouldn't
269// depend a) on the order the options occur in or b) on some opaque priority
270// system. The only priority is that keeps/copies overrule removes.
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000271static Error handleArgs(const CopyConfig &Config, Object &Obj,
272 const Reader &Reader, ElfType OutputElfType) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000273
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000274 if (!Config.SplitDWO.empty())
275 if (Error E =
276 splitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType))
277 return E;
278
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000279 if (Config.OutputArch)
280 Obj.Machine = Config.OutputArch.getValue().EMachine;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000281
282 // TODO: update or remove symbols only if there is an option that affects
283 // them.
284 if (Obj.SymbolTable) {
285 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
Jordan Rupprechtb47475c2018-11-01 17:26:36 +0000286 if (!Sym.isCommon() &&
287 ((Config.LocalizeHidden &&
288 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
Fangrui Songe4ee0662018-11-29 17:32:51 +0000289 is_contained(Config.SymbolsToLocalize, Sym.Name)))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000290 Sym.Binding = STB_LOCAL;
291
292 // Note: these two globalize flags have very similar names but different
293 // meanings:
294 //
295 // --globalize-symbol: promote a symbol to global
296 // --keep-global-symbol: all symbols except for these should be made local
297 //
298 // If --globalize-symbol is specified for a given symbol, it will be
299 // global in the output file even if it is not included via
300 // --keep-global-symbol. Because of that, make sure to check
301 // --globalize-symbol second.
302 if (!Config.SymbolsToKeepGlobal.empty() &&
Jordan Rupprecht634820d2018-10-30 16:23:38 +0000303 !is_contained(Config.SymbolsToKeepGlobal, Sym.Name) &&
304 Sym.getShndx() != SHN_UNDEF)
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000305 Sym.Binding = STB_LOCAL;
306
Fangrui Songe4ee0662018-11-29 17:32:51 +0000307 if (is_contained(Config.SymbolsToGlobalize, Sym.Name) &&
Jordan Rupprecht634820d2018-10-30 16:23:38 +0000308 Sym.getShndx() != SHN_UNDEF)
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000309 Sym.Binding = STB_GLOBAL;
310
Fangrui Songe4ee0662018-11-29 17:32:51 +0000311 if (is_contained(Config.SymbolsToWeaken, Sym.Name) &&
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000312 Sym.Binding == STB_GLOBAL)
313 Sym.Binding = STB_WEAK;
314
315 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
316 Sym.getShndx() != SHN_UNDEF)
317 Sym.Binding = STB_WEAK;
318
319 const auto I = Config.SymbolsToRename.find(Sym.Name);
320 if (I != Config.SymbolsToRename.end())
321 Sym.Name = I->getValue();
322
323 if (!Config.SymbolsPrefix.empty() && Sym.Type != STT_SECTION)
324 Sym.Name = (Config.SymbolsPrefix + Sym.Name).str();
325 });
326
327 // The purpose of this loop is to mark symbols referenced by sections
328 // (like GroupSection or RelocationSection). This way, we know which
329 // symbols are still 'needed' and which are not.
330 if (Config.StripUnneeded) {
331 for (auto &Section : Obj.sections())
332 Section.markSymbols();
333 }
334
335 Obj.removeSymbols([&](const Symbol &Sym) {
Fangrui Songe4ee0662018-11-29 17:32:51 +0000336 if (is_contained(Config.SymbolsToKeep, Sym.Name) ||
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000337 (Config.KeepFileSymbols && Sym.Type == STT_FILE))
338 return false;
339
Jordan Rupprechtd0f7bcf2019-01-30 14:58:13 +0000340 if ((Config.DiscardMode == DiscardType::All ||
341 (Config.DiscardMode == DiscardType::Locals &&
342 StringRef(Sym.Name).startswith(".L"))) &&
343 Sym.Binding == STB_LOCAL && Sym.getShndx() != SHN_UNDEF &&
344 Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000345 return true;
346
347 if (Config.StripAll || Config.StripAllGNU)
348 return true;
349
Fangrui Songe4ee0662018-11-29 17:32:51 +0000350 if (is_contained(Config.SymbolsToRemove, Sym.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000351 return true;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000352
353 if (Config.StripUnneeded && !Sym.Referenced &&
354 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
355 Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
356 return true;
357
358 return false;
359 });
360 }
361
362 SectionPred RemovePred = [](const SectionBase &) { return false; };
363
364 // Removes:
365 if (!Config.ToRemove.empty()) {
366 RemovePred = [&Config](const SectionBase &Sec) {
367 return is_contained(Config.ToRemove, Sec.Name);
368 };
369 }
370
371 if (Config.StripDWO || !Config.SplitDWO.empty())
372 RemovePred = [RemovePred](const SectionBase &Sec) {
373 return isDWOSection(Sec) || RemovePred(Sec);
374 };
375
376 if (Config.ExtractDWO)
377 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
378 return onlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
379 };
380
381 if (Config.StripAllGNU)
382 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
383 if (RemovePred(Sec))
384 return true;
385 if ((Sec.Flags & SHF_ALLOC) != 0)
386 return false;
387 if (&Sec == Obj.SectionNames)
388 return false;
389 switch (Sec.Type) {
390 case SHT_SYMTAB:
391 case SHT_REL:
392 case SHT_RELA:
393 case SHT_STRTAB:
394 return true;
395 }
396 return isDebugSection(Sec);
397 };
398
399 if (Config.StripSections) {
400 RemovePred = [RemovePred](const SectionBase &Sec) {
401 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
402 };
403 }
404
405 if (Config.StripDebug) {
406 RemovePred = [RemovePred](const SectionBase &Sec) {
407 return RemovePred(Sec) || isDebugSection(Sec);
408 };
409 }
410
411 if (Config.StripNonAlloc)
412 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
413 if (RemovePred(Sec))
414 return true;
415 if (&Sec == Obj.SectionNames)
416 return false;
417 return (Sec.Flags & SHF_ALLOC) == 0;
418 };
419
420 if (Config.StripAll)
421 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
422 if (RemovePred(Sec))
423 return true;
424 if (&Sec == Obj.SectionNames)
425 return false;
426 if (StringRef(Sec.Name).startswith(".gnu.warning"))
427 return false;
428 return (Sec.Flags & SHF_ALLOC) == 0;
429 };
430
431 // Explicit copies:
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000432 if (!Config.OnlySection.empty()) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000433 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
434 // Explicitly keep these sections regardless of previous removes.
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000435 if (is_contained(Config.OnlySection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000436 return false;
437
438 // Allow all implicit removes.
439 if (RemovePred(Sec))
440 return true;
441
442 // Keep special sections.
443 if (Obj.SectionNames == &Sec)
444 return false;
445 if (Obj.SymbolTable == &Sec ||
446 (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
447 return false;
448
449 // Remove everything else.
450 return true;
451 };
452 }
453
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000454 if (!Config.KeepSection.empty()) {
Fangrui Songe9f34b02018-11-12 23:46:22 +0000455 RemovePred = [&Config, RemovePred](const SectionBase &Sec) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000456 // Explicitly keep these sections regardless of previous removes.
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000457 if (is_contained(Config.KeepSection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000458 return false;
459 // Otherwise defer to RemovePred.
460 return RemovePred(Sec);
461 };
462 }
463
464 // This has to be the last predicate assignment.
465 // If the option --keep-symbol has been specified
466 // and at least one of those symbols is present
467 // (equivalently, the updated symbol table is not empty)
468 // the symbol table and the string table should not be removed.
469 if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) &&
470 Obj.SymbolTable && !Obj.SymbolTable->empty()) {
471 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
472 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
473 return false;
474 return RemovePred(Sec);
475 };
476 }
477
478 if (Config.CompressionType != DebugCompressionType::None)
479 replaceDebugSections(Config, Obj, RemovePred, isCompressable,
480 [&Config, &Obj](const SectionBase *S) {
481 return &Obj.addSection<CompressedSection>(
482 *S, Config.CompressionType);
483 });
484 else if (Config.DecompressDebugSections)
485 replaceDebugSections(
486 Config, Obj, RemovePred,
487 [](const SectionBase &S) { return isa<CompressedSection>(&S); },
488 [&Obj](const SectionBase *S) {
489 auto CS = cast<CompressedSection>(S);
490 return &Obj.addSection<DecompressedSection>(*CS);
491 });
492
493 Obj.removeSections(RemovePred);
494
495 if (!Config.SectionsToRename.empty()) {
496 for (auto &Sec : Obj.sections()) {
497 const auto Iter = Config.SectionsToRename.find(Sec.Name);
498 if (Iter != Config.SectionsToRename.end()) {
499 const SectionRename &SR = Iter->second;
500 Sec.Name = SR.NewName;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000501 if (SR.NewFlags.hasValue())
502 Sec.Flags =
503 setSectionFlagsPreserveMask(Sec.Flags, SR.NewFlags.getValue());
504 }
505 }
506 }
507
508 if (!Config.SetSectionFlags.empty()) {
509 for (auto &Sec : Obj.sections()) {
510 const auto Iter = Config.SetSectionFlags.find(Sec.Name);
511 if (Iter != Config.SetSectionFlags.end()) {
512 const SectionFlagsUpdate &SFU = Iter->second;
513 Sec.Flags = setSectionFlagsPreserveMask(Sec.Flags, SFU.NewFlags);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000514 }
515 }
516 }
517
518 if (!Config.AddSection.empty()) {
519 for (const auto &Flag : Config.AddSection) {
Jordan Rupprecht17dd4a22019-01-15 16:57:23 +0000520 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
521 StringRef SecName = SecPair.first;
522 StringRef File = SecPair.second;
523 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
524 MemoryBuffer::getFile(File);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000525 if (!BufOrErr)
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000526 return createFileError(File, errorCodeToError(BufOrErr.getError()));
Jordan Rupprecht17dd4a22019-01-15 16:57:23 +0000527 std::unique_ptr<MemoryBuffer> Buf = std::move(*BufOrErr);
528 ArrayRef<uint8_t> Data(
529 reinterpret_cast<const uint8_t *>(Buf->getBufferStart()),
530 Buf->getBufferSize());
531 OwnedDataSection &NewSection =
532 Obj.addSection<OwnedDataSection>(SecName, Data);
533 if (SecName.startswith(".note") && SecName != ".note.GNU-stack")
534 NewSection.Type = SHT_NOTE;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000535 }
536 }
537
538 if (!Config.DumpSection.empty()) {
539 for (const auto &Flag : Config.DumpSection) {
540 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
541 StringRef SecName = SecPair.first;
542 StringRef File = SecPair.second;
543 if (Error E = dumpSectionToFile(SecName, File, Obj))
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000544 return createFileError(Config.InputFilename, std::move(E));
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000545 }
546 }
547
548 if (!Config.AddGnuDebugLink.empty())
549 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000550
551 return Error::success();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000552}
553
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000554Error executeObjcopyOnRawBinary(const CopyConfig &Config, MemoryBuffer &In,
555 Buffer &Out) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000556 BinaryReader Reader(Config.BinaryArch, &In);
557 std::unique_ptr<Object> Obj = Reader.create();
558
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000559 // Prefer OutputArch (-O<format>) if set, otherwise fallback to BinaryArch
560 // (-B<arch>).
561 const ElfType OutputElfType = getOutputElfType(
562 Config.OutputArch ? Config.OutputArch.getValue() : Config.BinaryArch);
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000563 if (Error E = handleArgs(Config, *Obj, Reader, OutputElfType))
564 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000565 std::unique_ptr<Writer> Writer =
566 createWriter(Config, *Obj, Out, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000567 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000568 return E;
569 return Writer->write();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000570}
571
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000572Error executeObjcopyOnBinary(const CopyConfig &Config,
573 object::ELFObjectFileBase &In, Buffer &Out) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000574 ELFReader Reader(&In);
575 std::unique_ptr<Object> Obj = Reader.create();
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000576 // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
577 const ElfType OutputElfType =
578 Config.OutputArch ? getOutputElfType(Config.OutputArch.getValue())
579 : getOutputElfType(In);
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000580 ArrayRef<uint8_t> BuildIdBytes;
581
582 if (!Config.BuildIdLinkDir.empty()) {
583 BuildIdBytes = unwrapOrError(findBuildID(In));
584 if (BuildIdBytes.size() < 2)
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000585 return createFileError(
586 Config.InputFilename,
587 createStringError(object_error::parse_failed,
588 "build ID is smaller than two bytes."));
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000589 }
590
591 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkInput) {
592 linkToBuildIdDir(Config, Config.InputFilename,
593 Config.BuildIdLinkInput.getValue(), BuildIdBytes);
594 }
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000595 if (Error E = handleArgs(Config, *Obj, Reader, OutputElfType))
596 return E;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000597 std::unique_ptr<Writer> Writer =
598 createWriter(Config, *Obj, Out, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000599 if (Error E = Writer->finalize())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000600 return E;
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000601 if (Error E = Writer->write())
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000602 return E;
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000603 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkOutput) {
604 linkToBuildIdDir(Config, Config.OutputFilename,
605 Config.BuildIdLinkOutput.getValue(), BuildIdBytes);
606 }
Jordan Rupprecht307deab2019-01-30 14:36:53 +0000607 return Error::success();
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000608}
609
610} // end namespace elf
611} // end namespace objcopy
612} // end namespace llvm