blob: 2a52f1f9951ee75653b1bc5afcb99afdcc099854 [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
73static ElfType getOutputElfType(const Binary &Bin) {
74 // Infer output ELF type from the input ELF object
75 if (isa<ELFObjectFile<ELF32LE>>(Bin))
76 return ELFT_ELF32LE;
77 if (isa<ELFObjectFile<ELF64LE>>(Bin))
78 return ELFT_ELF64LE;
79 if (isa<ELFObjectFile<ELF32BE>>(Bin))
80 return ELFT_ELF32BE;
81 if (isa<ELFObjectFile<ELF64BE>>(Bin))
82 return ELFT_ELF64BE;
83 llvm_unreachable("Invalid ELFType");
84}
85
86static ElfType getOutputElfType(const MachineInfo &MI) {
87 // Infer output ELF type from the binary arch specified
88 if (MI.Is64Bit)
89 return MI.IsLittleEndian ? ELFT_ELF64LE : ELFT_ELF64BE;
90 else
91 return MI.IsLittleEndian ? ELFT_ELF32LE : ELFT_ELF32BE;
92}
93
94static std::unique_ptr<Writer> createWriter(const CopyConfig &Config,
95 Object &Obj, Buffer &Buf,
96 ElfType OutputElfType) {
97 if (Config.OutputFormat == "binary") {
98 return llvm::make_unique<BinaryWriter>(Obj, Buf);
99 }
100 // Depending on the initial ELFT and OutputFormat we need a different Writer.
101 switch (OutputElfType) {
102 case ELFT_ELF32LE:
103 return llvm::make_unique<ELFWriter<ELF32LE>>(Obj, Buf,
104 !Config.StripSections);
105 case ELFT_ELF64LE:
106 return llvm::make_unique<ELFWriter<ELF64LE>>(Obj, Buf,
107 !Config.StripSections);
108 case ELFT_ELF32BE:
109 return llvm::make_unique<ELFWriter<ELF32BE>>(Obj, Buf,
110 !Config.StripSections);
111 case ELFT_ELF64BE:
112 return llvm::make_unique<ELFWriter<ELF64BE>>(Obj, Buf,
113 !Config.StripSections);
114 }
115 llvm_unreachable("Invalid output format");
116}
117
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000118template <class ELFT>
119static Expected<ArrayRef<uint8_t>>
120findBuildID(const object::ELFFile<ELFT> &In) {
121 for (const auto &Phdr : unwrapOrError(In.program_headers())) {
122 if (Phdr.p_type != PT_NOTE)
123 continue;
124 Error Err = Error::success();
David Blaikieba005aa2018-12-11 00:09:06 +0000125 for (const auto &Note : In.notes(Phdr, Err))
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000126 if (Note.getType() == NT_GNU_BUILD_ID && Note.getName() == ELF_NOTE_GNU)
127 return Note.getDesc();
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000128 if (Err)
129 return std::move(Err);
130 }
131 return createStringError(llvm::errc::invalid_argument,
132 "Could not find build ID.");
133}
134
135static Expected<ArrayRef<uint8_t>>
136findBuildID(const object::ELFObjectFileBase &In) {
137 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(&In))
138 return findBuildID(*O->getELFFile());
139 else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(&In))
140 return findBuildID(*O->getELFFile());
141 else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(&In))
142 return findBuildID(*O->getELFFile());
143 else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(&In))
144 return findBuildID(*O->getELFFile());
145
146 llvm_unreachable("Bad file format");
147}
148
149static void linkToBuildIdDir(const CopyConfig &Config, StringRef ToLink,
150 StringRef Suffix, ArrayRef<uint8_t> BuildIdBytes) {
151 SmallString<128> Path = Config.BuildIdLinkDir;
152 sys::path::append(Path, llvm::toHex(BuildIdBytes[0], /*LowerCase*/ true));
153 if (auto EC = sys::fs::create_directories(Path))
154 error("cannot create build ID link directory " + Path + ": " +
155 EC.message());
156
157 sys::path::append(Path,
158 llvm::toHex(BuildIdBytes.slice(1), /*LowerCase*/ true));
159 Path += Suffix;
160 if (auto EC = sys::fs::create_hard_link(ToLink, Path)) {
161 // Hard linking failed, try to remove the file first if it exists.
162 if (sys::fs::exists(Path))
163 sys::fs::remove(Path);
164 EC = sys::fs::create_hard_link(ToLink, Path);
165 if (EC)
166 error("cannot link " + ToLink + " to " + Path + ": " + EC.message());
167 }
168}
169
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000170static void splitDWOToFile(const CopyConfig &Config, const Reader &Reader,
171 StringRef File, ElfType OutputElfType) {
172 auto DWOFile = Reader.create();
173 DWOFile->removeSections(
174 [&](const SectionBase &Sec) { return onlyKeepDWOPred(*DWOFile, Sec); });
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000175 if (Config.OutputArch)
176 DWOFile->Machine = Config.OutputArch.getValue().EMachine;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000177 FileBuffer FB(File);
178 auto Writer = createWriter(Config, *DWOFile, FB, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000179 if (Error E = Writer->finalize())
180 error(std::move(E));
181 if (Error E = Writer->write())
182 error(std::move(E));
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000183}
184
185static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
186 Object &Obj) {
187 for (auto &Sec : Obj.sections()) {
188 if (Sec.Name == SecName) {
Jordan Rupprecht16a0de22018-12-20 00:57:06 +0000189 if (Sec.OriginalData.empty())
Martin Storsjo8010c6be2019-01-22 10:57:59 +0000190 return createStringError(
191 object_error::parse_failed,
192 "Can't dump section \"%s\": it has no contents",
193 SecName.str().c_str());
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000194 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
195 FileOutputBuffer::create(Filename, Sec.OriginalData.size());
196 if (!BufferOrErr)
197 return BufferOrErr.takeError();
198 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
199 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(),
200 Buf->getBufferStart());
201 if (Error E = Buf->commit())
202 return E;
203 return Error::success();
204 }
205 }
Martin Storsjo8010c6be2019-01-22 10:57:59 +0000206 return createStringError(object_error::parse_failed, "Section not found");
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000207}
208
209static bool isCompressed(const SectionBase &Section) {
210 const char *Magic = "ZLIB";
211 return StringRef(Section.Name).startswith(".zdebug") ||
212 (Section.OriginalData.size() > strlen(Magic) &&
213 !strncmp(reinterpret_cast<const char *>(Section.OriginalData.data()),
214 Magic, strlen(Magic))) ||
215 (Section.Flags & ELF::SHF_COMPRESSED);
216}
217
218static bool isCompressable(const SectionBase &Section) {
219 return !isCompressed(Section) && isDebugSection(Section) &&
220 Section.Name != ".gdb_index";
221}
222
223static void replaceDebugSections(
224 const CopyConfig &Config, Object &Obj, SectionPred &RemovePred,
225 function_ref<bool(const SectionBase &)> shouldReplace,
226 function_ref<SectionBase *(const SectionBase *)> addSection) {
227 SmallVector<SectionBase *, 13> ToReplace;
228 SmallVector<RelocationSection *, 13> RelocationSections;
229 for (auto &Sec : Obj.sections()) {
230 if (RelocationSection *R = dyn_cast<RelocationSection>(&Sec)) {
231 if (shouldReplace(*R->getSection()))
232 RelocationSections.push_back(R);
233 continue;
234 }
235
236 if (shouldReplace(Sec))
237 ToReplace.push_back(&Sec);
238 }
239
240 for (SectionBase *S : ToReplace) {
241 SectionBase *NewSection = addSection(S);
242
243 for (RelocationSection *RS : RelocationSections) {
244 if (RS->getSection() == S)
245 RS->setSection(NewSection);
246 }
247 }
248
249 RemovePred = [shouldReplace, RemovePred](const SectionBase &Sec) {
250 return shouldReplace(Sec) || RemovePred(Sec);
251 };
252}
253
254// This function handles the high level operations of GNU objcopy including
255// handling command line options. It's important to outline certain properties
256// we expect to hold of the command line operations. Any operation that "keeps"
257// should keep regardless of a remove. Additionally any removal should respect
258// any previous removals. Lastly whether or not something is removed shouldn't
259// depend a) on the order the options occur in or b) on some opaque priority
260// system. The only priority is that keeps/copies overrule removes.
261static void handleArgs(const CopyConfig &Config, Object &Obj,
262 const Reader &Reader, ElfType OutputElfType) {
263
264 if (!Config.SplitDWO.empty()) {
265 splitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType);
266 }
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000267 if (Config.OutputArch)
268 Obj.Machine = Config.OutputArch.getValue().EMachine;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000269
270 // TODO: update or remove symbols only if there is an option that affects
271 // them.
272 if (Obj.SymbolTable) {
273 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
Jordan Rupprechtb47475c2018-11-01 17:26:36 +0000274 if (!Sym.isCommon() &&
275 ((Config.LocalizeHidden &&
276 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
Fangrui Songe4ee0662018-11-29 17:32:51 +0000277 is_contained(Config.SymbolsToLocalize, Sym.Name)))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000278 Sym.Binding = STB_LOCAL;
279
280 // Note: these two globalize flags have very similar names but different
281 // meanings:
282 //
283 // --globalize-symbol: promote a symbol to global
284 // --keep-global-symbol: all symbols except for these should be made local
285 //
286 // If --globalize-symbol is specified for a given symbol, it will be
287 // global in the output file even if it is not included via
288 // --keep-global-symbol. Because of that, make sure to check
289 // --globalize-symbol second.
290 if (!Config.SymbolsToKeepGlobal.empty() &&
Jordan Rupprecht634820d2018-10-30 16:23:38 +0000291 !is_contained(Config.SymbolsToKeepGlobal, Sym.Name) &&
292 Sym.getShndx() != SHN_UNDEF)
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000293 Sym.Binding = STB_LOCAL;
294
Fangrui Songe4ee0662018-11-29 17:32:51 +0000295 if (is_contained(Config.SymbolsToGlobalize, Sym.Name) &&
Jordan Rupprecht634820d2018-10-30 16:23:38 +0000296 Sym.getShndx() != SHN_UNDEF)
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000297 Sym.Binding = STB_GLOBAL;
298
Fangrui Songe4ee0662018-11-29 17:32:51 +0000299 if (is_contained(Config.SymbolsToWeaken, Sym.Name) &&
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000300 Sym.Binding == STB_GLOBAL)
301 Sym.Binding = STB_WEAK;
302
303 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
304 Sym.getShndx() != SHN_UNDEF)
305 Sym.Binding = STB_WEAK;
306
307 const auto I = Config.SymbolsToRename.find(Sym.Name);
308 if (I != Config.SymbolsToRename.end())
309 Sym.Name = I->getValue();
310
311 if (!Config.SymbolsPrefix.empty() && Sym.Type != STT_SECTION)
312 Sym.Name = (Config.SymbolsPrefix + Sym.Name).str();
313 });
314
315 // The purpose of this loop is to mark symbols referenced by sections
316 // (like GroupSection or RelocationSection). This way, we know which
317 // symbols are still 'needed' and which are not.
318 if (Config.StripUnneeded) {
319 for (auto &Section : Obj.sections())
320 Section.markSymbols();
321 }
322
323 Obj.removeSymbols([&](const Symbol &Sym) {
Fangrui Songe4ee0662018-11-29 17:32:51 +0000324 if (is_contained(Config.SymbolsToKeep, Sym.Name) ||
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000325 (Config.KeepFileSymbols && Sym.Type == STT_FILE))
326 return false;
327
328 if (Config.DiscardAll && Sym.Binding == STB_LOCAL &&
329 Sym.getShndx() != SHN_UNDEF && Sym.Type != STT_FILE &&
330 Sym.Type != STT_SECTION)
331 return true;
332
333 if (Config.StripAll || Config.StripAllGNU)
334 return true;
335
Fangrui Songe4ee0662018-11-29 17:32:51 +0000336 if (is_contained(Config.SymbolsToRemove, Sym.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000337 return true;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000338
339 if (Config.StripUnneeded && !Sym.Referenced &&
340 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
341 Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
342 return true;
343
344 return false;
345 });
346 }
347
348 SectionPred RemovePred = [](const SectionBase &) { return false; };
349
350 // Removes:
351 if (!Config.ToRemove.empty()) {
352 RemovePred = [&Config](const SectionBase &Sec) {
353 return is_contained(Config.ToRemove, Sec.Name);
354 };
355 }
356
357 if (Config.StripDWO || !Config.SplitDWO.empty())
358 RemovePred = [RemovePred](const SectionBase &Sec) {
359 return isDWOSection(Sec) || RemovePred(Sec);
360 };
361
362 if (Config.ExtractDWO)
363 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
364 return onlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
365 };
366
367 if (Config.StripAllGNU)
368 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
369 if (RemovePred(Sec))
370 return true;
371 if ((Sec.Flags & SHF_ALLOC) != 0)
372 return false;
373 if (&Sec == Obj.SectionNames)
374 return false;
375 switch (Sec.Type) {
376 case SHT_SYMTAB:
377 case SHT_REL:
378 case SHT_RELA:
379 case SHT_STRTAB:
380 return true;
381 }
382 return isDebugSection(Sec);
383 };
384
385 if (Config.StripSections) {
386 RemovePred = [RemovePred](const SectionBase &Sec) {
387 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
388 };
389 }
390
391 if (Config.StripDebug) {
392 RemovePred = [RemovePred](const SectionBase &Sec) {
393 return RemovePred(Sec) || isDebugSection(Sec);
394 };
395 }
396
397 if (Config.StripNonAlloc)
398 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
399 if (RemovePred(Sec))
400 return true;
401 if (&Sec == Obj.SectionNames)
402 return false;
403 return (Sec.Flags & SHF_ALLOC) == 0;
404 };
405
406 if (Config.StripAll)
407 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
408 if (RemovePred(Sec))
409 return true;
410 if (&Sec == Obj.SectionNames)
411 return false;
412 if (StringRef(Sec.Name).startswith(".gnu.warning"))
413 return false;
414 return (Sec.Flags & SHF_ALLOC) == 0;
415 };
416
417 // Explicit copies:
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000418 if (!Config.OnlySection.empty()) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000419 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
420 // Explicitly keep these sections regardless of previous removes.
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000421 if (is_contained(Config.OnlySection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000422 return false;
423
424 // Allow all implicit removes.
425 if (RemovePred(Sec))
426 return true;
427
428 // Keep special sections.
429 if (Obj.SectionNames == &Sec)
430 return false;
431 if (Obj.SymbolTable == &Sec ||
432 (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
433 return false;
434
435 // Remove everything else.
436 return true;
437 };
438 }
439
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000440 if (!Config.KeepSection.empty()) {
Fangrui Songe9f34b02018-11-12 23:46:22 +0000441 RemovePred = [&Config, RemovePred](const SectionBase &Sec) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000442 // Explicitly keep these sections regardless of previous removes.
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000443 if (is_contained(Config.KeepSection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000444 return false;
445 // Otherwise defer to RemovePred.
446 return RemovePred(Sec);
447 };
448 }
449
450 // This has to be the last predicate assignment.
451 // If the option --keep-symbol has been specified
452 // and at least one of those symbols is present
453 // (equivalently, the updated symbol table is not empty)
454 // the symbol table and the string table should not be removed.
455 if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) &&
456 Obj.SymbolTable && !Obj.SymbolTable->empty()) {
457 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
458 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
459 return false;
460 return RemovePred(Sec);
461 };
462 }
463
464 if (Config.CompressionType != DebugCompressionType::None)
465 replaceDebugSections(Config, Obj, RemovePred, isCompressable,
466 [&Config, &Obj](const SectionBase *S) {
467 return &Obj.addSection<CompressedSection>(
468 *S, Config.CompressionType);
469 });
470 else if (Config.DecompressDebugSections)
471 replaceDebugSections(
472 Config, Obj, RemovePred,
473 [](const SectionBase &S) { return isa<CompressedSection>(&S); },
474 [&Obj](const SectionBase *S) {
475 auto CS = cast<CompressedSection>(S);
476 return &Obj.addSection<DecompressedSection>(*CS);
477 });
478
479 Obj.removeSections(RemovePred);
480
481 if (!Config.SectionsToRename.empty()) {
482 for (auto &Sec : Obj.sections()) {
483 const auto Iter = Config.SectionsToRename.find(Sec.Name);
484 if (Iter != Config.SectionsToRename.end()) {
485 const SectionRename &SR = Iter->second;
486 Sec.Name = SR.NewName;
487 if (SR.NewFlags.hasValue()) {
488 // Preserve some flags which should not be dropped when setting flags.
489 // Also, preserve anything OS/processor dependant.
490 const uint64_t PreserveMask = ELF::SHF_COMPRESSED | ELF::SHF_EXCLUDE |
491 ELF::SHF_GROUP | ELF::SHF_LINK_ORDER |
492 ELF::SHF_MASKOS | ELF::SHF_MASKPROC |
493 ELF::SHF_TLS | ELF::SHF_INFO_LINK;
494 Sec.Flags = (Sec.Flags & PreserveMask) |
495 (SR.NewFlags.getValue() & ~PreserveMask);
496 }
497 }
498 }
499 }
500
501 if (!Config.AddSection.empty()) {
502 for (const auto &Flag : Config.AddSection) {
Jordan Rupprecht17dd4a22019-01-15 16:57:23 +0000503 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
504 StringRef SecName = SecPair.first;
505 StringRef File = SecPair.second;
506 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
507 MemoryBuffer::getFile(File);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000508 if (!BufOrErr)
509 reportError(File, BufOrErr.getError());
Jordan Rupprecht17dd4a22019-01-15 16:57:23 +0000510 std::unique_ptr<MemoryBuffer> Buf = std::move(*BufOrErr);
511 ArrayRef<uint8_t> Data(
512 reinterpret_cast<const uint8_t *>(Buf->getBufferStart()),
513 Buf->getBufferSize());
514 OwnedDataSection &NewSection =
515 Obj.addSection<OwnedDataSection>(SecName, Data);
516 if (SecName.startswith(".note") && SecName != ".note.GNU-stack")
517 NewSection.Type = SHT_NOTE;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000518 }
519 }
520
521 if (!Config.DumpSection.empty()) {
522 for (const auto &Flag : Config.DumpSection) {
523 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
524 StringRef SecName = SecPair.first;
525 StringRef File = SecPair.second;
526 if (Error E = dumpSectionToFile(SecName, File, Obj))
527 reportError(Config.InputFilename, std::move(E));
528 }
529 }
530
531 if (!Config.AddGnuDebugLink.empty())
532 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
533}
534
535void executeObjcopyOnRawBinary(const CopyConfig &Config, MemoryBuffer &In,
536 Buffer &Out) {
537 BinaryReader Reader(Config.BinaryArch, &In);
538 std::unique_ptr<Object> Obj = Reader.create();
539
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000540 // Prefer OutputArch (-O<format>) if set, otherwise fallback to BinaryArch
541 // (-B<arch>).
542 const ElfType OutputElfType = getOutputElfType(
543 Config.OutputArch ? Config.OutputArch.getValue() : Config.BinaryArch);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000544 handleArgs(Config, *Obj, Reader, OutputElfType);
545 std::unique_ptr<Writer> Writer =
546 createWriter(Config, *Obj, Out, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000547 if (Error E = Writer->finalize())
548 error(std::move(E));
549 if (Error E = Writer->write())
550 error(std::move(E));
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000551}
552
553void executeObjcopyOnBinary(const CopyConfig &Config,
554 object::ELFObjectFileBase &In, Buffer &Out) {
555 ELFReader Reader(&In);
556 std::unique_ptr<Object> Obj = Reader.create();
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000557 // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
558 const ElfType OutputElfType =
559 Config.OutputArch ? getOutputElfType(Config.OutputArch.getValue())
560 : getOutputElfType(In);
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000561 ArrayRef<uint8_t> BuildIdBytes;
562
563 if (!Config.BuildIdLinkDir.empty()) {
564 BuildIdBytes = unwrapOrError(findBuildID(In));
565 if (BuildIdBytes.size() < 2)
566 error("build ID in file '" + Config.InputFilename +
567 "' is smaller than two bytes");
568 }
569
570 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkInput) {
571 linkToBuildIdDir(Config, Config.InputFilename,
572 Config.BuildIdLinkInput.getValue(), BuildIdBytes);
573 }
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000574 handleArgs(Config, *Obj, Reader, OutputElfType);
575 std::unique_ptr<Writer> Writer =
576 createWriter(Config, *Obj, Out, OutputElfType);
Jordan Rupprecht881cae72019-01-22 23:49:16 +0000577 if (Error E = Writer->finalize())
578 error(std::move(E));
579 if (Error E = Writer->write())
580 error(std::move(E));
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000581 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkOutput) {
582 linkToBuildIdDir(Config, Config.OutputFilename,
583 Config.BuildIdLinkOutput.getValue(), BuildIdBytes);
584 }
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000585}
586
587} // end namespace elf
588} // end namespace objcopy
589} // end namespace llvm