blob: db0cd76ced41dc31bb44374a842ded985aab263a [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);
179 Writer->finalize();
180 Writer->write();
181}
182
183static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
184 Object &Obj) {
185 for (auto &Sec : Obj.sections()) {
186 if (Sec.Name == SecName) {
Jordan Rupprecht16a0de22018-12-20 00:57:06 +0000187 if (Sec.OriginalData.empty())
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000188 return make_error<StringError>("Can't dump section \"" + SecName +
189 "\": it has no contents",
190 object_error::parse_failed);
191 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
192 FileOutputBuffer::create(Filename, Sec.OriginalData.size());
193 if (!BufferOrErr)
194 return BufferOrErr.takeError();
195 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
196 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(),
197 Buf->getBufferStart());
198 if (Error E = Buf->commit())
199 return E;
200 return Error::success();
201 }
202 }
203 return make_error<StringError>("Section not found",
204 object_error::parse_failed);
205}
206
207static bool isCompressed(const SectionBase &Section) {
208 const char *Magic = "ZLIB";
209 return StringRef(Section.Name).startswith(".zdebug") ||
210 (Section.OriginalData.size() > strlen(Magic) &&
211 !strncmp(reinterpret_cast<const char *>(Section.OriginalData.data()),
212 Magic, strlen(Magic))) ||
213 (Section.Flags & ELF::SHF_COMPRESSED);
214}
215
216static bool isCompressable(const SectionBase &Section) {
217 return !isCompressed(Section) && isDebugSection(Section) &&
218 Section.Name != ".gdb_index";
219}
220
221static void replaceDebugSections(
222 const CopyConfig &Config, Object &Obj, SectionPred &RemovePred,
223 function_ref<bool(const SectionBase &)> shouldReplace,
224 function_ref<SectionBase *(const SectionBase *)> addSection) {
225 SmallVector<SectionBase *, 13> ToReplace;
226 SmallVector<RelocationSection *, 13> RelocationSections;
227 for (auto &Sec : Obj.sections()) {
228 if (RelocationSection *R = dyn_cast<RelocationSection>(&Sec)) {
229 if (shouldReplace(*R->getSection()))
230 RelocationSections.push_back(R);
231 continue;
232 }
233
234 if (shouldReplace(Sec))
235 ToReplace.push_back(&Sec);
236 }
237
238 for (SectionBase *S : ToReplace) {
239 SectionBase *NewSection = addSection(S);
240
241 for (RelocationSection *RS : RelocationSections) {
242 if (RS->getSection() == S)
243 RS->setSection(NewSection);
244 }
245 }
246
247 RemovePred = [shouldReplace, RemovePred](const SectionBase &Sec) {
248 return shouldReplace(Sec) || RemovePred(Sec);
249 };
250}
251
252// This function handles the high level operations of GNU objcopy including
253// handling command line options. It's important to outline certain properties
254// we expect to hold of the command line operations. Any operation that "keeps"
255// should keep regardless of a remove. Additionally any removal should respect
256// any previous removals. Lastly whether or not something is removed shouldn't
257// depend a) on the order the options occur in or b) on some opaque priority
258// system. The only priority is that keeps/copies overrule removes.
259static void handleArgs(const CopyConfig &Config, Object &Obj,
260 const Reader &Reader, ElfType OutputElfType) {
261
262 if (!Config.SplitDWO.empty()) {
263 splitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType);
264 }
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000265 if (Config.OutputArch)
266 Obj.Machine = Config.OutputArch.getValue().EMachine;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000267
268 // TODO: update or remove symbols only if there is an option that affects
269 // them.
270 if (Obj.SymbolTable) {
271 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
Jordan Rupprechtb47475c2018-11-01 17:26:36 +0000272 if (!Sym.isCommon() &&
273 ((Config.LocalizeHidden &&
274 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
Fangrui Songe4ee0662018-11-29 17:32:51 +0000275 is_contained(Config.SymbolsToLocalize, Sym.Name)))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000276 Sym.Binding = STB_LOCAL;
277
278 // Note: these two globalize flags have very similar names but different
279 // meanings:
280 //
281 // --globalize-symbol: promote a symbol to global
282 // --keep-global-symbol: all symbols except for these should be made local
283 //
284 // If --globalize-symbol is specified for a given symbol, it will be
285 // global in the output file even if it is not included via
286 // --keep-global-symbol. Because of that, make sure to check
287 // --globalize-symbol second.
288 if (!Config.SymbolsToKeepGlobal.empty() &&
Jordan Rupprecht634820d2018-10-30 16:23:38 +0000289 !is_contained(Config.SymbolsToKeepGlobal, Sym.Name) &&
290 Sym.getShndx() != SHN_UNDEF)
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000291 Sym.Binding = STB_LOCAL;
292
Fangrui Songe4ee0662018-11-29 17:32:51 +0000293 if (is_contained(Config.SymbolsToGlobalize, Sym.Name) &&
Jordan Rupprecht634820d2018-10-30 16:23:38 +0000294 Sym.getShndx() != SHN_UNDEF)
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000295 Sym.Binding = STB_GLOBAL;
296
Fangrui Songe4ee0662018-11-29 17:32:51 +0000297 if (is_contained(Config.SymbolsToWeaken, Sym.Name) &&
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000298 Sym.Binding == STB_GLOBAL)
299 Sym.Binding = STB_WEAK;
300
301 if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
302 Sym.getShndx() != SHN_UNDEF)
303 Sym.Binding = STB_WEAK;
304
305 const auto I = Config.SymbolsToRename.find(Sym.Name);
306 if (I != Config.SymbolsToRename.end())
307 Sym.Name = I->getValue();
308
309 if (!Config.SymbolsPrefix.empty() && Sym.Type != STT_SECTION)
310 Sym.Name = (Config.SymbolsPrefix + Sym.Name).str();
311 });
312
313 // The purpose of this loop is to mark symbols referenced by sections
314 // (like GroupSection or RelocationSection). This way, we know which
315 // symbols are still 'needed' and which are not.
316 if (Config.StripUnneeded) {
317 for (auto &Section : Obj.sections())
318 Section.markSymbols();
319 }
320
321 Obj.removeSymbols([&](const Symbol &Sym) {
Fangrui Songe4ee0662018-11-29 17:32:51 +0000322 if (is_contained(Config.SymbolsToKeep, Sym.Name) ||
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000323 (Config.KeepFileSymbols && Sym.Type == STT_FILE))
324 return false;
325
326 if (Config.DiscardAll && Sym.Binding == STB_LOCAL &&
327 Sym.getShndx() != SHN_UNDEF && Sym.Type != STT_FILE &&
328 Sym.Type != STT_SECTION)
329 return true;
330
331 if (Config.StripAll || Config.StripAllGNU)
332 return true;
333
Fangrui Songe4ee0662018-11-29 17:32:51 +0000334 if (is_contained(Config.SymbolsToRemove, Sym.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000335 return true;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000336
337 if (Config.StripUnneeded && !Sym.Referenced &&
338 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
339 Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
340 return true;
341
342 return false;
343 });
344 }
345
346 SectionPred RemovePred = [](const SectionBase &) { return false; };
347
348 // Removes:
349 if (!Config.ToRemove.empty()) {
350 RemovePred = [&Config](const SectionBase &Sec) {
351 return is_contained(Config.ToRemove, Sec.Name);
352 };
353 }
354
355 if (Config.StripDWO || !Config.SplitDWO.empty())
356 RemovePred = [RemovePred](const SectionBase &Sec) {
357 return isDWOSection(Sec) || RemovePred(Sec);
358 };
359
360 if (Config.ExtractDWO)
361 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
362 return onlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
363 };
364
365 if (Config.StripAllGNU)
366 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
367 if (RemovePred(Sec))
368 return true;
369 if ((Sec.Flags & SHF_ALLOC) != 0)
370 return false;
371 if (&Sec == Obj.SectionNames)
372 return false;
373 switch (Sec.Type) {
374 case SHT_SYMTAB:
375 case SHT_REL:
376 case SHT_RELA:
377 case SHT_STRTAB:
378 return true;
379 }
380 return isDebugSection(Sec);
381 };
382
383 if (Config.StripSections) {
384 RemovePred = [RemovePred](const SectionBase &Sec) {
385 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0;
386 };
387 }
388
389 if (Config.StripDebug) {
390 RemovePred = [RemovePred](const SectionBase &Sec) {
391 return RemovePred(Sec) || isDebugSection(Sec);
392 };
393 }
394
395 if (Config.StripNonAlloc)
396 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
397 if (RemovePred(Sec))
398 return true;
399 if (&Sec == Obj.SectionNames)
400 return false;
401 return (Sec.Flags & SHF_ALLOC) == 0;
402 };
403
404 if (Config.StripAll)
405 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
406 if (RemovePred(Sec))
407 return true;
408 if (&Sec == Obj.SectionNames)
409 return false;
410 if (StringRef(Sec.Name).startswith(".gnu.warning"))
411 return false;
412 return (Sec.Flags & SHF_ALLOC) == 0;
413 };
414
415 // Explicit copies:
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000416 if (!Config.OnlySection.empty()) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000417 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
418 // Explicitly keep these sections regardless of previous removes.
Jake Ehrlich85985ed2018-12-06 02:03:53 +0000419 if (is_contained(Config.OnlySection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000420 return false;
421
422 // Allow all implicit removes.
423 if (RemovePred(Sec))
424 return true;
425
426 // Keep special sections.
427 if (Obj.SectionNames == &Sec)
428 return false;
429 if (Obj.SymbolTable == &Sec ||
430 (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
431 return false;
432
433 // Remove everything else.
434 return true;
435 };
436 }
437
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000438 if (!Config.KeepSection.empty()) {
Fangrui Songe9f34b02018-11-12 23:46:22 +0000439 RemovePred = [&Config, RemovePred](const SectionBase &Sec) {
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000440 // Explicitly keep these sections regardless of previous removes.
Jordan Rupprechtc5bae782018-11-13 19:32:27 +0000441 if (is_contained(Config.KeepSection, Sec.Name))
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000442 return false;
443 // Otherwise defer to RemovePred.
444 return RemovePred(Sec);
445 };
446 }
447
448 // This has to be the last predicate assignment.
449 // If the option --keep-symbol has been specified
450 // and at least one of those symbols is present
451 // (equivalently, the updated symbol table is not empty)
452 // the symbol table and the string table should not be removed.
453 if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) &&
454 Obj.SymbolTable && !Obj.SymbolTable->empty()) {
455 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
456 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
457 return false;
458 return RemovePred(Sec);
459 };
460 }
461
462 if (Config.CompressionType != DebugCompressionType::None)
463 replaceDebugSections(Config, Obj, RemovePred, isCompressable,
464 [&Config, &Obj](const SectionBase *S) {
465 return &Obj.addSection<CompressedSection>(
466 *S, Config.CompressionType);
467 });
468 else if (Config.DecompressDebugSections)
469 replaceDebugSections(
470 Config, Obj, RemovePred,
471 [](const SectionBase &S) { return isa<CompressedSection>(&S); },
472 [&Obj](const SectionBase *S) {
473 auto CS = cast<CompressedSection>(S);
474 return &Obj.addSection<DecompressedSection>(*CS);
475 });
476
477 Obj.removeSections(RemovePred);
478
479 if (!Config.SectionsToRename.empty()) {
480 for (auto &Sec : Obj.sections()) {
481 const auto Iter = Config.SectionsToRename.find(Sec.Name);
482 if (Iter != Config.SectionsToRename.end()) {
483 const SectionRename &SR = Iter->second;
484 Sec.Name = SR.NewName;
485 if (SR.NewFlags.hasValue()) {
486 // Preserve some flags which should not be dropped when setting flags.
487 // Also, preserve anything OS/processor dependant.
488 const uint64_t PreserveMask = ELF::SHF_COMPRESSED | ELF::SHF_EXCLUDE |
489 ELF::SHF_GROUP | ELF::SHF_LINK_ORDER |
490 ELF::SHF_MASKOS | ELF::SHF_MASKPROC |
491 ELF::SHF_TLS | ELF::SHF_INFO_LINK;
492 Sec.Flags = (Sec.Flags & PreserveMask) |
493 (SR.NewFlags.getValue() & ~PreserveMask);
494 }
495 }
496 }
497 }
498
499 if (!Config.AddSection.empty()) {
500 for (const auto &Flag : Config.AddSection) {
Jordan Rupprecht17dd4a22019-01-15 16:57:23 +0000501 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
502 StringRef SecName = SecPair.first;
503 StringRef File = SecPair.second;
504 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
505 MemoryBuffer::getFile(File);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000506 if (!BufOrErr)
507 reportError(File, BufOrErr.getError());
Jordan Rupprecht17dd4a22019-01-15 16:57:23 +0000508 std::unique_ptr<MemoryBuffer> Buf = std::move(*BufOrErr);
509 ArrayRef<uint8_t> Data(
510 reinterpret_cast<const uint8_t *>(Buf->getBufferStart()),
511 Buf->getBufferSize());
512 OwnedDataSection &NewSection =
513 Obj.addSection<OwnedDataSection>(SecName, Data);
514 if (SecName.startswith(".note") && SecName != ".note.GNU-stack")
515 NewSection.Type = SHT_NOTE;
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000516 }
517 }
518
519 if (!Config.DumpSection.empty()) {
520 for (const auto &Flag : Config.DumpSection) {
521 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
522 StringRef SecName = SecPair.first;
523 StringRef File = SecPair.second;
524 if (Error E = dumpSectionToFile(SecName, File, Obj))
525 reportError(Config.InputFilename, std::move(E));
526 }
527 }
528
529 if (!Config.AddGnuDebugLink.empty())
530 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink);
531}
532
533void executeObjcopyOnRawBinary(const CopyConfig &Config, MemoryBuffer &In,
534 Buffer &Out) {
535 BinaryReader Reader(Config.BinaryArch, &In);
536 std::unique_ptr<Object> Obj = Reader.create();
537
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000538 // Prefer OutputArch (-O<format>) if set, otherwise fallback to BinaryArch
539 // (-B<arch>).
540 const ElfType OutputElfType = getOutputElfType(
541 Config.OutputArch ? Config.OutputArch.getValue() : Config.BinaryArch);
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000542 handleArgs(Config, *Obj, Reader, OutputElfType);
543 std::unique_ptr<Writer> Writer =
544 createWriter(Config, *Obj, Out, OutputElfType);
545 Writer->finalize();
546 Writer->write();
547}
548
549void executeObjcopyOnBinary(const CopyConfig &Config,
550 object::ELFObjectFileBase &In, Buffer &Out) {
551 ELFReader Reader(&In);
552 std::unique_ptr<Object> Obj = Reader.create();
Jordan Rupprecht70038e02019-01-07 16:59:12 +0000553 // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
554 const ElfType OutputElfType =
555 Config.OutputArch ? getOutputElfType(Config.OutputArch.getValue())
556 : getOutputElfType(In);
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000557 ArrayRef<uint8_t> BuildIdBytes;
558
559 if (!Config.BuildIdLinkDir.empty()) {
560 BuildIdBytes = unwrapOrError(findBuildID(In));
561 if (BuildIdBytes.size() < 2)
562 error("build ID in file '" + Config.InputFilename +
563 "' is smaller than two bytes");
564 }
565
566 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkInput) {
567 linkToBuildIdDir(Config, Config.InputFilename,
568 Config.BuildIdLinkInput.getValue(), BuildIdBytes);
569 }
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000570 handleArgs(Config, *Obj, Reader, OutputElfType);
571 std::unique_ptr<Writer> Writer =
572 createWriter(Config, *Obj, Out, OutputElfType);
573 Writer->finalize();
574 Writer->write();
Jake Ehrlich8ad77792018-12-03 19:49:23 +0000575 if (!Config.BuildIdLinkDir.empty() && Config.BuildIdLinkOutput) {
576 linkToBuildIdDir(Config, Config.OutputFilename,
577 Config.BuildIdLinkOutput.getValue(), BuildIdBytes);
578 }
Alexander Shaposhnikovf4e75a52018-10-29 21:22:58 +0000579}
580
581} // end namespace elf
582} // end namespace objcopy
583} // end namespace llvm