ELFObjcopy.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. //===- ELFObjcopy.cpp -----------------------------------------------------===//
  2. //
  3. // 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
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "ELFObjcopy.h"
  9. #include "CommonConfig.h"
  10. #include "ELFConfig.h"
  11. #include "Object.h"
  12. #include "llvm-objcopy.h"
  13. #include "llvm/ADT/BitmaskEnum.h"
  14. #include "llvm/ADT/DenseSet.h"
  15. #include "llvm/ADT/Optional.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/ADT/StringRef.h"
  19. #include "llvm/ADT/Twine.h"
  20. #include "llvm/BinaryFormat/ELF.h"
  21. #include "llvm/MC/MCTargetOptions.h"
  22. #include "llvm/Object/Binary.h"
  23. #include "llvm/Object/ELFObjectFile.h"
  24. #include "llvm/Object/ELFTypes.h"
  25. #include "llvm/Object/Error.h"
  26. #include "llvm/Option/Option.h"
  27. #include "llvm/Support/Casting.h"
  28. #include "llvm/Support/Compression.h"
  29. #include "llvm/Support/Errc.h"
  30. #include "llvm/Support/Error.h"
  31. #include "llvm/Support/ErrorHandling.h"
  32. #include "llvm/Support/ErrorOr.h"
  33. #include "llvm/Support/FileSystem.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. using namespace llvm;
  47. using namespace llvm::ELF;
  48. using namespace llvm::objcopy;
  49. using namespace llvm::objcopy::elf;
  50. using namespace llvm::object;
  51. using SectionPred = std::function<bool(const SectionBase &Sec)>;
  52. static bool isDebugSection(const SectionBase &Sec) {
  53. return StringRef(Sec.Name).startswith(".debug") ||
  54. StringRef(Sec.Name).startswith(".zdebug") || Sec.Name == ".gdb_index";
  55. }
  56. static bool isDWOSection(const SectionBase &Sec) {
  57. return StringRef(Sec.Name).endswith(".dwo");
  58. }
  59. static bool onlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) {
  60. // We can't remove the section header string table.
  61. if (&Sec == Obj.SectionNames)
  62. return false;
  63. // Short of keeping the string table we want to keep everything that is a DWO
  64. // section and remove everything else.
  65. return !isDWOSection(Sec);
  66. }
  67. static uint64_t getNewShfFlags(SectionFlag AllFlags) {
  68. uint64_t NewFlags = 0;
  69. if (AllFlags & SectionFlag::SecAlloc)
  70. NewFlags |= ELF::SHF_ALLOC;
  71. if (!(AllFlags & SectionFlag::SecReadonly))
  72. NewFlags |= ELF::SHF_WRITE;
  73. if (AllFlags & SectionFlag::SecCode)
  74. NewFlags |= ELF::SHF_EXECINSTR;
  75. if (AllFlags & SectionFlag::SecMerge)
  76. NewFlags |= ELF::SHF_MERGE;
  77. if (AllFlags & SectionFlag::SecStrings)
  78. NewFlags |= ELF::SHF_STRINGS;
  79. if (AllFlags & SectionFlag::SecExclude)
  80. NewFlags |= ELF::SHF_EXCLUDE;
  81. return NewFlags;
  82. }
  83. static uint64_t getSectionFlagsPreserveMask(uint64_t OldFlags,
  84. uint64_t NewFlags) {
  85. // Preserve some flags which should not be dropped when setting flags.
  86. // Also, preserve anything OS/processor dependant.
  87. const uint64_t PreserveMask =
  88. (ELF::SHF_COMPRESSED | ELF::SHF_GROUP | ELF::SHF_LINK_ORDER |
  89. ELF::SHF_MASKOS | ELF::SHF_MASKPROC | ELF::SHF_TLS |
  90. ELF::SHF_INFO_LINK) &
  91. ~ELF::SHF_EXCLUDE;
  92. return (OldFlags & PreserveMask) | (NewFlags & ~PreserveMask);
  93. }
  94. static void setSectionFlagsAndType(SectionBase &Sec, SectionFlag Flags) {
  95. Sec.Flags = getSectionFlagsPreserveMask(Sec.Flags, getNewShfFlags(Flags));
  96. // In GNU objcopy, certain flags promote SHT_NOBITS to SHT_PROGBITS. This rule
  97. // may promote more non-ALLOC sections than GNU objcopy, but it is fine as
  98. // non-ALLOC SHT_NOBITS sections do not make much sense.
  99. if (Sec.Type == SHT_NOBITS &&
  100. (!(Sec.Flags & ELF::SHF_ALLOC) ||
  101. Flags & (SectionFlag::SecContents | SectionFlag::SecLoad)))
  102. Sec.Type = SHT_PROGBITS;
  103. }
  104. static ElfType getOutputElfType(const Binary &Bin) {
  105. // Infer output ELF type from the input ELF object
  106. if (isa<ELFObjectFile<ELF32LE>>(Bin))
  107. return ELFT_ELF32LE;
  108. if (isa<ELFObjectFile<ELF64LE>>(Bin))
  109. return ELFT_ELF64LE;
  110. if (isa<ELFObjectFile<ELF32BE>>(Bin))
  111. return ELFT_ELF32BE;
  112. if (isa<ELFObjectFile<ELF64BE>>(Bin))
  113. return ELFT_ELF64BE;
  114. llvm_unreachable("Invalid ELFType");
  115. }
  116. static ElfType getOutputElfType(const MachineInfo &MI) {
  117. // Infer output ELF type from the binary arch specified
  118. if (MI.Is64Bit)
  119. return MI.IsLittleEndian ? ELFT_ELF64LE : ELFT_ELF64BE;
  120. else
  121. return MI.IsLittleEndian ? ELFT_ELF32LE : ELFT_ELF32BE;
  122. }
  123. static std::unique_ptr<Writer> createELFWriter(const CommonConfig &Config,
  124. Object &Obj, raw_ostream &Out,
  125. ElfType OutputElfType) {
  126. // Depending on the initial ELFT and OutputFormat we need a different Writer.
  127. switch (OutputElfType) {
  128. case ELFT_ELF32LE:
  129. return std::make_unique<ELFWriter<ELF32LE>>(Obj, Out, !Config.StripSections,
  130. Config.OnlyKeepDebug);
  131. case ELFT_ELF64LE:
  132. return std::make_unique<ELFWriter<ELF64LE>>(Obj, Out, !Config.StripSections,
  133. Config.OnlyKeepDebug);
  134. case ELFT_ELF32BE:
  135. return std::make_unique<ELFWriter<ELF32BE>>(Obj, Out, !Config.StripSections,
  136. Config.OnlyKeepDebug);
  137. case ELFT_ELF64BE:
  138. return std::make_unique<ELFWriter<ELF64BE>>(Obj, Out, !Config.StripSections,
  139. Config.OnlyKeepDebug);
  140. }
  141. llvm_unreachable("Invalid output format");
  142. }
  143. static std::unique_ptr<Writer> createWriter(const CommonConfig &Config,
  144. Object &Obj, raw_ostream &Out,
  145. ElfType OutputElfType) {
  146. switch (Config.OutputFormat) {
  147. case FileFormat::Binary:
  148. return std::make_unique<BinaryWriter>(Obj, Out);
  149. case FileFormat::IHex:
  150. return std::make_unique<IHexWriter>(Obj, Out);
  151. default:
  152. return createELFWriter(Config, Obj, Out, OutputElfType);
  153. }
  154. }
  155. template <class... Ts>
  156. static Error makeStringError(std::error_code EC, const Twine &Msg,
  157. Ts &&... Args) {
  158. std::string FullMsg = (EC.message() + ": " + Msg).str();
  159. return createStringError(EC, FullMsg.c_str(), std::forward<Ts>(Args)...);
  160. }
  161. static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
  162. Object &Obj) {
  163. for (auto &Sec : Obj.sections()) {
  164. if (Sec.Name == SecName) {
  165. if (Sec.Type == SHT_NOBITS)
  166. return createStringError(object_error::parse_failed,
  167. "cannot dump section '%s': it has no contents",
  168. SecName.str().c_str());
  169. Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
  170. FileOutputBuffer::create(Filename, Sec.OriginalData.size());
  171. if (!BufferOrErr)
  172. return BufferOrErr.takeError();
  173. std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
  174. std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(),
  175. Buf->getBufferStart());
  176. if (Error E = Buf->commit())
  177. return E;
  178. return Error::success();
  179. }
  180. }
  181. return createStringError(object_error::parse_failed, "section '%s' not found",
  182. SecName.str().c_str());
  183. }
  184. static bool isCompressable(const SectionBase &Sec) {
  185. return !(Sec.Flags & ELF::SHF_COMPRESSED) &&
  186. StringRef(Sec.Name).startswith(".debug");
  187. }
  188. static Error replaceDebugSections(
  189. Object &Obj, function_ref<bool(const SectionBase &)> ShouldReplace,
  190. function_ref<Expected<SectionBase *>(const SectionBase *)> AddSection) {
  191. // Build a list of the debug sections we are going to replace.
  192. // We can't call `AddSection` while iterating over sections,
  193. // because it would mutate the sections array.
  194. SmallVector<SectionBase *, 13> ToReplace;
  195. for (auto &Sec : Obj.sections())
  196. if (ShouldReplace(Sec))
  197. ToReplace.push_back(&Sec);
  198. // Build a mapping from original section to a new one.
  199. DenseMap<SectionBase *, SectionBase *> FromTo;
  200. for (SectionBase *S : ToReplace) {
  201. Expected<SectionBase *> NewSection = AddSection(S);
  202. if (!NewSection)
  203. return NewSection.takeError();
  204. FromTo[S] = *NewSection;
  205. }
  206. return Obj.replaceSections(FromTo);
  207. }
  208. static bool isAArch64MappingSymbol(const Symbol &Sym) {
  209. if (Sym.Binding != STB_LOCAL || Sym.Type != STT_NOTYPE ||
  210. Sym.getShndx() == SHN_UNDEF)
  211. return false;
  212. StringRef Name = Sym.Name;
  213. if (!Name.consume_front("$x") && !Name.consume_front("$d"))
  214. return false;
  215. return Name.empty() || Name.startswith(".");
  216. }
  217. static bool isArmMappingSymbol(const Symbol &Sym) {
  218. if (Sym.Binding != STB_LOCAL || Sym.Type != STT_NOTYPE ||
  219. Sym.getShndx() == SHN_UNDEF)
  220. return false;
  221. StringRef Name = Sym.Name;
  222. if (!Name.consume_front("$a") && !Name.consume_front("$d") &&
  223. !Name.consume_front("$t"))
  224. return false;
  225. return Name.empty() || Name.startswith(".");
  226. }
  227. // Check if the symbol should be preserved because it is required by ABI.
  228. static bool isRequiredByABISymbol(const Object &Obj, const Symbol &Sym) {
  229. switch (Obj.Machine) {
  230. case EM_AARCH64:
  231. // Mapping symbols should be preserved for a relocatable object file.
  232. return Obj.isRelocatable() && isAArch64MappingSymbol(Sym);
  233. case EM_ARM:
  234. // Mapping symbols should be preserved for a relocatable object file.
  235. return Obj.isRelocatable() && isArmMappingSymbol(Sym);
  236. default:
  237. return false;
  238. }
  239. }
  240. static bool isUnneededSymbol(const Symbol &Sym) {
  241. return !Sym.Referenced &&
  242. (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) &&
  243. Sym.Type != STT_SECTION;
  244. }
  245. static Error updateAndRemoveSymbols(const CommonConfig &Config,
  246. const ELFConfig &ELFConfig, Object &Obj) {
  247. // TODO: update or remove symbols only if there is an option that affects
  248. // them.
  249. if (!Obj.SymbolTable)
  250. return Error::success();
  251. Obj.SymbolTable->updateSymbols([&](Symbol &Sym) {
  252. // Common and undefined symbols don't make sense as local symbols, and can
  253. // even cause crashes if we localize those, so skip them.
  254. if (!Sym.isCommon() && Sym.getShndx() != SHN_UNDEF &&
  255. ((ELFConfig.LocalizeHidden &&
  256. (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) ||
  257. Config.SymbolsToLocalize.matches(Sym.Name)))
  258. Sym.Binding = STB_LOCAL;
  259. // Note: these two globalize flags have very similar names but different
  260. // meanings:
  261. //
  262. // --globalize-symbol: promote a symbol to global
  263. // --keep-global-symbol: all symbols except for these should be made local
  264. //
  265. // If --globalize-symbol is specified for a given symbol, it will be
  266. // global in the output file even if it is not included via
  267. // --keep-global-symbol. Because of that, make sure to check
  268. // --globalize-symbol second.
  269. if (!Config.SymbolsToKeepGlobal.empty() &&
  270. !Config.SymbolsToKeepGlobal.matches(Sym.Name) &&
  271. Sym.getShndx() != SHN_UNDEF)
  272. Sym.Binding = STB_LOCAL;
  273. if (Config.SymbolsToGlobalize.matches(Sym.Name) &&
  274. Sym.getShndx() != SHN_UNDEF)
  275. Sym.Binding = STB_GLOBAL;
  276. if (Config.SymbolsToWeaken.matches(Sym.Name) && Sym.Binding == STB_GLOBAL)
  277. Sym.Binding = STB_WEAK;
  278. if (Config.Weaken && Sym.Binding == STB_GLOBAL &&
  279. Sym.getShndx() != SHN_UNDEF)
  280. Sym.Binding = STB_WEAK;
  281. const auto I = Config.SymbolsToRename.find(Sym.Name);
  282. if (I != Config.SymbolsToRename.end())
  283. Sym.Name = std::string(I->getValue());
  284. if (!Config.SymbolsPrefix.empty() && Sym.Type != STT_SECTION)
  285. Sym.Name = (Config.SymbolsPrefix + Sym.Name).str();
  286. });
  287. // The purpose of this loop is to mark symbols referenced by sections
  288. // (like GroupSection or RelocationSection). This way, we know which
  289. // symbols are still 'needed' and which are not.
  290. if (Config.StripUnneeded || !Config.UnneededSymbolsToRemove.empty() ||
  291. !Config.OnlySection.empty()) {
  292. for (SectionBase &Sec : Obj.sections())
  293. Sec.markSymbols();
  294. }
  295. auto RemoveSymbolsPred = [&](const Symbol &Sym) {
  296. if (Config.SymbolsToKeep.matches(Sym.Name) ||
  297. (ELFConfig.KeepFileSymbols && Sym.Type == STT_FILE))
  298. return false;
  299. if (Config.SymbolsToRemove.matches(Sym.Name))
  300. return true;
  301. if (Config.StripAll || Config.StripAllGNU)
  302. return true;
  303. if (isRequiredByABISymbol(Obj, Sym))
  304. return false;
  305. if (Config.StripDebug && Sym.Type == STT_FILE)
  306. return true;
  307. if ((Config.DiscardMode == DiscardType::All ||
  308. (Config.DiscardMode == DiscardType::Locals &&
  309. StringRef(Sym.Name).startswith(".L"))) &&
  310. Sym.Binding == STB_LOCAL && Sym.getShndx() != SHN_UNDEF &&
  311. Sym.Type != STT_FILE && Sym.Type != STT_SECTION)
  312. return true;
  313. if ((Config.StripUnneeded ||
  314. Config.UnneededSymbolsToRemove.matches(Sym.Name)) &&
  315. (!Obj.isRelocatable() || isUnneededSymbol(Sym)))
  316. return true;
  317. // We want to remove undefined symbols if all references have been stripped.
  318. if (!Config.OnlySection.empty() && !Sym.Referenced &&
  319. Sym.getShndx() == SHN_UNDEF)
  320. return true;
  321. return false;
  322. };
  323. return Obj.removeSymbols(RemoveSymbolsPred);
  324. }
  325. static Error replaceAndRemoveSections(const CommonConfig &Config,
  326. const ELFConfig &ELFConfig, Object &Obj) {
  327. SectionPred RemovePred = [](const SectionBase &) { return false; };
  328. // Removes:
  329. if (!Config.ToRemove.empty()) {
  330. RemovePred = [&Config](const SectionBase &Sec) {
  331. return Config.ToRemove.matches(Sec.Name);
  332. };
  333. }
  334. if (Config.StripDWO)
  335. RemovePred = [RemovePred](const SectionBase &Sec) {
  336. return isDWOSection(Sec) || RemovePred(Sec);
  337. };
  338. if (Config.ExtractDWO)
  339. RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
  340. return onlyKeepDWOPred(Obj, Sec) || RemovePred(Sec);
  341. };
  342. if (Config.StripAllGNU)
  343. RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
  344. if (RemovePred(Sec))
  345. return true;
  346. if ((Sec.Flags & SHF_ALLOC) != 0)
  347. return false;
  348. if (&Sec == Obj.SectionNames)
  349. return false;
  350. switch (Sec.Type) {
  351. case SHT_SYMTAB:
  352. case SHT_REL:
  353. case SHT_RELA:
  354. case SHT_STRTAB:
  355. return true;
  356. }
  357. return isDebugSection(Sec);
  358. };
  359. if (Config.StripSections) {
  360. RemovePred = [RemovePred](const SectionBase &Sec) {
  361. return RemovePred(Sec) || Sec.ParentSegment == nullptr;
  362. };
  363. }
  364. if (Config.StripDebug || Config.StripUnneeded) {
  365. RemovePred = [RemovePred](const SectionBase &Sec) {
  366. return RemovePred(Sec) || isDebugSection(Sec);
  367. };
  368. }
  369. if (Config.StripNonAlloc)
  370. RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
  371. if (RemovePred(Sec))
  372. return true;
  373. if (&Sec == Obj.SectionNames)
  374. return false;
  375. return (Sec.Flags & SHF_ALLOC) == 0 && Sec.ParentSegment == nullptr;
  376. };
  377. if (Config.StripAll)
  378. RemovePred = [RemovePred, &Obj](const SectionBase &Sec) {
  379. if (RemovePred(Sec))
  380. return true;
  381. if (&Sec == Obj.SectionNames)
  382. return false;
  383. if (StringRef(Sec.Name).startswith(".gnu.warning"))
  384. return false;
  385. // We keep the .ARM.attribute section to maintain compatibility
  386. // with Debian derived distributions. This is a bug in their
  387. // patchset as documented here:
  388. // https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=943798
  389. if (Sec.Type == SHT_ARM_ATTRIBUTES)
  390. return false;
  391. if (Sec.ParentSegment != nullptr)
  392. return false;
  393. return (Sec.Flags & SHF_ALLOC) == 0;
  394. };
  395. if (Config.ExtractPartition || Config.ExtractMainPartition) {
  396. RemovePred = [RemovePred](const SectionBase &Sec) {
  397. if (RemovePred(Sec))
  398. return true;
  399. if (Sec.Type == SHT_LLVM_PART_EHDR || Sec.Type == SHT_LLVM_PART_PHDR)
  400. return true;
  401. return (Sec.Flags & SHF_ALLOC) != 0 && !Sec.ParentSegment;
  402. };
  403. }
  404. // Explicit copies:
  405. if (!Config.OnlySection.empty()) {
  406. RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) {
  407. // Explicitly keep these sections regardless of previous removes.
  408. if (Config.OnlySection.matches(Sec.Name))
  409. return false;
  410. // Allow all implicit removes.
  411. if (RemovePred(Sec))
  412. return true;
  413. // Keep special sections.
  414. if (Obj.SectionNames == &Sec)
  415. return false;
  416. if (Obj.SymbolTable == &Sec ||
  417. (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec))
  418. return false;
  419. // Remove everything else.
  420. return true;
  421. };
  422. }
  423. if (!Config.KeepSection.empty()) {
  424. RemovePred = [&Config, RemovePred](const SectionBase &Sec) {
  425. // Explicitly keep these sections regardless of previous removes.
  426. if (Config.KeepSection.matches(Sec.Name))
  427. return false;
  428. // Otherwise defer to RemovePred.
  429. return RemovePred(Sec);
  430. };
  431. }
  432. // This has to be the last predicate assignment.
  433. // If the option --keep-symbol has been specified
  434. // and at least one of those symbols is present
  435. // (equivalently, the updated symbol table is not empty)
  436. // the symbol table and the string table should not be removed.
  437. if ((!Config.SymbolsToKeep.empty() || ELFConfig.KeepFileSymbols) &&
  438. Obj.SymbolTable && !Obj.SymbolTable->empty()) {
  439. RemovePred = [&Obj, RemovePred](const SectionBase &Sec) {
  440. if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab())
  441. return false;
  442. return RemovePred(Sec);
  443. };
  444. }
  445. if (Error E = Obj.removeSections(ELFConfig.AllowBrokenLinks, RemovePred))
  446. return E;
  447. if (Config.CompressionType != DebugCompressionType::None) {
  448. if (Error Err = replaceDebugSections(
  449. Obj, isCompressable,
  450. [&Config, &Obj](const SectionBase *S) -> Expected<SectionBase *> {
  451. Expected<CompressedSection> NewSection =
  452. CompressedSection::create(*S, Config.CompressionType);
  453. if (!NewSection)
  454. return NewSection.takeError();
  455. return &Obj.addSection<CompressedSection>(std::move(*NewSection));
  456. }))
  457. return Err;
  458. } else if (Config.DecompressDebugSections) {
  459. if (Error Err = replaceDebugSections(
  460. Obj,
  461. [](const SectionBase &S) { return isa<CompressedSection>(&S); },
  462. [&Obj](const SectionBase *S) {
  463. const CompressedSection *CS = cast<CompressedSection>(S);
  464. return &Obj.addSection<DecompressedSection>(*CS);
  465. }))
  466. return Err;
  467. }
  468. return Error::success();
  469. }
  470. // Add symbol to the Object symbol table with the specified properties.
  471. static void addSymbol(Object &Obj, const NewSymbolInfo &SymInfo,
  472. uint8_t DefaultVisibility) {
  473. SectionBase *Sec = Obj.findSection(SymInfo.SectionName);
  474. uint64_t Value = Sec ? Sec->Addr + SymInfo.Value : SymInfo.Value;
  475. uint8_t Bind = ELF::STB_GLOBAL;
  476. uint8_t Type = ELF::STT_NOTYPE;
  477. uint8_t Visibility = DefaultVisibility;
  478. for (SymbolFlag FlagValue : SymInfo.Flags)
  479. switch (FlagValue) {
  480. case SymbolFlag::Global:
  481. Bind = ELF::STB_GLOBAL;
  482. break;
  483. case SymbolFlag::Local:
  484. Bind = ELF::STB_LOCAL;
  485. break;
  486. case SymbolFlag::Weak:
  487. Bind = ELF::STB_WEAK;
  488. break;
  489. case SymbolFlag::Default:
  490. Visibility = ELF::STV_DEFAULT;
  491. break;
  492. case SymbolFlag::Hidden:
  493. Visibility = ELF::STV_HIDDEN;
  494. break;
  495. case SymbolFlag::Protected:
  496. Visibility = ELF::STV_PROTECTED;
  497. break;
  498. case SymbolFlag::File:
  499. Type = ELF::STT_FILE;
  500. break;
  501. case SymbolFlag::Section:
  502. Type = ELF::STT_SECTION;
  503. break;
  504. case SymbolFlag::Object:
  505. Type = ELF::STT_OBJECT;
  506. break;
  507. case SymbolFlag::Function:
  508. Type = ELF::STT_FUNC;
  509. break;
  510. case SymbolFlag::IndirectFunction:
  511. Type = ELF::STT_GNU_IFUNC;
  512. break;
  513. default: /* Other flag values are ignored for ELF. */
  514. break;
  515. };
  516. Obj.SymbolTable->addSymbol(
  517. SymInfo.SymbolName, Bind, Type, Sec, Value, Visibility,
  518. Sec ? (uint16_t)SYMBOL_SIMPLE_INDEX : (uint16_t)SHN_ABS, 0);
  519. }
  520. static Error
  521. handleUserSection(StringRef Flag,
  522. function_ref<Error(StringRef, ArrayRef<uint8_t>)> F) {
  523. std::pair<StringRef, StringRef> SecPair = Flag.split("=");
  524. StringRef SecName = SecPair.first;
  525. StringRef File = SecPair.second;
  526. ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = MemoryBuffer::getFile(File);
  527. if (!BufOrErr)
  528. return createFileError(File, errorCodeToError(BufOrErr.getError()));
  529. std::unique_ptr<MemoryBuffer> Buf = std::move(*BufOrErr);
  530. ArrayRef<uint8_t> Data(
  531. reinterpret_cast<const uint8_t *>(Buf->getBufferStart()),
  532. Buf->getBufferSize());
  533. return F(SecName, Data);
  534. }
  535. // This function handles the high level operations of GNU objcopy including
  536. // handling command line options. It's important to outline certain properties
  537. // we expect to hold of the command line operations. Any operation that "keeps"
  538. // should keep regardless of a remove. Additionally any removal should respect
  539. // any previous removals. Lastly whether or not something is removed shouldn't
  540. // depend a) on the order the options occur in or b) on some opaque priority
  541. // system. The only priority is that keeps/copies overrule removes.
  542. static Error handleArgs(const CommonConfig &Config, const ELFConfig &ELFConfig,
  543. Object &Obj) {
  544. if (Config.OutputArch) {
  545. Obj.Machine = Config.OutputArch.getValue().EMachine;
  546. Obj.OSABI = Config.OutputArch.getValue().OSABI;
  547. }
  548. if (!Config.SplitDWO.empty() && Config.ExtractDWO) {
  549. return Obj.removeSections(
  550. ELFConfig.AllowBrokenLinks,
  551. [&Obj](const SectionBase &Sec) { return onlyKeepDWOPred(Obj, Sec); });
  552. }
  553. // Dump sections before add/remove for compatibility with GNU objcopy.
  554. for (StringRef Flag : Config.DumpSection) {
  555. StringRef SectionName;
  556. StringRef FileName;
  557. std::tie(SectionName, FileName) = Flag.split('=');
  558. if (Error E = dumpSectionToFile(SectionName, FileName, Obj))
  559. return E;
  560. }
  561. // It is important to remove the sections first. For example, we want to
  562. // remove the relocation sections before removing the symbols. That allows
  563. // us to avoid reporting the inappropriate errors about removing symbols
  564. // named in relocations.
  565. if (Error E = replaceAndRemoveSections(Config, ELFConfig, Obj))
  566. return E;
  567. if (Error E = updateAndRemoveSymbols(Config, ELFConfig, Obj))
  568. return E;
  569. if (!Config.SectionsToRename.empty()) {
  570. std::vector<RelocationSectionBase *> RelocSections;
  571. DenseSet<SectionBase *> RenamedSections;
  572. for (SectionBase &Sec : Obj.sections()) {
  573. auto *RelocSec = dyn_cast<RelocationSectionBase>(&Sec);
  574. const auto Iter = Config.SectionsToRename.find(Sec.Name);
  575. if (Iter != Config.SectionsToRename.end()) {
  576. const SectionRename &SR = Iter->second;
  577. Sec.Name = std::string(SR.NewName);
  578. if (SR.NewFlags.hasValue())
  579. setSectionFlagsAndType(Sec, SR.NewFlags.getValue());
  580. RenamedSections.insert(&Sec);
  581. } else if (RelocSec && !(Sec.Flags & SHF_ALLOC))
  582. // Postpone processing relocation sections which are not specified in
  583. // their explicit '--rename-section' commands until after their target
  584. // sections are renamed.
  585. // Dynamic relocation sections (i.e. ones with SHF_ALLOC) should be
  586. // renamed only explicitly. Otherwise, renaming, for example, '.got.plt'
  587. // would affect '.rela.plt', which is not desirable.
  588. RelocSections.push_back(RelocSec);
  589. }
  590. // Rename relocation sections according to their target sections.
  591. for (RelocationSectionBase *RelocSec : RelocSections) {
  592. auto Iter = RenamedSections.find(RelocSec->getSection());
  593. if (Iter != RenamedSections.end())
  594. RelocSec->Name = (RelocSec->getNamePrefix() + (*Iter)->Name).str();
  595. }
  596. }
  597. // Add a prefix to allocated sections and their relocation sections. This
  598. // should be done after renaming the section by Config.SectionToRename to
  599. // imitate the GNU objcopy behavior.
  600. if (!Config.AllocSectionsPrefix.empty()) {
  601. DenseSet<SectionBase *> PrefixedSections;
  602. for (SectionBase &Sec : Obj.sections()) {
  603. if (Sec.Flags & SHF_ALLOC) {
  604. Sec.Name = (Config.AllocSectionsPrefix + Sec.Name).str();
  605. PrefixedSections.insert(&Sec);
  606. } else if (auto *RelocSec = dyn_cast<RelocationSectionBase>(&Sec)) {
  607. // Rename relocation sections associated to the allocated sections.
  608. // For example, if we rename .text to .prefix.text, we also rename
  609. // .rel.text to .rel.prefix.text.
  610. //
  611. // Dynamic relocation sections (SHT_REL[A] with SHF_ALLOC) are handled
  612. // above, e.g., .rela.plt is renamed to .prefix.rela.plt, not
  613. // .rela.prefix.plt since GNU objcopy does so.
  614. const SectionBase *TargetSec = RelocSec->getSection();
  615. if (TargetSec && (TargetSec->Flags & SHF_ALLOC)) {
  616. // If the relocation section comes *after* the target section, we
  617. // don't add Config.AllocSectionsPrefix because we've already added
  618. // the prefix to TargetSec->Name. Otherwise, if the relocation
  619. // section comes *before* the target section, we add the prefix.
  620. if (PrefixedSections.count(TargetSec))
  621. Sec.Name = (RelocSec->getNamePrefix() + TargetSec->Name).str();
  622. else
  623. Sec.Name = (RelocSec->getNamePrefix() + Config.AllocSectionsPrefix +
  624. TargetSec->Name)
  625. .str();
  626. }
  627. }
  628. }
  629. }
  630. if (!Config.SetSectionAlignment.empty()) {
  631. for (SectionBase &Sec : Obj.sections()) {
  632. auto I = Config.SetSectionAlignment.find(Sec.Name);
  633. if (I != Config.SetSectionAlignment.end())
  634. Sec.Align = I->second;
  635. }
  636. }
  637. if (Config.OnlyKeepDebug)
  638. for (auto &Sec : Obj.sections())
  639. if (Sec.Flags & SHF_ALLOC && Sec.Type != SHT_NOTE)
  640. Sec.Type = SHT_NOBITS;
  641. for (const auto &Flag : Config.AddSection) {
  642. auto AddSection = [&](StringRef Name, ArrayRef<uint8_t> Data) {
  643. OwnedDataSection &NewSection =
  644. Obj.addSection<OwnedDataSection>(Name, Data);
  645. if (Name.startswith(".note") && Name != ".note.GNU-stack")
  646. NewSection.Type = SHT_NOTE;
  647. return Error::success();
  648. };
  649. if (Error E = handleUserSection(Flag, AddSection))
  650. return E;
  651. }
  652. for (StringRef Flag : Config.UpdateSection) {
  653. auto UpdateSection = [&](StringRef Name, ArrayRef<uint8_t> Data) {
  654. return Obj.updateSection(Name, Data);
  655. };
  656. if (Error E = handleUserSection(Flag, UpdateSection))
  657. return E;
  658. }
  659. if (!Config.AddGnuDebugLink.empty())
  660. Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink,
  661. Config.GnuDebugLinkCRC32);
  662. // If the symbol table was previously removed, we need to create a new one
  663. // before adding new symbols.
  664. if (!Obj.SymbolTable && !Config.SymbolsToAdd.empty())
  665. if (Error E = Obj.addNewSymbolTable())
  666. return E;
  667. for (const NewSymbolInfo &SI : Config.SymbolsToAdd)
  668. addSymbol(Obj, SI, ELFConfig.NewSymbolVisibility);
  669. // --set-section-flags works with sections added by --add-section.
  670. if (!Config.SetSectionFlags.empty()) {
  671. for (auto &Sec : Obj.sections()) {
  672. const auto Iter = Config.SetSectionFlags.find(Sec.Name);
  673. if (Iter != Config.SetSectionFlags.end()) {
  674. const SectionFlagsUpdate &SFU = Iter->second;
  675. setSectionFlagsAndType(Sec, SFU.NewFlags);
  676. }
  677. }
  678. }
  679. if (ELFConfig.EntryExpr)
  680. Obj.Entry = ELFConfig.EntryExpr(Obj.Entry);
  681. return Error::success();
  682. }
  683. static Error writeOutput(const CommonConfig &Config, Object &Obj,
  684. raw_ostream &Out, ElfType OutputElfType) {
  685. std::unique_ptr<Writer> Writer =
  686. createWriter(Config, Obj, Out, OutputElfType);
  687. if (Error E = Writer->finalize())
  688. return E;
  689. return Writer->write();
  690. }
  691. Error objcopy::elf::executeObjcopyOnIHex(const CommonConfig &Config,
  692. const ELFConfig &ELFConfig,
  693. MemoryBuffer &In, raw_ostream &Out) {
  694. IHexReader Reader(&In);
  695. Expected<std::unique_ptr<Object>> Obj = Reader.create(true);
  696. if (!Obj)
  697. return Obj.takeError();
  698. const ElfType OutputElfType =
  699. getOutputElfType(Config.OutputArch.getValueOr(MachineInfo()));
  700. if (Error E = handleArgs(Config, ELFConfig, **Obj))
  701. return E;
  702. return writeOutput(Config, **Obj, Out, OutputElfType);
  703. }
  704. Error objcopy::elf::executeObjcopyOnRawBinary(const CommonConfig &Config,
  705. const ELFConfig &ELFConfig,
  706. MemoryBuffer &In,
  707. raw_ostream &Out) {
  708. BinaryReader Reader(&In, ELFConfig.NewSymbolVisibility);
  709. Expected<std::unique_ptr<Object>> Obj = Reader.create(true);
  710. if (!Obj)
  711. return Obj.takeError();
  712. // Prefer OutputArch (-O<format>) if set, otherwise fallback to BinaryArch
  713. // (-B<arch>).
  714. const ElfType OutputElfType =
  715. getOutputElfType(Config.OutputArch.getValueOr(MachineInfo()));
  716. if (Error E = handleArgs(Config, ELFConfig, **Obj))
  717. return E;
  718. return writeOutput(Config, **Obj, Out, OutputElfType);
  719. }
  720. Error objcopy::elf::executeObjcopyOnBinary(const CommonConfig &Config,
  721. const ELFConfig &ELFConfig,
  722. object::ELFObjectFileBase &In,
  723. raw_ostream &Out) {
  724. ELFReader Reader(&In, Config.ExtractPartition);
  725. Expected<std::unique_ptr<Object>> Obj =
  726. Reader.create(!Config.SymbolsToAdd.empty());
  727. if (!Obj)
  728. return Obj.takeError();
  729. // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input.
  730. const ElfType OutputElfType =
  731. Config.OutputArch ? getOutputElfType(Config.OutputArch.getValue())
  732. : getOutputElfType(In);
  733. if (Error E = handleArgs(Config, ELFConfig, **Obj))
  734. return createFileError(Config.InputFilename, std::move(E));
  735. if (Error E = writeOutput(Config, **Obj, Out, OutputElfType))
  736. return createFileError(Config.InputFilename, std::move(E));
  737. return Error::success();
  738. }