Object.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. //===- Object.cpp - Mach-O object file model --------------------*- C++ -*-===//
  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 "Object.h"
  9. #include "llvm/ADT/SmallPtrSet.h"
  10. #include <unordered_set>
  11. using namespace llvm;
  12. using namespace llvm::objcopy::macho;
  13. Section::Section(StringRef SegName, StringRef SectName)
  14. : Segname(std::string(SegName)), Sectname(std::string(SectName)),
  15. CanonicalName((Twine(SegName) + Twine(',') + SectName).str()) {}
  16. Section::Section(StringRef SegName, StringRef SectName, StringRef Content)
  17. : Segname(std::string(SegName)), Sectname(std::string(SectName)),
  18. CanonicalName((Twine(SegName) + Twine(',') + SectName).str()),
  19. Content(Content) {}
  20. const SymbolEntry *SymbolTable::getSymbolByIndex(uint32_t Index) const {
  21. assert(Index < Symbols.size() && "invalid symbol index");
  22. return Symbols[Index].get();
  23. }
  24. SymbolEntry *SymbolTable::getSymbolByIndex(uint32_t Index) {
  25. return const_cast<SymbolEntry *>(
  26. static_cast<const SymbolTable *>(this)->getSymbolByIndex(Index));
  27. }
  28. void SymbolTable::removeSymbols(
  29. function_ref<bool(const std::unique_ptr<SymbolEntry> &)> ToRemove) {
  30. llvm::erase_if(Symbols, ToRemove);
  31. }
  32. void Object::updateLoadCommandIndexes() {
  33. static constexpr char TextSegmentName[] = "__TEXT";
  34. // Update indices of special load commands
  35. for (size_t Index = 0, Size = LoadCommands.size(); Index < Size; ++Index) {
  36. LoadCommand &LC = LoadCommands[Index];
  37. switch (LC.MachOLoadCommand.load_command_data.cmd) {
  38. case MachO::LC_CODE_SIGNATURE:
  39. CodeSignatureCommandIndex = Index;
  40. break;
  41. case MachO::LC_SEGMENT:
  42. if (StringRef(LC.MachOLoadCommand.segment_command_data.segname) ==
  43. TextSegmentName)
  44. TextSegmentCommandIndex = Index;
  45. break;
  46. case MachO::LC_SEGMENT_64:
  47. if (StringRef(LC.MachOLoadCommand.segment_command_64_data.segname) ==
  48. TextSegmentName)
  49. TextSegmentCommandIndex = Index;
  50. break;
  51. case MachO::LC_SYMTAB:
  52. SymTabCommandIndex = Index;
  53. break;
  54. case MachO::LC_DYSYMTAB:
  55. DySymTabCommandIndex = Index;
  56. break;
  57. case MachO::LC_DYLD_INFO:
  58. case MachO::LC_DYLD_INFO_ONLY:
  59. DyLdInfoCommandIndex = Index;
  60. break;
  61. case MachO::LC_DATA_IN_CODE:
  62. DataInCodeCommandIndex = Index;
  63. break;
  64. case MachO::LC_LINKER_OPTIMIZATION_HINT:
  65. LinkerOptimizationHintCommandIndex = Index;
  66. break;
  67. case MachO::LC_FUNCTION_STARTS:
  68. FunctionStartsCommandIndex = Index;
  69. break;
  70. case MachO::LC_DYLD_CHAINED_FIXUPS:
  71. ChainedFixupsCommandIndex = Index;
  72. break;
  73. case MachO::LC_DYLD_EXPORTS_TRIE:
  74. ExportsTrieCommandIndex = Index;
  75. break;
  76. }
  77. }
  78. }
  79. Error Object::removeLoadCommands(
  80. function_ref<bool(const LoadCommand &)> ToRemove) {
  81. auto It = std::stable_partition(
  82. LoadCommands.begin(), LoadCommands.end(),
  83. [&](const LoadCommand &LC) { return !ToRemove(LC); });
  84. LoadCommands.erase(It, LoadCommands.end());
  85. updateLoadCommandIndexes();
  86. return Error::success();
  87. }
  88. Error Object::removeSections(
  89. function_ref<bool(const std::unique_ptr<Section> &)> ToRemove) {
  90. DenseMap<uint32_t, const Section *> OldIndexToSection;
  91. uint32_t NextSectionIndex = 1;
  92. for (LoadCommand &LC : LoadCommands) {
  93. auto It = std::stable_partition(
  94. std::begin(LC.Sections), std::end(LC.Sections),
  95. [&](const std::unique_ptr<Section> &Sec) { return !ToRemove(Sec); });
  96. for (auto I = LC.Sections.begin(), End = It; I != End; ++I) {
  97. OldIndexToSection[(*I)->Index] = I->get();
  98. (*I)->Index = NextSectionIndex++;
  99. }
  100. LC.Sections.erase(It, LC.Sections.end());
  101. }
  102. auto IsDead = [&](const std::unique_ptr<SymbolEntry> &S) -> bool {
  103. Optional<uint32_t> Section = S->section();
  104. return (Section && !OldIndexToSection.count(*Section));
  105. };
  106. SmallPtrSet<const SymbolEntry *, 2> DeadSymbols;
  107. for (const std::unique_ptr<SymbolEntry> &Sym : SymTable.Symbols)
  108. if (IsDead(Sym))
  109. DeadSymbols.insert(Sym.get());
  110. for (const LoadCommand &LC : LoadCommands)
  111. for (const std::unique_ptr<Section> &Sec : LC.Sections)
  112. for (const RelocationInfo &R : Sec->Relocations)
  113. if (R.Symbol && *R.Symbol && DeadSymbols.count(*R.Symbol))
  114. return createStringError(std::errc::invalid_argument,
  115. "symbol '%s' defined in section with index "
  116. "'%u' cannot be removed because it is "
  117. "referenced by a relocation in section '%s'",
  118. (*R.Symbol)->Name.c_str(),
  119. *((*R.Symbol)->section()),
  120. Sec->CanonicalName.c_str());
  121. SymTable.removeSymbols(IsDead);
  122. for (std::unique_ptr<SymbolEntry> &S : SymTable.Symbols)
  123. if (S->section())
  124. S->n_sect = OldIndexToSection[S->n_sect]->Index;
  125. return Error::success();
  126. }
  127. uint64_t Object::nextAvailableSegmentAddress() const {
  128. uint64_t HeaderSize =
  129. is64Bit() ? sizeof(MachO::mach_header_64) : sizeof(MachO::mach_header);
  130. uint64_t Addr = HeaderSize + Header.SizeOfCmds;
  131. for (const LoadCommand &LC : LoadCommands) {
  132. const MachO::macho_load_command &MLC = LC.MachOLoadCommand;
  133. switch (MLC.load_command_data.cmd) {
  134. case MachO::LC_SEGMENT:
  135. Addr = std::max(Addr,
  136. static_cast<uint64_t>(MLC.segment_command_data.vmaddr) +
  137. MLC.segment_command_data.vmsize);
  138. break;
  139. case MachO::LC_SEGMENT_64:
  140. Addr = std::max(Addr, MLC.segment_command_64_data.vmaddr +
  141. MLC.segment_command_64_data.vmsize);
  142. break;
  143. default:
  144. continue;
  145. }
  146. }
  147. return Addr;
  148. }
  149. template <typename SegmentType>
  150. static void
  151. constructSegment(SegmentType &Seg, llvm::MachO::LoadCommandType CmdType,
  152. StringRef SegName, uint64_t SegVMAddr, uint64_t SegVMSize) {
  153. assert(SegName.size() <= sizeof(Seg.segname) && "too long segment name");
  154. memset(&Seg, 0, sizeof(SegmentType));
  155. Seg.cmd = CmdType;
  156. strncpy(Seg.segname, SegName.data(), SegName.size());
  157. Seg.maxprot |=
  158. (MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE);
  159. Seg.initprot |=
  160. (MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE);
  161. Seg.vmaddr = SegVMAddr;
  162. Seg.vmsize = SegVMSize;
  163. }
  164. LoadCommand &Object::addSegment(StringRef SegName, uint64_t SegVMSize) {
  165. LoadCommand LC;
  166. const uint64_t SegVMAddr = nextAvailableSegmentAddress();
  167. if (is64Bit())
  168. constructSegment(LC.MachOLoadCommand.segment_command_64_data,
  169. MachO::LC_SEGMENT_64, SegName, SegVMAddr, SegVMSize);
  170. else
  171. constructSegment(LC.MachOLoadCommand.segment_command_data,
  172. MachO::LC_SEGMENT, SegName, SegVMAddr, SegVMSize);
  173. LoadCommands.push_back(std::move(LC));
  174. return LoadCommands.back();
  175. }
  176. /// Extracts a segment name from a string which is possibly non-null-terminated.
  177. static StringRef extractSegmentName(const char *SegName) {
  178. return StringRef(SegName,
  179. strnlen(SegName, sizeof(MachO::segment_command::segname)));
  180. }
  181. Optional<StringRef> LoadCommand::getSegmentName() const {
  182. const MachO::macho_load_command &MLC = MachOLoadCommand;
  183. switch (MLC.load_command_data.cmd) {
  184. case MachO::LC_SEGMENT:
  185. return extractSegmentName(MLC.segment_command_data.segname);
  186. case MachO::LC_SEGMENT_64:
  187. return extractSegmentName(MLC.segment_command_64_data.segname);
  188. default:
  189. return None;
  190. }
  191. }
  192. Optional<uint64_t> LoadCommand::getSegmentVMAddr() const {
  193. const MachO::macho_load_command &MLC = MachOLoadCommand;
  194. switch (MLC.load_command_data.cmd) {
  195. case MachO::LC_SEGMENT:
  196. return MLC.segment_command_data.vmaddr;
  197. case MachO::LC_SEGMENT_64:
  198. return MLC.segment_command_64_data.vmaddr;
  199. default:
  200. return None;
  201. }
  202. }