blob: 925999630e6d3afa21a3f6f28a08652d18a2609a [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
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000181static void splitDWOToFile(const CopyConfig &Config, const Reader &Reader,
182 StringRef File, ElfType OutputElfType) {
183 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())
191 error(std::move(E));
192 if (Error E = Writer->write())
193 error(std::move(E));
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000194}
195
196static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
197 Object &Obj) {
198 for (auto &Sec : Obj.sections()) {
199 if (Sec.Name == SecName) {
Jordan Rupprecht16a0de22018-12-20 00:57:06 +0000200 if (Sec.OriginalData.empty())
Martin Storsjo8010c6be2019-01-22 10:57:59 +0000201 return createStringError(
202 object_error::parse_failed,
203 "Can't dump section \"%s\": it has no contents",
204 SecName.str().c_str());
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000205 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
206 FileOutputBuffer::create(Filename, Sec.OriginalData.size());
207 if (!BufferOrErr)
208 return BufferOrErr.takeError();
209 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
210 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(),
211 Buf->getBufferStart());
212 if (Error E = Buf->commit())
213 return E;
214 return Error::success();
215 }
216 }
Martin Storsjo8010c6be2019-01-22 10:57:59 +0000217 return createStringError(object_error::parse_failed, "Section not found");
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000218}
219
220static bool isCompressed(const SectionBase &Section) {
221 const char *Magic = "ZLIB";
222 return StringRef(Section.Name).startswith(".zdebug") ||
223 (Section.OriginalData.size() > strlen(Magic) &&
224 !strncmp(reinterpret_cast<const char *>(Section.OriginalData.data()),
225 Magic, strlen(Magic))) ||
226 (Section.Flags & ELF::SHF_COMPRESSED);
227}
228
229static bool isCompressable(const SectionBase &Section) {
230 return !isCompressed(Section) && isDebugSection(Section) &&
231 Section.Name != ".gdb_index";
232}
233
234static void replaceDebugSections(
235 const CopyConfig &Config, Object &Obj, SectionPred &RemovePred,
236 function_ref<bool(const SectionBase &)> shouldReplace,
237 function_ref<SectionBase *(const SectionBase *)> addSection) {
238 SmallVector<SectionBase *, 13> ToReplace;
239 SmallVector<RelocationSection *, 13> RelocationSections;
240 for (auto &Sec : Obj.sections()) {
241 if (RelocationSection *R = dyn_cast<RelocationSection>(&Sec)) {
242 if (shouldReplace(*R->getSection()))
243 RelocationSections.push_back(R);
244 continue;
245 }
246
247 if (shouldReplace(Sec))
248 ToReplace.push_back(&Sec);
249 }
250
251 for (SectionBase *S : ToReplace) {
252 SectionBase *NewSection = addSection(S);
253
254 for (RelocationSection *RS : RelocationSections) {
255 if (RS->getSection() == S)
256 RS->setSection(NewSection);
257 }
258 }
259
260 RemovePred = [shouldReplace, RemovePred](const SectionBase &Sec) {
261 return shouldReplace(Sec) || RemovePred(Sec);
262 };
263}
264
265// This function handles the high level operations of GNU objcopy including
266// handling command line options. It's important to outline certain properties
267// we expect to hold of the command line operations. Any operation that "keeps"
268// should keep regardless of a remove. Additionally any removal should respect
269// any previous removals. Lastly whether or not something is removed shouldn't
270// depend a) on the order the options occur in or b) on some opaque priority
271// system. The only priority is that keeps/copies overrule removes.
272static void handleArgs(const CopyConfig &Config, Object &Obj,
273 const Reader &Reader, ElfType OutputElfType) {
274
275 if (!Config.SplitDWO.empty()) {
276 splitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType);
277 }
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000278 if (Config.OutputArch)
279 Obj.Machine = Config.OutputArch.getValue().EMachine;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000280
281 // TODO: update or remove symbols only if there is an option that affects
282 // them.
283 if (Obj.SymbolTable) {
284 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
Jordan Rupprechtb47475c2018-11-01 17:26:36 +0000285 if (!Sym.isCommon() &&
286 ((Config.LocalizeHidden &&
287 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
Fangrui Songe4ee0662018-11-29 17:32:51 +0000288 is_contained(Config.SymbolsToLocalize, Sym.Name)))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000289 Sym.Binding = STB_LOCAL;
290
291 // Note: these two globalize flags have very similar names but different
292 // meanings:
293 //
294 // --globalize-symbol: promote a symbol to global
295 // --keep-global-symbol: all symbols except for these should be made local
296 //
297 // If --globalize-symbol is specified for a given symbol, it will be
298 // global in the output file even if it is not included via
299 // --keep-global-symbol. Because of that, make sure to check
300 // --globalize-symbol second.
301 if (!Config.SymbolsToKeepGlobal.empty() &&
Jordan Rupprecht634820d2018-10-30 16:23:38 +0000302 !is_contained(Config.SymbolsToKeepGlobal, Sym.Name) &&
303 Sym.getShndx() != SHN_UNDEF)
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000304 Sym.Binding = STB_LOCAL;
305
Fangrui Songe4ee0662018-11-29 17:32:51 +0000306 if (is_contained(Config.SymbolsToGlobalize, Sym.Name) &&
Jordan Rupprecht634820d2018-10-30 16:23:38 +0000307 Sym.getShndx() != SHN_UNDEF)
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000308 Sym.Binding = STB_GLOBAL;
309
Fangrui Songe4ee0662018-11-29 17:32:51 +0000310 if (is_contained(Config.SymbolsToWeaken, Sym.Name) &&
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000311 Sym.Binding == STB_GLOBAL)
312 Sym.Binding = STB_WEAK;
313
314 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
315 Sym.getShndx() != SHN_UNDEF)
316 Sym.Binding = STB_WEAK;
317
318 const auto I = Config.SymbolsToRename.find(Sym.Name);
319 if (I != Config.SymbolsToRename.end())
320 Sym.Name = I->getValue();
321
322 if (!Config.SymbolsPrefix.empty() && Sym.Type != STT_SECTION)
323 Sym.Name = (Config.SymbolsPrefix + Sym.Name).str();
324 });
325
326 // The purpose of this loop is to mark symbols referenced by sections
327 // (like GroupSection or RelocationSection). This way, we know which
328 // symbols are still 'needed' and which are not.
329 if (Config.StripUnneeded) {
330 for (auto &Section : Obj.sections())
331 Section.markSymbols();
332 }
333
334 Obj.removeSymbols([&](const Symbol &Sym) {
Fangrui Songe4ee0662018-11-29 17:32:51 +0000335 if (is_contained(Config.SymbolsToKeep, Sym.Name) ||
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000336 (Config.KeepFileSymbols && Sym.Type == STT_FILE))
337 return false;
338
339 if (Config.DiscardAll && Sym.Binding == STB_LOCAL &&
340 Sym.getShndx() != SHN_UNDEF && Sym.Type != STT_FILE &&
341 Sym.Type != STT_SECTION)
342 return true;
343
344 if (Config.StripAll || Config.StripAllGNU)
345 return true;
346
Fangrui Songe4ee0662018-11-29 17:32:51 +0000347 if (is_contained(Config.SymbolsToRemove, Sym.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000348 return true;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000349
350 if (Config.StripUnneeded && !Sym.Referenced &&
351 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
352 Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
353 return true;
354
355 return false;
356 });
357 }
358
359 SectionPred RemovePred = [](const SectionBase &) { return false; };
360
361 // Removes:
362 if (!Config.ToRemove.empty()) {
363 RemovePred = [&Config](const SectionBase &Sec) {
364 return is_contained(Config.ToRemove, Sec.Name);
365 };
366 }
367
368 if (Config.StripDWO || !Config.SplitDWO.empty())
369 RemovePred = [RemovePred](const SectionBase &Sec) {
370 return isDWOSection(Sec) || RemovePred(Sec);
371 };
372
373 if (Config.ExtractDWO)
374 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
375 return onlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
376 };
377
378 if (Config.StripAllGNU)
379 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
380 if (RemovePred(Sec))
381 return true;
382 if ((Sec.Flags & SHF_ALLOC) != 0)
383 return false;
384 if (&Sec == Obj.SectionNames)
385 return false;
386 switch (Sec.Type) {
387 case SHT_SYMTAB:
388 case SHT_REL:
389 case SHT_RELA:
390 case SHT_STRTAB:
391 return true;
392 }
393 return isDebugSection(Sec);
394 };
395
396 if (Config.StripSections) {
397 RemovePred = [RemovePred](const SectionBase &Sec) {
398 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
399 };
400 }
401
402 if (Config.StripDebug) {
403 RemovePred = [RemovePred](const SectionBase &Sec) {
404 return RemovePred(Sec) || isDebugSection(Sec);
405 };
406 }
407
408 if (Config.StripNonAlloc)
409 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
410 if (RemovePred(Sec))
411 return true;
412 if (&Sec == Obj.SectionNames)
413 return false;
414 return (Sec.Flags & SHF_ALLOC) == 0;
415 };
416
417 if (Config.StripAll)
418 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
419 if (RemovePred(Sec))
420 return true;
421 if (&Sec == Obj.SectionNames)
422 return false;
423 if (StringRef(Sec.Name).startswith(".gnu.warning"))
424 return false;
425 return (Sec.Flags & SHF_ALLOC) == 0;
426 };
427
428 // Explicit copies:
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000429 if (!Config.OnlySection.empty()) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000430 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
431 // Explicitly keep these sections regardless of previous removes.
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000432 if (is_contained(Config.OnlySection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000433 return false;
434
435 // Allow all implicit removes.
436 if (RemovePred(Sec))
437 return true;
438
439 // Keep special sections.
440 if (Obj.SectionNames == &Sec)
441 return false;
442 if (Obj.SymbolTable == &Sec ||
443 (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
444 return false;
445
446 // Remove everything else.
447 return true;
448 };
449 }
450
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000451 if (!Config.KeepSection.empty()) {
Fangrui Songe9f34b02018-11-12 23:46:22 +0000452 RemovePred = [&Config, RemovePred](const SectionBase &Sec) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000453 // Explicitly keep these sections regardless of previous removes.
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000454 if (is_contained(Config.KeepSection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000455 return false;
456 // Otherwise defer to RemovePred.
457 return RemovePred(Sec);
458 };
459 }
460
461 // This has to be the last predicate assignment.
462 // If the option --keep-symbol has been specified
463 // and at least one of those symbols is present
464 // (equivalently, the updated symbol table is not empty)
465 // the symbol table and the string table should not be removed.
466 if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) &&
467 Obj.SymbolTable && !Obj.SymbolTable->empty()) {
468 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
469 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
470 return false;
471 return RemovePred(Sec);
472 };
473 }
474
475 if (Config.CompressionType != DebugCompressionType::None)
476 replaceDebugSections(Config, Obj, RemovePred, isCompressable,
477 [&Config, &Obj](const SectionBase *S) {
478 return &Obj.addSection<CompressedSection>(
479 *S, Config.CompressionType);
480 });
481 else if (Config.DecompressDebugSections)
482 replaceDebugSections(
483 Config, Obj, RemovePred,
484 [](const SectionBase &S) { return isa<CompressedSection>(&S); },
485 [&Obj](const SectionBase *S) {
486 auto CS = cast<CompressedSection>(S);
487 return &Obj.addSection<DecompressedSection>(*CS);
488 });
489
490 Obj.removeSections(RemovePred);
491
492 if (!Config.SectionsToRename.empty()) {
493 for (auto &Sec : Obj.sections()) {
494 const auto Iter = Config.SectionsToRename.find(Sec.Name);
495 if (Iter != Config.SectionsToRename.end()) {
496 const SectionRename &SR = Iter->second;
497 Sec.Name = SR.NewName;
Jordan Rupprechtc8927412019-01-29 15:05:38 +0000498 if (SR.NewFlags.hasValue())
499 Sec.Flags =
500 setSectionFlagsPreserveMask(Sec.Flags, SR.NewFlags.getValue());
501 }
502 }
503 }
504
505 if (!Config.SetSectionFlags.empty()) {
506 for (auto &Sec : Obj.sections()) {
507 const auto Iter = Config.SetSectionFlags.find(Sec.Name);
508 if (Iter != Config.SetSectionFlags.end()) {
509 const SectionFlagsUpdate &SFU = Iter->second;
510 Sec.Flags = setSectionFlagsPreserveMask(Sec.Flags, SFU.NewFlags);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000511 }
512 }
513 }
514
515 if (!Config.AddSection.empty()) {
516 for (const auto &Flag : Config.AddSection) {
Jordan Rupprecht17dd4a22019-01-15 16:57:23 +0000517 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
518 StringRef SecName = SecPair.first;
519 StringRef File = SecPair.second;
520 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
521 MemoryBuffer::getFile(File);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000522 if (!BufOrErr)
523 reportError(File, BufOrErr.getError());
Jordan Rupprecht17dd4a22019-01-15 16:57:23 +0000524 std::unique_ptr<MemoryBuffer> Buf = std::move(*BufOrErr);
525 ArrayRef<uint8_t> Data(
526 reinterpret_cast<const uint8_t *>(Buf->getBufferStart()),
527 Buf->getBufferSize());
528 OwnedDataSection &NewSection =
529 Obj.addSection<OwnedDataSection>(SecName, Data);
530 if (SecName.startswith(".note") && SecName != ".note.GNU-stack")
531 NewSection.Type = SHT_NOTE;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000532 }
533 }
534
535 if (!Config.DumpSection.empty()) {
536 for (const auto &Flag : Config.DumpSection) {
537 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
538 StringRef SecName = SecPair.first;
539 StringRef File = SecPair.second;
540 if (Error E = dumpSectionToFile(SecName, File, Obj))
541 reportError(Config.InputFilename, std::move(E));
542 }
543 }
544
545 if (!Config.AddGnuDebugLink.empty())
546 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
547}
548
549void executeObjcopyOnRawBinary(const CopyConfig &Config, MemoryBuffer &In,
550 Buffer &Out) {
551 BinaryReader Reader(Config.BinaryArch, &In);
552 std::unique_ptr<Object> Obj = Reader.create();
553
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000554 // Prefer OutputArch (-O<format>) if set, otherwise fallback to BinaryArch
555 // (-B<arch>).
556 const ElfType OutputElfType = getOutputElfType(
557 Config.OutputArch ? Config.OutputArch.getValue() : Config.BinaryArch);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000558 handleArgs(Config, *Obj, Reader, OutputElfType);
559 std::unique_ptr<Writer> Writer =
560 createWriter(Config, *Obj, Out, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000561 if (Error E = Writer->finalize())
562 error(std::move(E));
563 if (Error E = Writer->write())
564 error(std::move(E));
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000565}
566
567void executeObjcopyOnBinary(const CopyConfig &Config,
568 object::ELFObjectFileBase &In, Buffer &Out) {
569 ELFReader Reader(&In);
570 std::unique_ptr<Object> Obj = Reader.create();
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000571 // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
572 const ElfType OutputElfType =
573 Config.OutputArch ? getOutputElfType(Config.OutputArch.getValue())
574 : getOutputElfType(In);
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000575 ArrayRef<uint8_t> BuildIdBytes;
576
577 if (!Config.BuildIdLinkDir.empty()) {
578 BuildIdBytes = unwrapOrError(findBuildID(In));
579 if (BuildIdBytes.size() < 2)
580 error("build ID in file '" + Config.InputFilename +
581 "' is smaller than two bytes");
582 }
583
584 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkInput) {
585 linkToBuildIdDir(Config, Config.InputFilename,
586 Config.BuildIdLinkInput.getValue(), BuildIdBytes);
587 }
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000588 handleArgs(Config, *Obj, Reader, OutputElfType);
589 std::unique_ptr<Writer> Writer =
590 createWriter(Config, *Obj, Out, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000591 if (Error E = Writer->finalize())
592 error(std::move(E));
593 if (Error E = Writer->write())
594 error(std::move(E));
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000595 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkOutput) {
596 linkToBuildIdDir(Config, Config.OutputFilename,
597 Config.BuildIdLinkOutput.getValue(), BuildIdBytes);
598 }
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000599}
600
601} // end namespace elf
602} // end namespace objcopy
603} // end namespace llvm