ELFObjcopy.cpp 30 KB

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