Object.cpp 7.5 KB

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