blob: be44fdbe45f9540b18d5ba910664b97682dde716 [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;
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -080021using SectionPred = std::function<bool(const std::unique_ptr<Section> &Sec)>;
Seiya Nuta7f19dd12019-10-28 15:40:37 +090022
Alexander Shaposhnikovf34fdbc2020-04-22 14:26:28 -070023static Error removeSections(const CopyConfig &Config, Object &Obj) {
Alexander Shaposhnikova7abe8d2020-05-17 20:46:17 -070024 SectionPred RemovePred = [](const std::unique_ptr<Section> &) {
25 return false;
26 };
Seiya Nuta7f19dd12019-10-28 15:40:37 +090027
Seiya Nutabc118302019-11-15 12:37:55 +090028 if (!Config.ToRemove.empty()) {
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -080029 RemovePred = [&Config, RemovePred](const std::unique_ptr<Section> &Sec) {
30 return Config.ToRemove.matches(Sec->CanonicalName);
Seiya Nutabc118302019-11-15 12:37:55 +090031 };
32 }
33
Fangrui Song30ccee72019-11-18 15:25:04 -080034 if (Config.StripAll || Config.StripDebug) {
Seiya Nuta9bbf2a12019-10-31 13:51:11 +090035 // Remove all debug sections.
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -080036 RemovePred = [RemovePred](const std::unique_ptr<Section> &Sec) {
37 if (Sec->Segname == "__DWARF")
Seiya Nuta9bbf2a12019-10-31 13:51:11 +090038 return true;
39
40 return RemovePred(Sec);
41 };
42 }
43
Seiya Nuta7f19dd12019-10-28 15:40:37 +090044 if (!Config.OnlySection.empty()) {
Seiya Nutabc118302019-11-15 12:37:55 +090045 // Overwrite RemovePred because --only-section takes priority.
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -080046 RemovePred = [&Config](const std::unique_ptr<Section> &Sec) {
47 return !Config.OnlySection.matches(Sec->CanonicalName);
Seiya Nuta7f19dd12019-10-28 15:40:37 +090048 };
49 }
50
51 return Obj.removeSections(RemovePred);
52}
Seiya Nuta4bc71012019-05-29 22:21:12 +000053
Seiya Nuta9bbf2a12019-10-31 13:51:11 +090054static void markSymbols(const CopyConfig &Config, Object &Obj) {
55 // Symbols referenced from the indirect symbol table must not be removed.
56 for (IndirectSymbolEntry &ISE : Obj.IndirectSymTable.Symbols)
57 if (ISE.Symbol)
58 (*ISE.Symbol)->Referenced = true;
59}
60
Fangrui Song28a5dc72019-11-13 13:10:15 -080061static void updateAndRemoveSymbols(const CopyConfig &Config, Object &Obj) {
62 for (SymbolEntry &Sym : Obj.SymTable) {
63 auto I = Config.SymbolsToRename.find(Sym.Name);
64 if (I != Config.SymbolsToRename.end())
Benjamin Krameradcd0262020-01-28 20:23:46 +010065 Sym.Name = std::string(I->getValue());
Fangrui Song28a5dc72019-11-13 13:10:15 -080066 }
67
Seiya Nuta9bbf2a12019-10-31 13:51:11 +090068 auto RemovePred = [Config](const std::unique_ptr<SymbolEntry> &N) {
69 if (N->Referenced)
70 return false;
Alexander Shaposhnikovf79b81f2020-02-26 11:32:44 -080071 if (Config.StripAll)
72 return true;
73 if (Config.DiscardMode == DiscardType::All && !(N->n_type & MachO::N_EXT))
74 return true;
75 return false;
Seiya Nuta9bbf2a12019-10-31 13:51:11 +090076 };
77
78 Obj.SymTable.removeSymbols(RemovePred);
79}
80
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -080081static LoadCommand buildRPathLoadCommand(StringRef Path) {
82 LoadCommand LC;
83 MachO::rpath_command RPathLC;
84 RPathLC.cmd = MachO::LC_RPATH;
85 RPathLC.path = sizeof(MachO::rpath_command);
86 RPathLC.cmdsize = alignTo(sizeof(MachO::rpath_command) + Path.size(), 8);
87 LC.MachOLoadCommand.rpath_command_data = RPathLC;
88 LC.Payload.assign(RPathLC.cmdsize - sizeof(MachO::rpath_command), 0);
89 std::copy(Path.begin(), Path.end(), LC.Payload.begin());
90 return LC;
91}
92
Seiya Nutad72a8a42019-11-25 12:29:58 +090093static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
94 Object &Obj) {
95 for (LoadCommand &LC : Obj.LoadCommands)
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -080096 for (const std::unique_ptr<Section> &Sec : LC.Sections) {
97 if (Sec->CanonicalName == SecName) {
Seiya Nutad72a8a42019-11-25 12:29:58 +090098 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -080099 FileOutputBuffer::create(Filename, Sec->Content.size());
Seiya Nutad72a8a42019-11-25 12:29:58 +0900100 if (!BufferOrErr)
101 return BufferOrErr.takeError();
102 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -0800103 llvm::copy(Sec->Content, Buf->getBufferStart());
Seiya Nutad72a8a42019-11-25 12:29:58 +0900104
105 if (Error E = Buf->commit())
106 return E;
107 return Error::success();
108 }
109 }
110
111 return createStringError(object_error::parse_failed, "section '%s' not found",
112 SecName.str().c_str());
113}
114
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900115static Error addSection(StringRef SecName, StringRef Filename, Object &Obj) {
116 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
117 MemoryBuffer::getFile(Filename);
118 if (!BufOrErr)
119 return createFileError(Filename, errorCodeToError(BufOrErr.getError()));
120 std::unique_ptr<MemoryBuffer> Buf = std::move(*BufOrErr);
121
122 std::pair<StringRef, StringRef> Pair = SecName.split(',');
123 StringRef TargetSegName = Pair.first;
124 Section Sec(TargetSegName, Pair.second);
125 Sec.Content = Obj.NewSectionsContents.save(Buf->getBuffer());
126
127 // Add the a section into an existing segment.
128 for (LoadCommand &LC : Obj.LoadCommands) {
129 Optional<StringRef> SegName = LC.getSegmentName();
130 if (SegName && SegName == TargetSegName) {
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -0800131 LC.Sections.push_back(std::make_unique<Section>(Sec));
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900132 return Error::success();
133 }
134 }
135
136 // There's no segment named TargetSegName. Create a new load command and
137 // Insert a new section into it.
138 LoadCommand &NewSegment = Obj.addSegment(TargetSegName);
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -0800139 NewSegment.Sections.push_back(std::make_unique<Section>(Sec));
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900140 return Error::success();
141}
142
143// isValidMachOCannonicalName returns success if Name is a MachO cannonical name
144// ("<segment>,<section>") and lengths of both segment and section names are
145// valid.
146Error isValidMachOCannonicalName(StringRef Name) {
147 if (Name.count(',') != 1)
148 return createStringError(errc::invalid_argument,
149 "invalid section name '%s' (should be formatted "
150 "as '<segment name>,<section name>')",
151 Name.str().c_str());
152
153 std::pair<StringRef, StringRef> Pair = Name.split(',');
154 if (Pair.first.size() > 16)
155 return createStringError(errc::invalid_argument,
156 "too long segment name: '%s'",
157 Pair.first.str().c_str());
158 if (Pair.second.size() > 16)
159 return createStringError(errc::invalid_argument,
160 "too long section name: '%s'",
161 Pair.second.str().c_str());
162 return Error::success();
163}
164
Seiya Nuta4bc71012019-05-29 22:21:12 +0000165static Error handleArgs(const CopyConfig &Config, Object &Obj) {
166 if (Config.AllowBrokenLinks || !Config.BuildIdLinkDir.empty() ||
167 Config.BuildIdLinkInput || Config.BuildIdLinkOutput ||
168 !Config.SplitDWO.empty() || !Config.SymbolsPrefix.empty() ||
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900169 !Config.AllocSectionsPrefix.empty() || !Config.KeepSection.empty() ||
170 Config.NewSymbolVisibility || !Config.SymbolsToGlobalize.empty() ||
171 !Config.SymbolsToKeep.empty() || !Config.SymbolsToLocalize.empty() ||
172 !Config.SymbolsToWeaken.empty() || !Config.SymbolsToKeepGlobal.empty() ||
173 !Config.SectionsToRename.empty() ||
Seiya Nuta4bc71012019-05-29 22:21:12 +0000174 !Config.UnneededSymbolsToRemove.empty() ||
Fangrui Song671fb342019-10-02 12:41:25 +0000175 !Config.SetSectionAlignment.empty() || !Config.SetSectionFlags.empty() ||
Fangrui Songb14e9e32020-03-24 15:38:48 +0800176 Config.ExtractDWO || Config.LocalizeHidden || Config.PreserveDates ||
177 Config.StripAllGNU || Config.StripDWO || Config.StripNonAlloc ||
178 Config.StripSections || Config.Weaken || Config.DecompressDebugSections ||
179 Config.StripNonAlloc || Config.StripSections || Config.StripUnneeded ||
Alexander Shaposhnikovf79b81f2020-02-26 11:32:44 -0800180 Config.DiscardMode == DiscardType::Locals ||
181 !Config.SymbolsToAdd.empty() || Config.EntryExpr) {
Seiya Nuta4bc71012019-05-29 22:21:12 +0000182 return createStringError(llvm::errc::invalid_argument,
183 "option not supported by llvm-objcopy for MachO");
184 }
Alexander Shaposhnikovf34fdbc2020-04-22 14:26:28 -0700185
186 if (Error E = removeSections(Config, Obj))
187 return E;
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900188
189 // Mark symbols to determine which symbols are still needed.
190 if (Config.StripAll)
191 markSymbols(Config, Obj);
192
Fangrui Song28a5dc72019-11-13 13:10:15 -0800193 updateAndRemoveSymbols(Config, Obj);
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900194
195 if (Config.StripAll)
196 for (LoadCommand &LC : Obj.LoadCommands)
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -0800197 for (std::unique_ptr<Section> &Sec : LC.Sections)
198 Sec->Relocations.clear();
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900199
Seiya Nutad72a8a42019-11-25 12:29:58 +0900200 for (const StringRef &Flag : Config.DumpSection) {
201 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
202 StringRef SecName = SecPair.first;
203 StringRef File = SecPair.second;
204 if (Error E = dumpSectionToFile(SecName, File, Obj))
205 return E;
206 }
207
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900208 for (const auto &Flag : Config.AddSection) {
209 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
210 StringRef SecName = SecPair.first;
211 StringRef File = SecPair.second;
212 if (Error E = isValidMachOCannonicalName(SecName))
213 return E;
214 if (Error E = addSection(SecName, File, Obj))
215 return E;
216 }
217
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -0800218 for (StringRef RPath : Config.RPathToAdd) {
219 for (LoadCommand &LC : Obj.LoadCommands) {
220 if (LC.MachOLoadCommand.load_command_data.cmd == MachO::LC_RPATH &&
221 RPath == StringRef(reinterpret_cast<char *>(LC.Payload.data()),
222 LC.Payload.size())
223 .trim(0)) {
224 return createStringError(errc::invalid_argument,
225 "rpath " + RPath +
226 " would create a duplicate load command");
227 }
228 }
229 Obj.addLoadCommand(buildRPathLoadCommand(RPath));
230 }
Seiya Nuta4bc71012019-05-29 22:21:12 +0000231 return Error::success();
232}
233
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000234Error executeObjcopyOnBinary(const CopyConfig &Config,
235 object::MachOObjectFile &In, Buffer &Out) {
236 MachOReader Reader(In);
237 std::unique_ptr<Object> O = Reader.create();
Seiya Nuta4bc71012019-05-29 22:21:12 +0000238 if (!O)
239 return createFileError(
240 Config.InputFilename,
241 createStringError(object_error::parse_failed,
242 "unable to deserialize MachO object"));
243
244 if (Error E = handleArgs(Config, *O))
245 return createFileError(Config.InputFilename, std::move(E));
246
Seiya Nuta552bcb82019-08-19 21:05:31 +0000247 // TODO: Support 16KB pages which are employed in iOS arm64 binaries:
248 // https://github.com/llvm/llvm-project/commit/1bebb2832ee312d3b0316dacff457a7a29435edb
249 const uint64_t PageSize = 4096;
250
251 MachOWriter Writer(*O, In.is64Bit(), In.isLittleEndian(), PageSize, Out);
Seiya Nutab728e532019-06-08 01:22:54 +0000252 if (auto E = Writer.finalize())
253 return E;
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000254 return Writer.write();
255}
256
257} // end namespace macho
258} // end namespace objcopy
259} // end namespace llvm