blob: ef3973e51aea4f56b78550feda4ab2041b3932d6 [file] [log] [blame]
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +00001//===- MachOObjcopy.cpp -----------------------------------------*- C++ -*-===//
2//
Chandler Carruth127252b2019-02-11 08:25:19 +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 Shaposhnikovd911ed12019-02-02 00:38:07 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "MachOObjcopy.h"
10#include "../CopyConfig.h"
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +000011#include "MachOReader.h"
12#include "MachOWriter.h"
Seiya Nuta4bc71012019-05-29 22:21:12 +000013#include "llvm/Support/Errc.h"
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +000014#include "llvm/Support/Error.h"
15
16namespace llvm {
17namespace objcopy {
18namespace macho {
19
Seiya Nuta4bc71012019-05-29 22:21:12 +000020using namespace object;
Seiya Nuta7f19dd12019-10-28 15:40:37 +090021using SectionPred = std::function<bool(const Section &Sec)>;
22
23static void removeSections(const CopyConfig &Config, Object &Obj) {
24 SectionPred RemovePred = [](const Section &) { return false; };
25
Seiya Nutabc118302019-11-15 12:37:55 +090026 if (!Config.ToRemove.empty()) {
27 RemovePred = [&Config, RemovePred](const Section &Sec) {
28 return Config.ToRemove.matches(Sec.CanonicalName);
29 };
30 }
31
Fangrui Song30ccee72019-11-18 15:25:04 -080032 if (Config.StripAll || Config.StripDebug) {
Seiya Nuta9bbf2a12019-10-31 13:51:11 +090033 // Remove all debug sections.
34 RemovePred = [RemovePred](const Section &Sec) {
35 if (Sec.Segname == "__DWARF")
36 return true;
37
38 return RemovePred(Sec);
39 };
40 }
41
Seiya Nuta7f19dd12019-10-28 15:40:37 +090042 if (!Config.OnlySection.empty()) {
Seiya Nutabc118302019-11-15 12:37:55 +090043 // Overwrite RemovePred because --only-section takes priority.
44 RemovePred = [&Config](const Section &Sec) {
Seiya Nuta7f19dd12019-10-28 15:40:37 +090045 return !Config.OnlySection.matches(Sec.CanonicalName);
46 };
47 }
48
49 return Obj.removeSections(RemovePred);
50}
Seiya Nuta4bc71012019-05-29 22:21:12 +000051
Seiya Nuta9bbf2a12019-10-31 13:51:11 +090052static void markSymbols(const CopyConfig &Config, Object &Obj) {
53 // Symbols referenced from the indirect symbol table must not be removed.
54 for (IndirectSymbolEntry &ISE : Obj.IndirectSymTable.Symbols)
55 if (ISE.Symbol)
56 (*ISE.Symbol)->Referenced = true;
57}
58
Fangrui Song28a5dc72019-11-13 13:10:15 -080059static void updateAndRemoveSymbols(const CopyConfig &Config, Object &Obj) {
60 for (SymbolEntry &Sym : Obj.SymTable) {
61 auto I = Config.SymbolsToRename.find(Sym.Name);
62 if (I != Config.SymbolsToRename.end())
63 Sym.Name = I->getValue();
64 }
65
Seiya Nuta9bbf2a12019-10-31 13:51:11 +090066 auto RemovePred = [Config](const std::unique_ptr<SymbolEntry> &N) {
67 if (N->Referenced)
68 return false;
69 return Config.StripAll;
70 };
71
72 Obj.SymTable.removeSymbols(RemovePred);
73}
74
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -080075static LoadCommand buildRPathLoadCommand(StringRef Path) {
76 LoadCommand LC;
77 MachO::rpath_command RPathLC;
78 RPathLC.cmd = MachO::LC_RPATH;
79 RPathLC.path = sizeof(MachO::rpath_command);
80 RPathLC.cmdsize = alignTo(sizeof(MachO::rpath_command) + Path.size(), 8);
81 LC.MachOLoadCommand.rpath_command_data = RPathLC;
82 LC.Payload.assign(RPathLC.cmdsize - sizeof(MachO::rpath_command), 0);
83 std::copy(Path.begin(), Path.end(), LC.Payload.begin());
84 return LC;
85}
86
Seiya Nutad72a8a42019-11-25 12:29:58 +090087static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
88 Object &Obj) {
89 for (LoadCommand &LC : Obj.LoadCommands)
90 for (Section &Sec : LC.Sections) {
91 if (Sec.CanonicalName == SecName) {
92 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
93 FileOutputBuffer::create(Filename, Sec.Content.size());
94 if (!BufferOrErr)
95 return BufferOrErr.takeError();
96 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
97 llvm::copy(Sec.Content, Buf->getBufferStart());
98
99 if (Error E = Buf->commit())
100 return E;
101 return Error::success();
102 }
103 }
104
105 return createStringError(object_error::parse_failed, "section '%s' not found",
106 SecName.str().c_str());
107}
108
Seiya Nuta4bc71012019-05-29 22:21:12 +0000109static Error handleArgs(const CopyConfig &Config, Object &Obj) {
110 if (Config.AllowBrokenLinks || !Config.BuildIdLinkDir.empty() ||
111 Config.BuildIdLinkInput || Config.BuildIdLinkOutput ||
112 !Config.SplitDWO.empty() || !Config.SymbolsPrefix.empty() ||
113 !Config.AllocSectionsPrefix.empty() || !Config.AddSection.empty() ||
Seiya Nutad72a8a42019-11-25 12:29:58 +0900114 !Config.KeepSection.empty() || Config.NewSymbolVisibility ||
115 !Config.SymbolsToGlobalize.empty() || !Config.SymbolsToKeep.empty() ||
116 !Config.SymbolsToLocalize.empty() || !Config.SymbolsToWeaken.empty() ||
117 !Config.SymbolsToKeepGlobal.empty() || !Config.SectionsToRename.empty() ||
Seiya Nuta4bc71012019-05-29 22:21:12 +0000118 !Config.UnneededSymbolsToRemove.empty() ||
Fangrui Song671fb342019-10-02 12:41:25 +0000119 !Config.SetSectionAlignment.empty() || !Config.SetSectionFlags.empty() ||
Seiya Nutabc118302019-11-15 12:37:55 +0900120 Config.ExtractDWO || Config.KeepFileSymbols || Config.LocalizeHidden ||
121 Config.PreserveDates || Config.StripAllGNU || Config.StripDWO ||
122 Config.StripNonAlloc || Config.StripSections || Config.Weaken ||
Fangrui Song30ccee72019-11-18 15:25:04 -0800123 Config.DecompressDebugSections || Config.StripNonAlloc ||
124 Config.StripSections || Config.StripUnneeded ||
Fangrui Song671fb342019-10-02 12:41:25 +0000125 Config.DiscardMode != DiscardType::None || !Config.SymbolsToAdd.empty() ||
126 Config.EntryExpr) {
Seiya Nuta4bc71012019-05-29 22:21:12 +0000127 return createStringError(llvm::errc::invalid_argument,
128 "option not supported by llvm-objcopy for MachO");
129 }
Seiya Nuta7f19dd12019-10-28 15:40:37 +0900130 removeSections(Config, Obj);
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900131
132 // Mark symbols to determine which symbols are still needed.
133 if (Config.StripAll)
134 markSymbols(Config, Obj);
135
Fangrui Song28a5dc72019-11-13 13:10:15 -0800136 updateAndRemoveSymbols(Config, Obj);
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900137
138 if (Config.StripAll)
139 for (LoadCommand &LC : Obj.LoadCommands)
140 for (Section &Sec : LC.Sections)
141 Sec.Relocations.clear();
142
Seiya Nutad72a8a42019-11-25 12:29:58 +0900143 for (const StringRef &Flag : Config.DumpSection) {
144 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
145 StringRef SecName = SecPair.first;
146 StringRef File = SecPair.second;
147 if (Error E = dumpSectionToFile(SecName, File, Obj))
148 return E;
149 }
150
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -0800151 for (StringRef RPath : Config.RPathToAdd) {
152 for (LoadCommand &LC : Obj.LoadCommands) {
153 if (LC.MachOLoadCommand.load_command_data.cmd == MachO::LC_RPATH &&
154 RPath == StringRef(reinterpret_cast<char *>(LC.Payload.data()),
155 LC.Payload.size())
156 .trim(0)) {
157 return createStringError(errc::invalid_argument,
158 "rpath " + RPath +
159 " would create a duplicate load command");
160 }
161 }
162 Obj.addLoadCommand(buildRPathLoadCommand(RPath));
163 }
Seiya Nuta4bc71012019-05-29 22:21:12 +0000164 return Error::success();
165}
166
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000167Error executeObjcopyOnBinary(const CopyConfig &Config,
168 object::MachOObjectFile &In, Buffer &Out) {
169 MachOReader Reader(In);
170 std::unique_ptr<Object> O = Reader.create();
Seiya Nuta4bc71012019-05-29 22:21:12 +0000171 if (!O)
172 return createFileError(
173 Config.InputFilename,
174 createStringError(object_error::parse_failed,
175 "unable to deserialize MachO object"));
176
177 if (Error E = handleArgs(Config, *O))
178 return createFileError(Config.InputFilename, std::move(E));
179
Seiya Nuta552bcb82019-08-19 21:05:31 +0000180 // TODO: Support 16KB pages which are employed in iOS arm64 binaries:
181 // https://github.com/llvm/llvm-project/commit/1bebb2832ee312d3b0316dacff457a7a29435edb
182 const uint64_t PageSize = 4096;
183
184 MachOWriter Writer(*O, In.is64Bit(), In.isLittleEndian(), PageSize, Out);
Seiya Nutab728e532019-06-08 01:22:54 +0000185 if (auto E = Writer.finalize())
186 return E;
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000187 return Writer.write();
188}
189
190} // end namespace macho
191} // end namespace objcopy
192} // end namespace llvm